diff --git a/.gitignore b/.gitignore index ef79db8f2..3ec532e83 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,14 @@ -*.checkstyle -*.swp -.project -.settings -target/ -*/.settings -*/.classpath -*/.project -.metadata -.idea -*.iml -.checkstyle -dependency-reduced-pom.xml -*/bin +*.checkstyle +*.swp +.project +.settings +target/ +*/.settings +*/.classpath +*/.project +.metadata +.idea +*.iml +.checkstyle +dependency-reduced-pom.xml +*/bin diff --git a/.travis.yml b/.travis.yml index 5fb4b7178..f0b56ceef 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,25 +1,25 @@ -sudo: false - -language: java - -jdk: - - oraclejdk8 - - oraclejdk9 - -env: - global: - # taken first download mirror from http://maven.apache.org/ - - BASEURL=http://mirror.softaculous.com/apache/maven/maven-3/VERSION/binaries/apache-maven-VERSION-bin.tar.gz - - FILE=apache-maven-VERSION-bin.tar.gz - - DIR=apache-maven-VERSION/bin - matrix: - - VERSION=3.3.9 - - VERSION=3.2.5 - - VERSION=3.1.1 - - VERSION=3.0.5 - -script: - - wget $(echo -n $BASEURL | sed -e 's#VERSION#'$VERSION'#g') - - tar -xvzf $(echo -n $FILE | sed -e 's#VERSION#'$VERSION'#') - - export PATH=$(echo -n $DIR | sed -e 's#VERSION#'$VERSION'#'):$PATH - - mvn clean verify +sudo: false + +language: java + +jdk: + - oraclejdk8 + - oraclejdk9 + +env: + global: + # taken first download mirror from http://maven.apache.org/ + - BASEURL=http://mirror.softaculous.com/apache/maven/maven-3/VERSION/binaries/apache-maven-VERSION-bin.tar.gz + - FILE=apache-maven-VERSION-bin.tar.gz + - DIR=apache-maven-VERSION/bin + matrix: + - VERSION=3.3.9 + - VERSION=3.2.5 + - VERSION=3.1.1 + - VERSION=3.0.5 + +script: + - wget $(echo -n $BASEURL | sed -e 's#VERSION#'$VERSION'#g') + - tar -xvzf $(echo -n $FILE | sed -e 's#VERSION#'$VERSION'#') + - export PATH=$(echo -n $DIR | sed -e 's#VERSION#'$VERSION'#'):$PATH + - mvn clean verify diff --git a/LICENSE.txt b/LICENSE.txt index d64569567..75b52484e 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,202 +1,202 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index bc018685f..f57dd26fa 100644 --- a/README.md +++ b/README.md @@ -1,376 +1,62 @@ + [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.pitest/pitest/badge.svg?style=flat)](https://maven-badges.herokuapp.com/maven-central/org.pitest/pitest) [![Build Status](https://travis-ci.org/hcoles/pitest.png?branch=master)](https://travis-ci.org/hcoles/pitest) +# CS6367 - Pitest Improvement Project -Pitest (aka PIT) is a state of the art mutation testing system for Java and the JVM. - -Read all about it at http://pitest.org - -## Releases - -### 1.4.0-SNAPSHOT - -* #445 - Raise minimum supported java version to 8 - -### 1.3.2 - -* #433 - Aggregate reports via maven (thanks @rchargel) -* #438 - Filter tests at method level (thanks @ftrautsch) -* #439 - Primitives return mutator doesn't handle bytes -* #380 - Remove reliance on xstream for improved java 9 support -* #414 - Replace xstream history store (thanks @kiftio) - -Note when upgrading that history files generated by previous releases are not compatible with 1.3.2 an above. - -### 1.3.1 - -* #434 - XStream security warning - -### 1.3.0 - -* #196 - Raise minimum java version to 7 -* #425 - Broaden for-each detection -* #428 - Add `excludedTestClasses` parameter -* #379 - Remove support for mutating static initializers -* #432 - Add export plugin functionality into pitest -* #427 - Better return values mutators -* #429 - Simplify test api - -428 changes the existing behaviour of the excludedClasses filter. Previously this excluded classes from both being mutated and run as tests which may require changes for some people when upgrading. - -As a result of 429 TestNG tests will no longer be automatically detected - the new `testPlugin` parameter must be explicitly set to "testng". - -### 1.2.5 - -* #407 - SCM goal cannot be run from within module (thanks @sbuisson) -* #256 - Inline style violate Content Security Policy (thanks @kiftio) -* #403 - No css in the html report viewed from jenkins (thanks @kiftio) -* #409 - Mutate based on changes across branched (thanks @sbuisson) -* #418 - Avoid for loop increments -* #424 - Avoid for each code -* #389 - Widen matching of implicit null checks - -### 1.2.4 - -* #397 - Report reasons maven modules skipped -* #389 - Filter junk getClass null checks in lambdas -* #400 - Update to ASM 6.0 - -### 1.2.3 - -* Update to ASM 6 for Java 9 support -* #388 - Mark maven plugin as threadsafe -* #362 - Suppress common equivalent mutant in equals methods - -### 1.2.2 - -* #367 - Static analysis cannot find core classes in some projects - -### 1.2.1 - -* #347 - Avoid autogenerated code (e.g by lombok) anotated with @Generated -* #285 - Avoid compiler generated conditionals in switch on string. (thanks @Kwaq) -* #218 - New "naked receiver" / method chain mutator. (thanks @UrsMetz) -* #354/#356 - New extension point plus changes to reduce cost of random access to bytecode for static analysis -* #353 - Improved static initializer code detection -* #364 - Filter infinite loops via static analysis -* #365 - Configuration system for plugins - -(Note #347 will **not** detect `javax.annotaion.Generated` as it has only source retention.) - -### 1.2.0 - -* #318 - Separate main process code from code sharing client classpath -* #295 - Ignore abstract TestNG tests -* #215 - Automatic selection of target classes for maven -* #314 - Do not fail for maven modules without tests or code -* #306 - Do not fail when only interfaces are in changeset -* #325 - Anonymous class in Spock test causing error -* #334 - Compatibility with recent TestNG releases -* #335 - Incorrect coverage with powermock - -Note - as of this release the maven plugin will automatically determine which classes to mutate instead of assuming that the package names match the group id. - -### 1.1.11 - -* #269 - Not possible to break build on 1 mutant -* #271 - Include method descriptor in line coverage -* #170 - Exclusion by JUnit runner -* #291 - Handle empty excludes -* #287 - Check class hierarchy for annotations -* #289 - Option to supply classpath from file - - -### 1.1.10 - -* #260 - Initial support for mutating Kotlin code -* #264 - Support for yatspec runner (thanks @theangrydev) -* Break build when more than `maxSurviving` mutants survive - -### 1.1.9 - -* #132 - Allow analysis of only files touched in last commit (thanks Tomasz Luch) - -### 1.1.8 - -* #239 - Provide a shortcut to set history files via maven -* #240 - Support for regexes (thanks sebi-hgdata) -* #243 - Use ephemeral ports to communicate with minions - -### 1.1.7 - -* #196 - Raise minimum java version to 1.6 -* #231 - Process hangs - -### 1.1.6 - -* #10 - Add maven report goal (thanks jasonmfehr) -* #184 - Remove undocumented project file feature -* #219 - Performance improvement for report generation (thanks tobiasbaum) -* #190 - Allow custom properties for plugins - -Note this release contains a known issue (#231). Please upgrade. - -### 1.1.5 - -* Fix for #148 - Stackoverflow with TestNG data providers when using JMockit -* Fix for #56 - Not reporting junit incompatibilities -* Fix for #174 - Invalid linecoverage.xml with static initializers -* Fix for #183 - Can't run GWTMockito tests -* Fix for #179 - Broken `includeLaunchClasspath=false` on Windows -* #173 - Read exclusions and groups from maven surefire config - -### 1.1.4 - -* #157 - Support maven -DskipTests flag (thanks lkwg82) -* Fix for #163 - Should not include test tree in coverage threshold -* #166 - Allow classpath exclusions for maven plugin (thanks TomRK1089) -* #155 - Restore Java 5 compatibility -* Fix for #148 - Issue with JMockit + TestNG (thanks estekhin and KyleRogers) - -### 1.1.3 - -* Fix for #158 - Tests incorrectly excluded from mutants -* Fix for #153 - SCM plugin broken for maven 2 -* Fix for #152 - Does not work with IBM jdk - -### 1.1.2 - -* Fix for #150 - line coverage under reported - -### 1.1.1 - -* Block based coverage (fixes 79/131) -* End support for running on Java 5 (java 5 bytecode still supported) -* Skip flag for maven modules (#106) -* Stop declaring TestNG as a dependency -* New parameter propagation mutator (thanks UrsMetz) +## Project Summary -### 1.1.0 +This project aims at adding more mutations to Pitest and use it to help fixing errors. The first phase involves implementing the AOD, ROR and AOR mutations. The second phase will implement even more mutations and add code fixing rules. (treated as mutators) -* Change scheme for identifying mutants (see https://github.com/hcoles/pitest/issues/125) -* Support alternate test apis via plugin system -* Report error when supplied mutator name does not match (thanks artspb) -* Report exit codes from coverage child process (thanks KyleRogers) -* Treat JUnit tests with ClassRule annotation as one unit (thanks devmop) +## How to run -Please note that any stored history files or sonar results are invalidated by this release. - -### 1.0.0 - -* Switch version numbering scheme -* Upgrade to ASM 5.0.2 -* Fix for #114 - fails to run for java 8 when -parameters flag is set -* #99 Support additionalClasspathElements property in maven plugin (thanks artspb) -* #98 Do not mutate java 7 try with resources (thanks @artspb) -* #109 extended remove conditional mutator (thanks @vrthra) - - -### 0.33 - -* Move to Github -* Upgrade of ASM to support Java 8 bytecode (thanks to "iirekm") -* Partial support for JUnit categories (thanks to "chrisr") -* New Remove Increments Mutator (thanks to Rahul Gopinath) -* Minor logging improvements (thanks to Kyle Rogers aka Stephan Penndorf) -* Fix for #92 - broken maven 2 support -* Fix for #75 - incorrectly ignored tests in classes with both @Ignore and @BeforeClass / @AfterClass - -### 0.32 - -* restores java 7 compatibility -* new remove conditionals mutator -* support for mutating static initializers with TestNG -* properly isolate classpaths when running via Ant -* break builds on coverage threshold -* allow JVM to be specified -* support user defined test selection strategies -* support user defined output format -* support user defined test prioritisation -* fix for issue blocking usage with [Robolectric](http://robolectric.org/) - -Note, setup for Ant based projects changes in this release. See [ant setup](http://pitest.org/quickstart/ant/) for details on usage. - -### 0.31 - -* Maven 2 compatibility restored -* Much faster line coverage calculation -* Fix for #78 - Error when PowerMockito test stores mock as member - -This release also changes a number of internal implementation details, some of which may be of interest/importance to those maintaining tools that -integrate with PIT. - -Mutations are now scoped internally as described in [https://groups.google.com/forum/#!topic/pitusers/E0-3QZuMYjE](https://groups.google.com/forum/#!topic/pitusers/E0-3QZuMYjE) - -A new class (org.pitest.mutationtest.tooling.EntryPoint) has been introduced that removes some of the duplication that existed in the various ways of launching mutation analysis. - -### 0.30 - -* Support for parametrized [Spock](http://code.google.com/p/spock/) tests -* Support for [JUnitParams](http://code.google.com/p/junitparams/) tests -* Fix for #73 - JUnit parameterised tests calling mutee during setup failing during mutation phase -* Fix to #63 - ant task fails when empty options supplied -* Ability to override maven options from command line -* Ability to fail a build if it does not achieve a given mutation score -* Performance improvement when tests use @BeforeClass or @AfterClass annotations -* Slightly improved scheduling over multiple threads -* Improved maven multi project support -* Integration with source control for maven users - - -### 0.29 - -* Incremental analysis (--historyInputLocation and --historyOutputLocation) -* Inlined code detection turned on by default -* Quieter loggging by default -* Improved Java 7 support -* Upgrade of ASM from 3.3 to 4 -* Fix for concurrency issues during coverage collection -* Fix for #53 - problems with snapshot junit versions -* Fix for #59 - duplicate dependencies set via maven - - -### 0.28 - -* Inlined finally block detection (--detectInlinedCode) -* New experimental switch statement mutator (contributed by Chris Rimmer) -* Do not mutate Groovy classes -* Fix for #33 - set user.dir to match surefire -* Fix for #43 - optionally suppress timestamped folders (--timestampedReports=true/false) -* Fix for #44 - concurrent modification exception when gathering coverage -* Fix for #46 - incorrect setting of flags by ant task -* Smaller memory footprint for main process -* Faster coverage gathering for large codebases -* Faster classpath scanning for large codebases -* Support for JUnit 3 suite methods -* Fixes for incorrect detection of JUnit 3 tests - -**Known issue** - Fix for #33 may not resolve issue for maven 2 users. - -Detection of Groovy code has not yet been tested with Groovy 2 which may generate substantially different -byte code to earlier versions. - -### 0.27 - -* Much prettier reports -* Now avoids mutating assert statements -* Removed inScopeClasses option - use targetClasses and targetTests instead -* Fix for 100% CPU usage when child JVM crashes -* Fix for #35 #38 - experimental member variable mutator now corrects stack -* Fix for #39 - order of classpath elements now maintained when running from maven - -**Upgrading users may need to modify their build due to removal of the inScopeClasses parameter** - -### 0.26 - -* Ant support -* New experimental mutator for member variables -* Fix for #12 #27 - no longer hangs when code under test launches non daemon threads -* Fix for #26 - now warns when no test library found on classpath -* Fix for #30 - now errors if mutated classes have no line or source debug -* Fix for #32 - now correctly handles of JUnit assumptions - -**Known issue** - The new member variable mutator may cause errors in synchronized errors. The mutator is -however disabled by default, and the generated errors are correctly handled by PIT. - -### 0.25 - -* TestNG support (experimental) -* Fix for issue where mutations in nested classes not isolated from each other -* Fix for broken classpath isolation for projects using xstream -* Improved handling of JUnit parametrized tests -* Ability to limit mutations to specific classpath roots (--mutableCodePaths) -* Ability to add non launch classpath roots (--classPath) (experimental) -* Read configuration values from XML (experimental) -* Option to not throw error when no mutations found -* Consistent ordering of classes in HTML report -* Statistics written to console -* Classes no longer loaded during initial classpath scanning -* New syntax to easily enable all mutation operations - -### 0.24 - -* JMockit support -* Option to output results in XML or CSV -* Fix for #11 -* Improved INLINE_CONSTS mutator - -### 0.23 - -* Fix for issue 7 - source files not located - -### 0.22 - -* Upgrade of Xstream to 1.4.1 to enable OpenJDK 7 support -* Fix for #5 - corruption of newline character in child processes -* Ability to set child process launch arguments - -### 0.21 - -* Significant performance improvements -* Support for powermock via both classloader (requires PowerMockIgnore annotation) and java agent -* Minor error reporting and usability improvements -* Fix for major defect around dependency analysis -* PIT dependencies no longer placed on classpath when running via maven -* Support for excluding certain classes or tests -* Support for verbose logging - -### 0.20 - -* Limit number of mutations per class -* Upgrade xstream to 1.3.1 -* Make available from maven central - -### 0.19 - -* Built in enum methods now excluded from mutation -* Fixed bug around reporting of untested classes -* Support for excluding tests greater than a certain distance from class -* Support for excluding methods from mutation analysis -* Performance improvements -* Removed support for launching mutation reports from JUnit runner - -### 0.18 - -* First public release - -## Credits - -Pitest is mainly the work of [me](https://twitter.com/0hjc) but has benefited from contributions from many others. - -Notable contributions not visible [here](https://github.com/hcoles/pitest/graphs/contributors) as they were made before this code was migrated to github include - -* Nicolas Rusconi - Ant Task -* Struan Kerr-Liddell - Improvements to html report -* Stephan Pendorf - Multiple improvments including improved mutators + 1. Please clone our project and compile it in maven: `mvn install -DskipTests` (doing it without -Dskiptests is fine as well. + 2. Location of the compiled jar files: `C:\Users\\[User Account Name\]\.m2\repository\org\pitest\pitest\` + 3. As of this implementation, the pitest version is 1.4.0-SNAPSHOT. + 4. Then add the following section to pom.xml and test using this command: -Although PIT does not incorporate any code from the Jumble project (http://jumble.sourceforge.net/), the Jumble codebase was used as a guide when developing some aspects of PIT. - -## Other stuff - -The codebase is checked up on in a few places that give slower feedback than the github hooks. + mvn org.pitest:pitest-maven:mutationCoverage + + + + + + org.pitest + pitest-maven + 1.4.0-SNAPSHOT + + + DEFAULTS + AOD_FIRST + AOD_LAST + ARITHMETIC_OPERATOR_REPLACEMENT_MUTATOR + + + + + + + +## Members + - Joseph LaFreniere + - Leeja James + - Keith Nguyen + +## Progress +**First Phase** + Problem encountered: we have to use different bytecode operation for single-word operator/operands (int, float) compared to double-word operator/operands (long, double). + +*AOD mutator* + - Replaces two operands and the operator with each of the operands, meaning there are two mutators for each operation. + - Example: a + b is replaced with mutant a and mutant b. -[maven2 on IBM JDK check](https://hjc.ci.cloudbees.com/job/maven2_triangle_example/) -[Sonarqube analysis](http://nemo.sonarqube.org/dashboard/index/793182) +*ROR mutator* + - Replaces each relational operators with each of the other ones. + - Some ROR mutators have already been implemented in the Conditional Boundary Mutator and Negate Conditional Mutator. + - Example: < is replaced with >=, <=, !=, ==. + *AOR mutator* + - Replaces each arithmetic operator with each of the other ones. + - Some AOR mutators have been implemented in Math Mutator. + - Example: + is replaced with -, *, /, %. diff --git a/code_cleanup_profile.xml b/code_cleanup_profile.xml index 9d3a0ee3e..95ec613ff 100644 --- a/code_cleanup_profile.xml +++ b/code_cleanup_profile.xml @@ -1,62 +1,62 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/code_format_profile.xml b/code_format_profile.xml index 40c36cf26..078f04a83 100644 --- a/code_format_profile.xml +++ b/code_format_profile.xml @@ -1,269 +1,269 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hackers_guide.txt b/hackers_guide.txt index 58e0aca83..2a3f321ee 100644 --- a/hackers_guide.txt +++ b/hackers_guide.txt @@ -1,42 +1,42 @@ -# General - -Pitest supports all version of Java back to Java 6. - -As long as the resulting binaries support Java 6 technically the build itself could be tied to higher versions of Java, but testing is currently tied into building so it must build with Java 6. - -It is reccomended to use Java 8 while developing, but be aware that it is not possible to use any Java 8 (or 7) features. - -## Structure - -Pitest is split into several modules - -* pitest - Main mutation engine and other code that must share a JVM with the system under test -* pitest-entry - The main entry point for build tools. Contains code that runs in main controller process. -* pitest-html-report - Generates the html report -* pitest-command-line - Command line tool for running pitet -* pitest-maven - Maven mojo for running pitest -* pitest-ant - Ant task for running pitest -* pitest-maven-verification - Integration tests that execute pitest via maven module -* pitest-java8-verification - Integration tests that validate pitest against java 8 features -* pitest-groovy-verification - Integration tests that validate pitets behaviour with groovy -* pitest-build-config - A minimal checkstyle configuration used in other modules. - -Care must be taken not to load the code under test into the JVM within the pitest-entry module (e.g by the use of reflection). - -Third party dependencies must not be introduced into the pitest module as they may conflict with those of the code under test. Where dependencies are unavoidable (e.g ASM) they must be shaded to avoid conflict. - -Dependencies may be introduced into the other modules, but are discouraged so start a discussion before doing so. Any dependencies introduced must be added to the classpath by users of the command-line tool and Ant. - -## Eclipse users - -Import everything as an existing maven project. If you do not have groovy plugins installed the `pitest-groovy-verification` module will show errors. Unless you are working on something Groovy related it is easiest just to close the module rather than installing the Groovy dependencies into eclipse. - -### Code format - -The files `code_format_profile.xml` and `code_cleanup_profile.xml` in the root of the repository. - -Will create formatting and cleanup profiles named henry. Some aspects of these will be changed in the future (e.g. the use of columns to layout fields) but they should be used while editing pitest to maintain consistency. - -## InteliJ - -? +# General + +Pitest supports all version of Java back to Java 6. + +As long as the resulting binaries support Java 6 technically the build itself could be tied to higher versions of Java, but testing is currently tied into building so it must build with Java 6. + +It is reccomended to use Java 8 while developing, but be aware that it is not possible to use any Java 8 (or 7) features. + +## Structure + +Pitest is split into several modules + +* pitest - Main mutation engine and other code that must share a JVM with the system under test +* pitest-entry - The main entry point for build tools. Contains code that runs in main controller process. +* pitest-html-report - Generates the html report +* pitest-command-line - Command line tool for running pitet +* pitest-maven - Maven mojo for running pitest +* pitest-ant - Ant task for running pitest +* pitest-maven-verification - Integration tests that execute pitest via maven module +* pitest-java8-verification - Integration tests that validate pitest against java 8 features +* pitest-groovy-verification - Integration tests that validate pitets behaviour with groovy +* pitest-build-config - A minimal checkstyle configuration used in other modules. + +Care must be taken not to load the code under test into the JVM within the pitest-entry module (e.g by the use of reflection). + +Third party dependencies must not be introduced into the pitest module as they may conflict with those of the code under test. Where dependencies are unavoidable (e.g ASM) they must be shaded to avoid conflict. + +Dependencies may be introduced into the other modules, but are discouraged so start a discussion before doing so. Any dependencies introduced must be added to the classpath by users of the command-line tool and Ant. + +## Eclipse users + +Import everything as an existing maven project. If you do not have groovy plugins installed the `pitest-groovy-verification` module will show errors. Unless you are working on something Groovy related it is easiest just to close the module rather than installing the Groovy dependencies into eclipse. + +### Code format + +The files `code_format_profile.xml` and `code_cleanup_profile.xml` in the root of the repository. + +Will create formatting and cleanup profiles named henry. Some aspects of these will be changed in the future (e.g. the use of columns to layout fields) but they should be used while editing pitest to maintain consistency. + +## InteliJ + +? diff --git a/install.sh b/install.sh new file mode 100755 index 000000000..5b13be0da --- /dev/null +++ b/install.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +mvn -T 4 clean install -DskipTests -e -D"checkstyle.skip"=true -Dmaven.javadoc.skip=true diff --git a/nohup.out b/nohup.out new file mode 100644 index 000000000..046858548 --- /dev/null +++ b/nohup.out @@ -0,0 +1,14 @@ +WARNING: Using incubator modules: jdk.incubator.httpclient +org.eclipse.m2e.logback.configuration: The org.eclipse.m2e.logback.configuration bundle was activated before the state location was initialized. Will retry after the state location is initialized. +org.eclipse.m2e.logback.configuration: Logback config file: /home/khoa/Documents/work/.metadata/.plugins/org.eclipse.m2e.logback.configuration/logback.1.8.3.20180227-2137.xml +SLF4J: Class path contains multiple SLF4J bindings. +SLF4J: Found binding in [bundleresource://496.fwk123629835:1/org/slf4j/impl/StaticLoggerBinder.class] +SLF4J: Found binding in [bundleresource://496.fwk123629835:2/org/slf4j/impl/StaticLoggerBinder.class] +SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. +SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder] +org.eclipse.m2e.logback.configuration: Initializing logback +WARNING: An illegal reflective access operation has occurred +WARNING: Illegal reflective access by org.eclipse.emf.ecore.xmi.impl.XMLHandler (file:/home/khoa/.local/share/umake/ide/eclipse/plugins/org.eclipse.emf.ecore.xmi_2.13.0.v20170609-0707.jar) to method com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser$LocatorProxy.getEncoding() +WARNING: Please consider reporting this to the maintainers of org.eclipse.emf.ecore.xmi.impl.XMLHandler +WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations +WARNING: All illegal access operations will be denied in a future release diff --git a/perform_release.sh b/perform_release.sh index 26e37c396..376b735d2 100755 --- a/perform_release.sh +++ b/perform_release.sh @@ -1 +1 @@ -mvn -Darguments="-Dcheckstyle.skip=true" release:perform +mvn -Darguments="-Dcheckstyle.skip=true" release:perform diff --git a/pitest-aggregator/pom.xml b/pitest-aggregator/pom.xml index 4b364ca13..f4d4e648b 100644 --- a/pitest-aggregator/pom.xml +++ b/pitest-aggregator/pom.xml @@ -1,42 +1,42 @@ - - 4.0.0 - - org.pitest - pitest-parent - 1.4.0-SNAPSHOT - - pitest-aggregator - Aggregates the output of report XML documents into a new combined HTML report - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - - - - org.pitest - pitest-entry - ${project.version} - - - org.pitest - pitest-html-report - ${project.version} - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-library - 1.3 - test - - + + 4.0.0 + + org.pitest + pitest-parent + 1.4.0-SNAPSHOT + + pitest-aggregator + Aggregates the output of report XML documents into a new combined HTML report + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + + + + org.pitest + pitest-entry + ${project.version} + + + org.pitest + pitest-html-report + ${project.version} + + + junit + junit + ${junit.version} + test + + + org.hamcrest + hamcrest-library + 1.3 + test + + \ No newline at end of file diff --git a/pitest-aggregator/src/main/java/org/pitest/aggregate/BlockCoverageDataLoader.java b/pitest-aggregator/src/main/java/org/pitest/aggregate/BlockCoverageDataLoader.java index 1b0d4fb68..697c384e0 100644 --- a/pitest-aggregator/src/main/java/org/pitest/aggregate/BlockCoverageDataLoader.java +++ b/pitest-aggregator/src/main/java/org/pitest/aggregate/BlockCoverageDataLoader.java @@ -1,40 +1,40 @@ -package org.pitest.aggregate; - -import java.io.File; -import java.util.Collection; -import java.util.Map; - -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.BlockCoverage; -import org.pitest.coverage.BlockLocation; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; - -class BlockCoverageDataLoader extends DataLoader { - - private static final String METHOD = "method"; - private static final String CLASSNAME = "classname"; - private static final String NUMBER = "number"; - private static final String TESTS = "tests"; - - private static final String OPEN_PAREN = "("; - - BlockCoverageDataLoader(final Collection filesToLoad) { - super(filesToLoad); - } - - @Override - protected BlockCoverage mapToData(final Map map) { - final String method = (String) map.get(METHOD); - final Location location = new Location(ClassName.fromString((String) map.get(CLASSNAME)), - MethodName.fromString(method.substring(0, method.indexOf(OPEN_PAREN))), method.substring(method.indexOf(OPEN_PAREN))); - - final BlockLocation blockLocation = new BlockLocation(location, Integer.parseInt((String) map.get(NUMBER))); - - @SuppressWarnings("unchecked") - final Collection tests = (Collection) map.get(TESTS); - - return new BlockCoverage(blockLocation, tests); - } - -} +package org.pitest.aggregate; + +import java.io.File; +import java.util.Collection; +import java.util.Map; + +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.BlockCoverage; +import org.pitest.coverage.BlockLocation; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; + +class BlockCoverageDataLoader extends DataLoader { + + private static final String METHOD = "method"; + private static final String CLASSNAME = "classname"; + private static final String NUMBER = "number"; + private static final String TESTS = "tests"; + + private static final String OPEN_PAREN = "("; + + BlockCoverageDataLoader(final Collection filesToLoad) { + super(filesToLoad); + } + + @Override + protected BlockCoverage mapToData(final Map map) { + final String method = (String) map.get(METHOD); + final Location location = new Location(ClassName.fromString((String) map.get(CLASSNAME)), + MethodName.fromString(method.substring(0, method.indexOf(OPEN_PAREN))), method.substring(method.indexOf(OPEN_PAREN))); + + final BlockLocation blockLocation = new BlockLocation(location, Integer.parseInt((String) map.get(NUMBER))); + + @SuppressWarnings("unchecked") + final Collection tests = (Collection) map.get(TESTS); + + return new BlockCoverage(blockLocation, tests); + } + +} diff --git a/pitest-aggregator/src/main/java/org/pitest/aggregate/CodeSourceAggregator.java b/pitest-aggregator/src/main/java/org/pitest/aggregate/CodeSourceAggregator.java index 3b790df9a..865a5d211 100644 --- a/pitest-aggregator/src/main/java/org/pitest/aggregate/CodeSourceAggregator.java +++ b/pitest-aggregator/src/main/java/org/pitest/aggregate/CodeSourceAggregator.java @@ -1,59 +1,59 @@ -package org.pitest.aggregate; - -import java.io.File; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassFilter; -import org.pitest.classpath.ClassPath; -import org.pitest.classpath.ClassPathRoot; -import org.pitest.classpath.CodeSource; -import org.pitest.classpath.DirectoryClassPathRoot; -import org.pitest.classpath.PathFilter; -import org.pitest.classpath.ProjectClassPaths; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.config.DefaultCodePathPredicate; -import org.pitest.mutationtest.config.DefaultDependencyPathPredicate; -import org.pitest.util.Glob; - -class CodeSourceAggregator { - - private final Collection compiledCodeDirectories; - - CodeSourceAggregator(final Collection compiledCodeDirectories) { - this.compiledCodeDirectories = Collections.unmodifiableCollection(compiledCodeDirectories); - } - - public CodeSource createCodeSource() { - return new CodeSource(createProjectClassPaths()); - } - - private ProjectClassPaths createProjectClassPaths() { - final ClassPath classPath = new ClassPath(this.compiledCodeDirectories); - final Predicate classPredicate = createClassPredicate(); - final Predicate pathPredicate = new DefaultCodePathPredicate(); - return new ProjectClassPaths(classPath, new ClassFilter(classPredicate, classPredicate), - new PathFilter(pathPredicate, Prelude.not(new DefaultDependencyPathPredicate()))); - } - - private Predicate createClassPredicate() { - final Collection classes = new HashSet<>(); - for (final File buildOutputDirectory : this.compiledCodeDirectories) { - if (buildOutputDirectory.exists()) { - final DirectoryClassPathRoot dcRoot = new DirectoryClassPathRoot(buildOutputDirectory); - classes.addAll(FCollection.map(dcRoot.classNames(), toPredicate())); - } - } - return Prelude.or(FCollection.map(classes, Glob.toGlobPredicate())); - } - - private Function toPredicate() { - return a -> ClassName.fromString(a).getPackage().asJavaName() + ".*"; - } - -} +package org.pitest.aggregate; + +import java.io.File; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassFilter; +import org.pitest.classpath.ClassPath; +import org.pitest.classpath.ClassPathRoot; +import org.pitest.classpath.CodeSource; +import org.pitest.classpath.DirectoryClassPathRoot; +import org.pitest.classpath.PathFilter; +import org.pitest.classpath.ProjectClassPaths; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.config.DefaultCodePathPredicate; +import org.pitest.mutationtest.config.DefaultDependencyPathPredicate; +import org.pitest.util.Glob; + +class CodeSourceAggregator { + + private final Collection compiledCodeDirectories; + + CodeSourceAggregator(final Collection compiledCodeDirectories) { + this.compiledCodeDirectories = Collections.unmodifiableCollection(compiledCodeDirectories); + } + + public CodeSource createCodeSource() { + return new CodeSource(createProjectClassPaths()); + } + + private ProjectClassPaths createProjectClassPaths() { + final ClassPath classPath = new ClassPath(this.compiledCodeDirectories); + final Predicate classPredicate = createClassPredicate(); + final Predicate pathPredicate = new DefaultCodePathPredicate(); + return new ProjectClassPaths(classPath, new ClassFilter(classPredicate, classPredicate), + new PathFilter(pathPredicate, Prelude.not(new DefaultDependencyPathPredicate()))); + } + + private Predicate createClassPredicate() { + final Collection classes = new HashSet<>(); + for (final File buildOutputDirectory : this.compiledCodeDirectories) { + if (buildOutputDirectory.exists()) { + final DirectoryClassPathRoot dcRoot = new DirectoryClassPathRoot(buildOutputDirectory); + classes.addAll(FCollection.map(dcRoot.classNames(), toPredicate())); + } + } + return Prelude.or(FCollection.map(classes, Glob.toGlobPredicate())); + } + + private Function toPredicate() { + return a -> ClassName.fromString(a).getPackage().asJavaName() + ".*"; + } + +} diff --git a/pitest-aggregator/src/main/java/org/pitest/aggregate/DataLoader.java b/pitest-aggregator/src/main/java/org/pitest/aggregate/DataLoader.java index 4ef5e402a..8ddb38792 100644 --- a/pitest-aggregator/src/main/java/org/pitest/aggregate/DataLoader.java +++ b/pitest-aggregator/src/main/java/org/pitest/aggregate/DataLoader.java @@ -1,150 +1,150 @@ -package org.pitest.aggregate; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -abstract class DataLoader { - - private static final String CANNOT_CLOSE_ERR = "Unable to close input stream"; - - private final Set filesToLoad; - - protected DataLoader(final Collection filesToLoad) { - if ((filesToLoad == null) || filesToLoad.isEmpty()) { - throw new IllegalArgumentException("Null or empty filesToLoad"); - } - - this.filesToLoad = Collections.unmodifiableSet(new HashSet<>(filesToLoad)); - } - - public Set loadData() throws ReportAggregationException { - final Set data = new HashSet<>(); - - for (final File file : this.filesToLoad) { - data.addAll(loadData(file)); - } - return data; - } - - protected abstract T mapToData(Map map); - - Set loadData(final File dataLocation) throws ReportAggregationException { - if (!dataLocation.exists() || !dataLocation.isFile()) { - throw new ReportAggregationException(dataLocation.getAbsolutePath() + " does not exist or is not a file"); - } - final Set data = new HashSet<>(); - try { - final InputStream inputStream = new BufferedInputStream(new FileInputStream(dataLocation)); - - final Document doc = readDocument(inputStream); - - final Node docNode = doc.getFirstChild(); - final NodeList nodeList = docNode.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - final Node itemNode = nodeList.item(i); - if (itemNode.getNodeType() == Node.ELEMENT_NODE) { - data.add(mapToData(nodeMap(itemNode))); - } - } - return data; - } catch (final IOException e) { - throw new ReportAggregationException("Could not read file: " + dataLocation.getAbsolutePath(), e); - } - } - - /** - * Reads the input stream into a document and closes the input stream when - * finished. - */ - static Document readDocument(final InputStream inputStream) throws ReportAggregationException { - DocumentBuilder docBuilder; - try { - docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - return docBuilder.parse(inputStream); - } catch (final IOException e) { - throw new ReportAggregationException(e.getMessage(), e); - } catch (final SAXException e) { - throw new ReportAggregationException(e.getMessage(), e); - } catch (final ParserConfigurationException e) { - throw new ReportAggregationException(e.getMessage(), e); - } finally { - try { - inputStream.close(); - } catch (final IOException e) { - throw new ReportAggregationException(CANNOT_CLOSE_ERR, e); - } - } - } - - // converts the contents of a node into a map - static Map nodeMap(final Node node) { - final HashMap map = new HashMap<>(); - - final NamedNodeMap attrs = node.getAttributes(); - for (int i = 0; i < attrs.getLength(); i++) { - final Node attr = attrs.item(i); - final String tc = attr.getTextContent().trim(); - - if (!tc.isEmpty()) { - map.put(attr.getNodeName(), tc); - } - } - - final NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - final Node child = children.item(i); - - if (child.getNodeType() == Node.ELEMENT_NODE) { - final String tc = child.getTextContent().trim(); - if (!tc.isEmpty()) { - map.put(child.getNodeName(), tc); - } else { - // may have test nodes - final List tests = new ArrayList<>(); - final NodeList testNodeList = child.getChildNodes(); - for (int j = 0; j < testNodeList.getLength(); j++) { - final Node testNode = testNodeList.item(j); - if (testNode.getNodeType() == Node.ELEMENT_NODE) { - final NamedNodeMap testAttrs = testNode.getAttributes(); - for (int k = 0; k < testAttrs.getLength(); k++) { - final Node attr = testAttrs.item(k); - final String tn = attr.getTextContent().trim(); - - if (!tn.isEmpty()) { - tests.add(tn); - } - } - } - } - if (!tests.isEmpty()) { - map.put(child.getNodeName(), tests); - } - } - } - } - - return map; - } -} +package org.pitest.aggregate; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +abstract class DataLoader { + + private static final String CANNOT_CLOSE_ERR = "Unable to close input stream"; + + private final Set filesToLoad; + + protected DataLoader(final Collection filesToLoad) { + if ((filesToLoad == null) || filesToLoad.isEmpty()) { + throw new IllegalArgumentException("Null or empty filesToLoad"); + } + + this.filesToLoad = Collections.unmodifiableSet(new HashSet<>(filesToLoad)); + } + + public Set loadData() throws ReportAggregationException { + final Set data = new HashSet<>(); + + for (final File file : this.filesToLoad) { + data.addAll(loadData(file)); + } + return data; + } + + protected abstract T mapToData(Map map); + + Set loadData(final File dataLocation) throws ReportAggregationException { + if (!dataLocation.exists() || !dataLocation.isFile()) { + throw new ReportAggregationException(dataLocation.getAbsolutePath() + " does not exist or is not a file"); + } + final Set data = new HashSet<>(); + try { + final InputStream inputStream = new BufferedInputStream(new FileInputStream(dataLocation)); + + final Document doc = readDocument(inputStream); + + final Node docNode = doc.getFirstChild(); + final NodeList nodeList = docNode.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + final Node itemNode = nodeList.item(i); + if (itemNode.getNodeType() == Node.ELEMENT_NODE) { + data.add(mapToData(nodeMap(itemNode))); + } + } + return data; + } catch (final IOException e) { + throw new ReportAggregationException("Could not read file: " + dataLocation.getAbsolutePath(), e); + } + } + + /** + * Reads the input stream into a document and closes the input stream when + * finished. + */ + static Document readDocument(final InputStream inputStream) throws ReportAggregationException { + DocumentBuilder docBuilder; + try { + docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + return docBuilder.parse(inputStream); + } catch (final IOException e) { + throw new ReportAggregationException(e.getMessage(), e); + } catch (final SAXException e) { + throw new ReportAggregationException(e.getMessage(), e); + } catch (final ParserConfigurationException e) { + throw new ReportAggregationException(e.getMessage(), e); + } finally { + try { + inputStream.close(); + } catch (final IOException e) { + throw new ReportAggregationException(CANNOT_CLOSE_ERR, e); + } + } + } + + // converts the contents of a node into a map + static Map nodeMap(final Node node) { + final HashMap map = new HashMap<>(); + + final NamedNodeMap attrs = node.getAttributes(); + for (int i = 0; i < attrs.getLength(); i++) { + final Node attr = attrs.item(i); + final String tc = attr.getTextContent().trim(); + + if (!tc.isEmpty()) { + map.put(attr.getNodeName(), tc); + } + } + + final NodeList children = node.getChildNodes(); + + for (int i = 0; i < children.getLength(); i++) { + final Node child = children.item(i); + + if (child.getNodeType() == Node.ELEMENT_NODE) { + final String tc = child.getTextContent().trim(); + if (!tc.isEmpty()) { + map.put(child.getNodeName(), tc); + } else { + // may have test nodes + final List tests = new ArrayList<>(); + final NodeList testNodeList = child.getChildNodes(); + for (int j = 0; j < testNodeList.getLength(); j++) { + final Node testNode = testNodeList.item(j); + if (testNode.getNodeType() == Node.ELEMENT_NODE) { + final NamedNodeMap testAttrs = testNode.getAttributes(); + for (int k = 0; k < testAttrs.getLength(); k++) { + final Node attr = testAttrs.item(k); + final String tn = attr.getTextContent().trim(); + + if (!tn.isEmpty()) { + tests.add(tn); + } + } + } + } + if (!tests.isEmpty()) { + map.put(child.getNodeName(), tests); + } + } + } + } + + return map; + } +} diff --git a/pitest-aggregator/src/main/java/org/pitest/aggregate/MutationResultDataLoader.java b/pitest-aggregator/src/main/java/org/pitest/aggregate/MutationResultDataLoader.java index eea6d1534..159d01c28 100644 --- a/pitest-aggregator/src/main/java/org/pitest/aggregate/MutationResultDataLoader.java +++ b/pitest-aggregator/src/main/java/org/pitest/aggregate/MutationResultDataLoader.java @@ -1,52 +1,52 @@ -package org.pitest.aggregate; - -import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; - -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; - -class MutationResultDataLoader extends DataLoader { - - private static final String MUTATED_CLASS = "mutatedClass"; - private static final String MUTATED_METHOD = "mutatedMethod"; - private static final String METHOD_DESCRIPTION = "methodDescription"; - private static final String INDEX = "index"; - private static final String MUTATOR = "mutator"; - private static final String SOURCE_FILE = "sourceFile"; - private static final String DESCRIPTION = "description"; - private static final String LINE_NUMBER = "lineNumber"; - private static final String BLOCK = "block"; - private static final String NUMBER_OF_TESTS_RUN = "numberOfTestsRun"; - private static final String STATUS = "status"; - private static final String KILLING_TEST = "killingTest"; - - MutationResultDataLoader(final Collection filesToLoad) { - super(filesToLoad); - } - - @Override - protected MutationResult mapToData(final Map map) { - final Location location = new Location(ClassName.fromString((String) map.get(MUTATED_CLASS)), MethodName.fromString((String) map.get(MUTATED_METHOD)), - (String) map.get(METHOD_DESCRIPTION)); - - final MutationIdentifier id = new MutationIdentifier(location, Arrays.asList(new Integer((String) map.get(INDEX))), (String) map.get(MUTATOR)); - - final MutationDetails md = new MutationDetails(id, (String) map.get(SOURCE_FILE), (String) map.get(DESCRIPTION), - Integer.parseInt((String) map.get(LINE_NUMBER)), Integer.parseInt((String) map.get(BLOCK))); - - final MutationStatusTestPair status = new MutationStatusTestPair(Integer.parseInt((String) map.get(NUMBER_OF_TESTS_RUN)), - DetectionStatus.valueOf((String) map.get(STATUS)), (String) map.get(KILLING_TEST)); - - return new MutationResult(md, status); - } - -} +package org.pitest.aggregate; + +import java.io.File; +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; + +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; + +class MutationResultDataLoader extends DataLoader { + + private static final String MUTATED_CLASS = "mutatedClass"; + private static final String MUTATED_METHOD = "mutatedMethod"; + private static final String METHOD_DESCRIPTION = "methodDescription"; + private static final String INDEX = "index"; + private static final String MUTATOR = "mutator"; + private static final String SOURCE_FILE = "sourceFile"; + private static final String DESCRIPTION = "description"; + private static final String LINE_NUMBER = "lineNumber"; + private static final String BLOCK = "block"; + private static final String NUMBER_OF_TESTS_RUN = "numberOfTestsRun"; + private static final String STATUS = "status"; + private static final String KILLING_TEST = "killingTest"; + + MutationResultDataLoader(final Collection filesToLoad) { + super(filesToLoad); + } + + @Override + protected MutationResult mapToData(final Map map) { + final Location location = new Location(ClassName.fromString((String) map.get(MUTATED_CLASS)), MethodName.fromString((String) map.get(MUTATED_METHOD)), + (String) map.get(METHOD_DESCRIPTION)); + + final MutationIdentifier id = new MutationIdentifier(location, Arrays.asList(new Integer((String) map.get(INDEX))), (String) map.get(MUTATOR)); + + final MutationDetails md = new MutationDetails(id, (String) map.get(SOURCE_FILE), (String) map.get(DESCRIPTION), + Integer.parseInt((String) map.get(LINE_NUMBER)), Integer.parseInt((String) map.get(BLOCK))); + + final MutationStatusTestPair status = new MutationStatusTestPair(Integer.parseInt((String) map.get(NUMBER_OF_TESTS_RUN)), + DetectionStatus.valueOf((String) map.get(STATUS)), (String) map.get(KILLING_TEST)); + + return new MutationResult(md, status); + } + +} diff --git a/pitest-aggregator/src/main/java/org/pitest/aggregate/MutatorUtil.java b/pitest-aggregator/src/main/java/org/pitest/aggregate/MutatorUtil.java index 660c2df9d..d7368793d 100644 --- a/pitest-aggregator/src/main/java/org/pitest/aggregate/MutatorUtil.java +++ b/pitest-aggregator/src/main/java/org/pitest/aggregate/MutatorUtil.java @@ -1,29 +1,29 @@ -package org.pitest.aggregate; - -import java.lang.reflect.Array; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; - -final class MutatorUtil { - - private static Map factories = new ConcurrentHashMap<>(); - - @SuppressWarnings("unchecked") - static MethodMutatorFactory loadMutator(final String className) { - if (!factories.containsKey(className)) { - try { - final Class clazz = (Class) Class.forName(className); - final Method values = clazz.getMethod("values"); - final Object valuesArray = values.invoke(null); - final MethodMutatorFactory mutator = (MethodMutatorFactory) Array.get(valuesArray, 0); - factories.put(className, mutator); - } catch (final Exception e) { - throw new RuntimeException("Unable to load Mutator for class: " + className, e); - } - } - return factories.get(className); - } -} +package org.pitest.aggregate; + +import java.lang.reflect.Array; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; + +final class MutatorUtil { + + private static Map factories = new ConcurrentHashMap<>(); + + @SuppressWarnings("unchecked") + static MethodMutatorFactory loadMutator(final String className) { + if (!factories.containsKey(className)) { + try { + final Class clazz = (Class) Class.forName(className); + final Method values = clazz.getMethod("values"); + final Object valuesArray = values.invoke(null); + final MethodMutatorFactory mutator = (MethodMutatorFactory) Array.get(valuesArray, 0); + factories.put(className, mutator); + } catch (final Exception e) { + throw new RuntimeException("Unable to load Mutator for class: " + className, e); + } + } + return factories.get(className); + } +} diff --git a/pitest-aggregator/src/main/java/org/pitest/aggregate/ReportAggregationException.java b/pitest-aggregator/src/main/java/org/pitest/aggregate/ReportAggregationException.java index 0cc4f3475..ea5772f2f 100644 --- a/pitest-aggregator/src/main/java/org/pitest/aggregate/ReportAggregationException.java +++ b/pitest-aggregator/src/main/java/org/pitest/aggregate/ReportAggregationException.java @@ -1,15 +1,15 @@ -package org.pitest.aggregate; - -public class ReportAggregationException extends Exception { - - private static final long serialVersionUID = 1L; - - public ReportAggregationException(final String message) { - super(message); - } - - public ReportAggregationException(final String message, final Throwable cause) { - super(message, cause); - } - -} +package org.pitest.aggregate; + +public class ReportAggregationException extends Exception { + + private static final long serialVersionUID = 1L; + + public ReportAggregationException(final String message) { + super(message); + } + + public ReportAggregationException(final String message, final Throwable cause) { + super(message, cause); + } + +} diff --git a/pitest-aggregator/src/main/java/org/pitest/aggregate/ReportAggregator.java b/pitest-aggregator/src/main/java/org/pitest/aggregate/ReportAggregator.java index 17337436d..ffe920054 100644 --- a/pitest-aggregator/src/main/java/org/pitest/aggregate/ReportAggregator.java +++ b/pitest-aggregator/src/main/java/org/pitest/aggregate/ReportAggregator.java @@ -1,239 +1,239 @@ -package org.pitest.aggregate; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; - -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.BlockCoverage; -import org.pitest.coverage.BlockLocation; -import org.pitest.coverage.CoverageData; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.coverage.TestInfo; -import org.pitest.coverage.analysis.LineMapper; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationMetaData; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.SourceLocator; -import org.pitest.mutationtest.report.html.MutationHtmlReportListener; -import org.pitest.mutationtest.tooling.SmartSourceLocator; -import org.pitest.util.ResultOutputStrategy; - -public final class ReportAggregator { - private final ResultOutputStrategy resultOutputStrategy; - private final DataLoader blockCoverageLoader; - private final DataLoader mutationLoader; - - private final Collection sourceCodeDirectories; - private final CodeSourceAggregator codeSourceAggregator; - - private ReportAggregator(final ResultOutputStrategy resultOutputStrategy, final Set lineCoverageFiles, final Set mutationFiles, - final Set sourceCodeDirs, final Set compiledCodeDirs) { - this.resultOutputStrategy = resultOutputStrategy; - this.blockCoverageLoader = new BlockCoverageDataLoader(lineCoverageFiles); - this.mutationLoader = new MutationResultDataLoader(mutationFiles); - this.sourceCodeDirectories = Collections.unmodifiableCollection(new HashSet<>(sourceCodeDirs)); - this.codeSourceAggregator = new CodeSourceAggregator(new HashSet<>(compiledCodeDirs)); - } - - public void aggregateReport() throws ReportAggregationException { - final MutationMetaData mutationMetaData = new MutationMetaData(new ArrayList<>(this.mutationLoader.loadData())); - - final MutationResultListener mutationResultListener = createResultListener(mutationMetaData); - - mutationResultListener.runStart(); - - for (final ClassMutationResults mutationResults : mutationMetaData.toClassResults()) { - mutationResultListener.handleMutationResult(mutationResults); - } - mutationResultListener.runEnd(); - } - - private MutationResultListener createResultListener(final MutationMetaData mutationMetaData) throws ReportAggregationException { - final SourceLocator sourceLocator = new SmartSourceLocator(this.sourceCodeDirectories); - - final CodeSource codeSource = this.codeSourceAggregator.createCodeSource(); - final CoverageDatabase coverageDatabase = calculateCoverage(codeSource, mutationMetaData); - final Collection mutatorNames = new HashSet<>(FCollection.flatMap(mutationMetaData.getMutations(), resultToMutatorName())); - - return new MutationHtmlReportListener(coverageDatabase, this.resultOutputStrategy, mutatorNames, sourceLocator); - } - - private static Function> resultToMutatorName() { - return a -> { - try { - final String mutatorName = MutatorUtil.loadMutator(a.getDetails().getMutator()).getName(); - return Collections.singletonList(mutatorName); - } catch (final Exception e) { - throw new RuntimeException("Cannot convert to mutator: " + a.getDetails().getMutator(), e); - } - }; - } - - private CoverageData calculateCoverage(final CodeSource codeSource, final MutationMetaData metadata) throws ReportAggregationException { - final Collection coverageData = this.blockCoverageLoader.loadData(); - try { - final Map> blockCoverageMap = blocksToMap(coverageData); - return new CoverageData(codeSource, new LineMapper(codeSource),blockCoverageMap); - } catch (final Exception e) { - throw new ReportAggregationException(e.getMessage(), e); - } - } - - private Map> blocksToMap( - final Collection coverageData) { - final Map> blockCoverageMap = new HashMap<>(); - - for (final BlockCoverage blockData : coverageData) { - blockCoverageMap.put(blockData.getBlock(), new HashSet<>(FCollection.map(blockData.getTests(), toTestInfo(blockData)))); - } - return blockCoverageMap; - } - - private Function toTestInfo(final BlockCoverage blockData) { - return a -> new TestInfo(null, a, 0, Optional.ofNullable(blockData.getBlock().getLocation().getClassName()), blockData.getBlock().getBlock()); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private ResultOutputStrategy resultOutputStrategy; - private final Set lineCoverageFiles = new HashSet<>(); - private final Set mutationResultsFiles = new HashSet<>(); - private final Set sourceCodeDirectories = new HashSet<>(); - private final Set compiledCodeDirectories = new HashSet<>(); - - public Builder resultOutputStrategy(final ResultOutputStrategy resultOutputStrategy) { - this.resultOutputStrategy = resultOutputStrategy; - return this; - } - - public Builder lineCoverageFiles(final List lineCoverageFiles) { - this.lineCoverageFiles.clear(); - for (final File file : lineCoverageFiles) { - addLineCoverageFile(file); - } - return this; - } - - public Builder addLineCoverageFile(final File lineCoverageFile) { - validateFile(lineCoverageFile); - this.lineCoverageFiles.add(lineCoverageFile); - return this; - } - - public Builder mutationResultsFiles(final List mutationResultsFiles) { - this.mutationResultsFiles.clear(); - for (final File file : mutationResultsFiles) { - addMutationResultsFile(file); - } - return this; - } - - public Builder addMutationResultsFile(final File mutationResultsFile) { - validateFile(mutationResultsFile); - this.mutationResultsFiles.add(mutationResultsFile); - return this; - } - - public Builder sourceCodeDirectories(final List sourceCodeDirectories) { - this.sourceCodeDirectories.clear(); - for (final File file : sourceCodeDirectories) { - addSourceCodeDirectory(file); - } - return this; - } - - public Builder addSourceCodeDirectory(final File sourceCodeDirectory) { - validateDirectory(sourceCodeDirectory); - this.sourceCodeDirectories.add(sourceCodeDirectory); - return this; - } - - public Builder compiledCodeDirectories(final List compiledCodeDirectories) { - this.compiledCodeDirectories.clear(); - for (final File file : compiledCodeDirectories) { - addCompiledCodeDirectory(file); - } - return this; - } - - public Builder addCompiledCodeDirectory(final File compiledCodeDirectory) { - validateDirectory(compiledCodeDirectory); - this.compiledCodeDirectories.add(compiledCodeDirectory); - return this; - } - - public Set getCompiledCodeDirectories() { - return this.compiledCodeDirectories; - } - - public Set getLineCoverageFiles() { - return this.lineCoverageFiles; - } - - public Set getMutationResultsFiles() { - return this.mutationResultsFiles; - } - - public Set getSourceCodeDirectories() { - return this.sourceCodeDirectories; - } - - public ReportAggregator build() { - validateState(); - return new ReportAggregator(this.resultOutputStrategy, this.lineCoverageFiles, this.mutationResultsFiles, this.sourceCodeDirectories, this.compiledCodeDirectories); - } - - /* - * Validators - */ - private void validateState() { - if (this.resultOutputStrategy == null) { - throw new IllegalStateException("Failed to build: the resultOutputStrategy has not been set"); - } - if (this.lineCoverageFiles.isEmpty()) { - throw new IllegalStateException("Failed to build: no lineCoverageFiles have been set"); - } - if (this.mutationResultsFiles.isEmpty()) { - throw new IllegalStateException("Failed to build: no mutationResultsFiles have been set"); - } - if (this.sourceCodeDirectories.isEmpty()) { - throw new IllegalStateException("Failed to build: no sourceCodeDirectories have been set"); - } - if (this.compiledCodeDirectories.isEmpty()) { - throw new IllegalStateException("Failed to build: no compiledCodeDirectories have been set"); - } - } - - private void validateFile(final File file) { - if (file == null) { - throw new IllegalArgumentException("file is null"); - } - if (!file.exists() || !file.isFile()) { - throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist or is not a file"); - } - } - - private void validateDirectory(final File directory) { - if (directory == null) { - throw new IllegalArgumentException("directory is null"); - } - if (!directory.exists() || !directory.isDirectory()) { - throw new IllegalArgumentException(directory.getAbsolutePath() + " does not exist or is not a directory"); - } - } - } -} +package org.pitest.aggregate; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.BlockCoverage; +import org.pitest.coverage.BlockLocation; +import org.pitest.coverage.CoverageData; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.coverage.TestInfo; +import org.pitest.coverage.analysis.LineMapper; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationMetaData; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.SourceLocator; +import org.pitest.mutationtest.report.html.MutationHtmlReportListener; +import org.pitest.mutationtest.tooling.SmartSourceLocator; +import org.pitest.util.ResultOutputStrategy; + +public final class ReportAggregator { + private final ResultOutputStrategy resultOutputStrategy; + private final DataLoader blockCoverageLoader; + private final DataLoader mutationLoader; + + private final Collection sourceCodeDirectories; + private final CodeSourceAggregator codeSourceAggregator; + + private ReportAggregator(final ResultOutputStrategy resultOutputStrategy, final Set lineCoverageFiles, final Set mutationFiles, + final Set sourceCodeDirs, final Set compiledCodeDirs) { + this.resultOutputStrategy = resultOutputStrategy; + this.blockCoverageLoader = new BlockCoverageDataLoader(lineCoverageFiles); + this.mutationLoader = new MutationResultDataLoader(mutationFiles); + this.sourceCodeDirectories = Collections.unmodifiableCollection(new HashSet<>(sourceCodeDirs)); + this.codeSourceAggregator = new CodeSourceAggregator(new HashSet<>(compiledCodeDirs)); + } + + public void aggregateReport() throws ReportAggregationException { + final MutationMetaData mutationMetaData = new MutationMetaData(new ArrayList<>(this.mutationLoader.loadData())); + + final MutationResultListener mutationResultListener = createResultListener(mutationMetaData); + + mutationResultListener.runStart(); + + for (final ClassMutationResults mutationResults : mutationMetaData.toClassResults()) { + mutationResultListener.handleMutationResult(mutationResults); + } + mutationResultListener.runEnd(); + } + + private MutationResultListener createResultListener(final MutationMetaData mutationMetaData) throws ReportAggregationException { + final SourceLocator sourceLocator = new SmartSourceLocator(this.sourceCodeDirectories); + + final CodeSource codeSource = this.codeSourceAggregator.createCodeSource(); + final CoverageDatabase coverageDatabase = calculateCoverage(codeSource, mutationMetaData); + final Collection mutatorNames = new HashSet<>(FCollection.flatMap(mutationMetaData.getMutations(), resultToMutatorName())); + + return new MutationHtmlReportListener(coverageDatabase, this.resultOutputStrategy, mutatorNames, sourceLocator); + } + + private static Function> resultToMutatorName() { + return a -> { + try { + final String mutatorName = MutatorUtil.loadMutator(a.getDetails().getMutator()).getName(); + return Collections.singletonList(mutatorName); + } catch (final Exception e) { + throw new RuntimeException("Cannot convert to mutator: " + a.getDetails().getMutator(), e); + } + }; + } + + private CoverageData calculateCoverage(final CodeSource codeSource, final MutationMetaData metadata) throws ReportAggregationException { + final Collection coverageData = this.blockCoverageLoader.loadData(); + try { + final Map> blockCoverageMap = blocksToMap(coverageData); + return new CoverageData(codeSource, new LineMapper(codeSource),blockCoverageMap); + } catch (final Exception e) { + throw new ReportAggregationException(e.getMessage(), e); + } + } + + private Map> blocksToMap( + final Collection coverageData) { + final Map> blockCoverageMap = new HashMap<>(); + + for (final BlockCoverage blockData : coverageData) { + blockCoverageMap.put(blockData.getBlock(), new HashSet<>(FCollection.map(blockData.getTests(), toTestInfo(blockData)))); + } + return blockCoverageMap; + } + + private Function toTestInfo(final BlockCoverage blockData) { + return a -> new TestInfo(null, a, 0, Optional.ofNullable(blockData.getBlock().getLocation().getClassName()), blockData.getBlock().getBlock()); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private ResultOutputStrategy resultOutputStrategy; + private final Set lineCoverageFiles = new HashSet<>(); + private final Set mutationResultsFiles = new HashSet<>(); + private final Set sourceCodeDirectories = new HashSet<>(); + private final Set compiledCodeDirectories = new HashSet<>(); + + public Builder resultOutputStrategy(final ResultOutputStrategy resultOutputStrategy) { + this.resultOutputStrategy = resultOutputStrategy; + return this; + } + + public Builder lineCoverageFiles(final List lineCoverageFiles) { + this.lineCoverageFiles.clear(); + for (final File file : lineCoverageFiles) { + addLineCoverageFile(file); + } + return this; + } + + public Builder addLineCoverageFile(final File lineCoverageFile) { + validateFile(lineCoverageFile); + this.lineCoverageFiles.add(lineCoverageFile); + return this; + } + + public Builder mutationResultsFiles(final List mutationResultsFiles) { + this.mutationResultsFiles.clear(); + for (final File file : mutationResultsFiles) { + addMutationResultsFile(file); + } + return this; + } + + public Builder addMutationResultsFile(final File mutationResultsFile) { + validateFile(mutationResultsFile); + this.mutationResultsFiles.add(mutationResultsFile); + return this; + } + + public Builder sourceCodeDirectories(final List sourceCodeDirectories) { + this.sourceCodeDirectories.clear(); + for (final File file : sourceCodeDirectories) { + addSourceCodeDirectory(file); + } + return this; + } + + public Builder addSourceCodeDirectory(final File sourceCodeDirectory) { + validateDirectory(sourceCodeDirectory); + this.sourceCodeDirectories.add(sourceCodeDirectory); + return this; + } + + public Builder compiledCodeDirectories(final List compiledCodeDirectories) { + this.compiledCodeDirectories.clear(); + for (final File file : compiledCodeDirectories) { + addCompiledCodeDirectory(file); + } + return this; + } + + public Builder addCompiledCodeDirectory(final File compiledCodeDirectory) { + validateDirectory(compiledCodeDirectory); + this.compiledCodeDirectories.add(compiledCodeDirectory); + return this; + } + + public Set getCompiledCodeDirectories() { + return this.compiledCodeDirectories; + } + + public Set getLineCoverageFiles() { + return this.lineCoverageFiles; + } + + public Set getMutationResultsFiles() { + return this.mutationResultsFiles; + } + + public Set getSourceCodeDirectories() { + return this.sourceCodeDirectories; + } + + public ReportAggregator build() { + validateState(); + return new ReportAggregator(this.resultOutputStrategy, this.lineCoverageFiles, this.mutationResultsFiles, this.sourceCodeDirectories, this.compiledCodeDirectories); + } + + /* + * Validators + */ + private void validateState() { + if (this.resultOutputStrategy == null) { + throw new IllegalStateException("Failed to build: the resultOutputStrategy has not been set"); + } + if (this.lineCoverageFiles.isEmpty()) { + throw new IllegalStateException("Failed to build: no lineCoverageFiles have been set"); + } + if (this.mutationResultsFiles.isEmpty()) { + throw new IllegalStateException("Failed to build: no mutationResultsFiles have been set"); + } + if (this.sourceCodeDirectories.isEmpty()) { + throw new IllegalStateException("Failed to build: no sourceCodeDirectories have been set"); + } + if (this.compiledCodeDirectories.isEmpty()) { + throw new IllegalStateException("Failed to build: no compiledCodeDirectories have been set"); + } + } + + private void validateFile(final File file) { + if (file == null) { + throw new IllegalArgumentException("file is null"); + } + if (!file.exists() || !file.isFile()) { + throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist or is not a file"); + } + } + + private void validateDirectory(final File directory) { + if (directory == null) { + throw new IllegalArgumentException("directory is null"); + } + if (!directory.exists() || !directory.isDirectory()) { + throw new IllegalArgumentException(directory.getAbsolutePath() + " does not exist or is not a directory"); + } + } + } +} diff --git a/pitest-aggregator/src/test/java/org/pitest/aggregate/BlockCoverageDataLoaderTest.java b/pitest-aggregator/src/test/java/org/pitest/aggregate/BlockCoverageDataLoaderTest.java index 70a87ea2f..f0d4e63c5 100644 --- a/pitest-aggregator/src/test/java/org/pitest/aggregate/BlockCoverageDataLoaderTest.java +++ b/pitest-aggregator/src/test/java/org/pitest/aggregate/BlockCoverageDataLoaderTest.java @@ -1,41 +1,41 @@ -package org.pitest.aggregate; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.net.URL; -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.coverage.BlockCoverage; - -public class BlockCoverageDataLoaderTest { - - private BlockCoverageDataLoader underTest; - - @Before - public void setup() throws Exception { - final URL url = MutationResultDataLoaderTest.class.getResource("/full-data/linecoverage.xml"); - final File file = new File(url.toURI()); - - this.underTest = new BlockCoverageDataLoader(Arrays.asList(file)); - } - - @Test - public void testLoadData() throws Exception { - final Collection results = this.underTest.loadData(); - - assertNotNull(results); - assertEquals(5, results.size()); - for (final BlockCoverage block : results) { - assertNotNull(block.getTests()); - assertEquals(1, block.getTests().size()); - - assertEquals("com.example.DividerTest.testDivide(com.example.DividerTest)", block.getTests().iterator().next()); - } - } - -} +package org.pitest.aggregate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.File; +import java.net.URL; +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.coverage.BlockCoverage; + +public class BlockCoverageDataLoaderTest { + + private BlockCoverageDataLoader underTest; + + @Before + public void setup() throws Exception { + final URL url = MutationResultDataLoaderTest.class.getResource("/full-data/linecoverage.xml"); + final File file = new File(url.toURI()); + + this.underTest = new BlockCoverageDataLoader(Arrays.asList(file)); + } + + @Test + public void testLoadData() throws Exception { + final Collection results = this.underTest.loadData(); + + assertNotNull(results); + assertEquals(5, results.size()); + for (final BlockCoverage block : results) { + assertNotNull(block.getTests()); + assertEquals(1, block.getTests().size()); + + assertEquals("com.example.DividerTest.testDivide(com.example.DividerTest)", block.getTests().iterator().next()); + } + } + +} diff --git a/pitest-aggregator/src/test/java/org/pitest/aggregate/CodeSourceAggregatorTest.java b/pitest-aggregator/src/test/java/org/pitest/aggregate/CodeSourceAggregatorTest.java index d0fe4f308..7f1726ef6 100644 --- a/pitest-aggregator/src/test/java/org/pitest/aggregate/CodeSourceAggregatorTest.java +++ b/pitest-aggregator/src/test/java/org/pitest/aggregate/CodeSourceAggregatorTest.java @@ -1,38 +1,38 @@ -package org.pitest.aggregate; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.CodeSource; - -public class CodeSourceAggregatorTest { - - private CodeSourceAggregator underTest; - - @Before - public void setup() throws Exception { - final File testDir = new File(CodeSourceAggregatorTest.class.getResource("/").toURI()); - final File mainDir = new File(CodeSourceAggregatorTest.class.getResource("/org/pitest/aggregate/DataLoader.class").toURI()).getParentFile() // aggregate - .getParentFile() // pitest - .getParentFile() // org - .getParentFile(); // classes - this.underTest = new CodeSourceAggregator(Arrays.asList(testDir, mainDir)); - } - - @Test - public void testCreateCodeSource() { - final CodeSource source = this.underTest.createCodeSource(); - assertNotNull(source); - - assertTrue(source.fetchClass(ClassName.fromClass(CodeSourceAggregator.class)).isPresent()); - assertFalse(source.fetchClass(ClassName.fromString("com.doesnt.exist.Type")).isPresent()); - } - -} +package org.pitest.aggregate; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.CodeSource; + +public class CodeSourceAggregatorTest { + + private CodeSourceAggregator underTest; + + @Before + public void setup() throws Exception { + final File testDir = new File(CodeSourceAggregatorTest.class.getResource("/").toURI()); + final File mainDir = new File(CodeSourceAggregatorTest.class.getResource("/org/pitest/aggregate/DataLoader.class").toURI()).getParentFile() // aggregate + .getParentFile() // pitest + .getParentFile() // org + .getParentFile(); // classes + this.underTest = new CodeSourceAggregator(Arrays.asList(testDir, mainDir)); + } + + @Test + public void testCreateCodeSource() { + final CodeSource source = this.underTest.createCodeSource(); + assertNotNull(source); + + assertTrue(source.fetchClass(ClassName.fromClass(CodeSourceAggregator.class)).isPresent()); + assertFalse(source.fetchClass(ClassName.fromString("com.doesnt.exist.Type")).isPresent()); + } + +} diff --git a/pitest-aggregator/src/test/java/org/pitest/aggregate/DataLoaderTest.java b/pitest-aggregator/src/test/java/org/pitest/aggregate/DataLoaderTest.java index 8ee10136e..4c7bcd8bd 100644 --- a/pitest-aggregator/src/test/java/org/pitest/aggregate/DataLoaderTest.java +++ b/pitest-aggregator/src/test/java/org/pitest/aggregate/DataLoaderTest.java @@ -1,53 +1,53 @@ -package org.pitest.aggregate; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Map; - -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -public class DataLoaderTest { - - @Test - public void testLoadMutationSnippet() throws Exception { - final Document doc = DataLoader.readDocument(DataLoaderTest.class.getResourceAsStream("/snippets/mutation.xml")); - final Node node = doc.getFirstChild(); - - final Map map = DataLoader.nodeMap(node); - - assertEquals(13, map.size()); - assertEquals("true", map.get("detected")); - assertEquals("KILLED", map.get("status")); - assertEquals("1", map.get("numberOfTestsRun")); - assertEquals("OrderedWeightedValueSampler.java", map.get("sourceFile")); - assertEquals("com.mycompany.OrderedWeightedValueSampler", map.get("mutatedClass")); - assertEquals("", map.get("mutatedMethod")); - assertEquals("(JLjava/util/function/Consumer;Ljava/util/function/BiFunction;I)V", map.get("methodDescription")); - assertEquals("77", map.get("lineNumber")); - assertEquals("org.pitest.mutationtest.engine.gregor.mutators.MathMutator", map.get("mutator")); - assertEquals("61", map.get("index")); - assertEquals( - "com.mycompany.SmallScaleOrderedWeightedValueSamplerTest.shouldSucceedWithVariousGapTimestamps(com.mycompany.SmallScaleOrderedWeightedValueSamplerTest)", - map.get("killingTest")); - assertEquals("Replaced long multiplication with division", map.get("description")); - assertEquals("27", map.get("block")); - } - - @Test - public void testLoadCoverageSnippet() throws Exception { - final Document doc = DataLoader.readDocument(DataLoaderTest.class.getResourceAsStream("/snippets/linecoverage.xml")); - final Node node = doc.getFirstChild(); - - final Map map = DataLoader.nodeMap(node); - - assertEquals(4, map.size()); - assertEquals("com.example.DividerTest", map.get("classname")); - assertEquals("testDivide()V", map.get("method")); - assertEquals("0", map.get("number")); - assertEquals(Arrays.asList("com.example.DividerTest.testDivide(com.example.DividerTest)"), map.get("tests")); - } - -} +package org.pitest.aggregate; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Map; + +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +public class DataLoaderTest { + + @Test + public void testLoadMutationSnippet() throws Exception { + final Document doc = DataLoader.readDocument(DataLoaderTest.class.getResourceAsStream("/snippets/mutation.xml")); + final Node node = doc.getFirstChild(); + + final Map map = DataLoader.nodeMap(node); + + assertEquals(13, map.size()); + assertEquals("true", map.get("detected")); + assertEquals("KILLED", map.get("status")); + assertEquals("1", map.get("numberOfTestsRun")); + assertEquals("OrderedWeightedValueSampler.java", map.get("sourceFile")); + assertEquals("com.mycompany.OrderedWeightedValueSampler", map.get("mutatedClass")); + assertEquals("", map.get("mutatedMethod")); + assertEquals("(JLjava/util/function/Consumer;Ljava/util/function/BiFunction;I)V", map.get("methodDescription")); + assertEquals("77", map.get("lineNumber")); + assertEquals("org.pitest.mutationtest.engine.gregor.mutators.MathMutator", map.get("mutator")); + assertEquals("61", map.get("index")); + assertEquals( + "com.mycompany.SmallScaleOrderedWeightedValueSamplerTest.shouldSucceedWithVariousGapTimestamps(com.mycompany.SmallScaleOrderedWeightedValueSamplerTest)", + map.get("killingTest")); + assertEquals("Replaced long multiplication with division", map.get("description")); + assertEquals("27", map.get("block")); + } + + @Test + public void testLoadCoverageSnippet() throws Exception { + final Document doc = DataLoader.readDocument(DataLoaderTest.class.getResourceAsStream("/snippets/linecoverage.xml")); + final Node node = doc.getFirstChild(); + + final Map map = DataLoader.nodeMap(node); + + assertEquals(4, map.size()); + assertEquals("com.example.DividerTest", map.get("classname")); + assertEquals("testDivide()V", map.get("method")); + assertEquals("0", map.get("number")); + assertEquals(Arrays.asList("com.example.DividerTest.testDivide(com.example.DividerTest)"), map.get("tests")); + } + +} diff --git a/pitest-aggregator/src/test/java/org/pitest/aggregate/MutationResultDataLoaderTest.java b/pitest-aggregator/src/test/java/org/pitest/aggregate/MutationResultDataLoaderTest.java index 021b63c62..e9b6e74db 100644 --- a/pitest-aggregator/src/test/java/org/pitest/aggregate/MutationResultDataLoaderTest.java +++ b/pitest-aggregator/src/test/java/org/pitest/aggregate/MutationResultDataLoaderTest.java @@ -1,54 +1,54 @@ -package org.pitest.aggregate; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.net.URL; -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; - -public class MutationResultDataLoaderTest { - - private MutationResultDataLoader underTest; - - @Before - public void setup() throws Exception { - final URL url = MutationResultDataLoaderTest.class.getResource("/full-data/mutations.xml"); - final File file = new File(url.toURI()); - - this.underTest = new MutationResultDataLoader(Arrays.asList(file)); - } - - @Test - public void testLoadData() throws Exception { - final Collection results = this.underTest.loadData(); - - assertNotNull(results); - assertEquals(2, results.size()); - - for (final MutationResult result : results) { - if (result.getDetails().getFirstIndex() == 5) { - assertEquals(38, result.getDetails().getBlock()); - assertEquals("com.mycompany.OrderedWeightedValueSampler", result.getDetails().getId().getClassName().asJavaName()); - assertEquals(202, result.getDetails().getLineNumber()); - assertFalse(result.getStatus().isDetected()); - assertEquals(DetectionStatus.NO_COVERAGE, result.getStatus()); - } else { - assertEquals(27, result.getDetails().getBlock()); - assertEquals("com.mycompany.OrderedWeightedValueSampler", result.getDetails().getId().getClassName().asJavaName()); - assertEquals(77, result.getDetails().getLineNumber()); - assertTrue(result.getStatus().isDetected()); - assertEquals(DetectionStatus.KILLED, result.getStatus()); - } - } - } - -} +package org.pitest.aggregate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.net.URL; +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; + +public class MutationResultDataLoaderTest { + + private MutationResultDataLoader underTest; + + @Before + public void setup() throws Exception { + final URL url = MutationResultDataLoaderTest.class.getResource("/full-data/mutations.xml"); + final File file = new File(url.toURI()); + + this.underTest = new MutationResultDataLoader(Arrays.asList(file)); + } + + @Test + public void testLoadData() throws Exception { + final Collection results = this.underTest.loadData(); + + assertNotNull(results); + assertEquals(2, results.size()); + + for (final MutationResult result : results) { + if (result.getDetails().getFirstIndex() == 5) { + assertEquals(38, result.getDetails().getBlock()); + assertEquals("com.mycompany.OrderedWeightedValueSampler", result.getDetails().getId().getClassName().asJavaName()); + assertEquals(202, result.getDetails().getLineNumber()); + assertFalse(result.getStatus().isDetected()); + assertEquals(DetectionStatus.NO_COVERAGE, result.getStatus()); + } else { + assertEquals(27, result.getDetails().getBlock()); + assertEquals("com.mycompany.OrderedWeightedValueSampler", result.getDetails().getId().getClassName().asJavaName()); + assertEquals(77, result.getDetails().getLineNumber()); + assertTrue(result.getStatus().isDetected()); + assertEquals(DetectionStatus.KILLED, result.getStatus()); + } + } + } + +} diff --git a/pitest-aggregator/src/test/java/org/pitest/aggregate/ReportAggregatorBuilderTest.java b/pitest-aggregator/src/test/java/org/pitest/aggregate/ReportAggregatorBuilderTest.java index aaf186e1a..a4c40a379 100644 --- a/pitest-aggregator/src/test/java/org/pitest/aggregate/ReportAggregatorBuilderTest.java +++ b/pitest-aggregator/src/test/java/org/pitest/aggregate/ReportAggregatorBuilderTest.java @@ -1,195 +1,195 @@ -package org.pitest.aggregate; - -import static org.junit.Assert.assertNotNull; -import static org.pitest.aggregate.TestInvocationHelper.getCompiledDirectory; -import static org.pitest.aggregate.TestInvocationHelper.getCoverageFile; -import static org.pitest.aggregate.TestInvocationHelper.getMutationFile; -import static org.pitest.aggregate.TestInvocationHelper.getResultOutputStrategy; -import static org.pitest.aggregate.TestInvocationHelper.getSourceDirectory; -import static org.pitest.aggregate.TestInvocationHelper.getTestCompiledDirectory; -import static org.pitest.aggregate.TestInvocationHelper.getTestSourceDirectory; - -import java.io.File; -import java.util.Arrays; - -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class ReportAggregatorBuilderTest { - - private static final String NOT_A_FILE = "does not exist or is not a file"; - private static final String NOT_A_DIR = "does not exist or is not a directory"; - private static final String IS_NULL = "is null"; - @Rule - public ExpectedException expected = ExpectedException.none(); - - @Test - public void testLineCoverageFiles_withNull() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(IS_NULL)); - - ReportAggregator.builder().lineCoverageFiles(Arrays.asList(getCoverageFile(), null, getCoverageFile())); - } - - @Test - public void testLineCoverageFiles_withFake() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(NOT_A_FILE)); - - ReportAggregator.builder().lineCoverageFiles(Arrays.asList(new File("doesnotexist.xml"))); - } - - @Test - public void testLineCoverageFiles_withDir() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(NOT_A_FILE)); - - ReportAggregator.builder().lineCoverageFiles(Arrays.asList(getSourceDirectory())); - } - - @Test - public void testMutationResultsFiles_withNull() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(IS_NULL)); - - ReportAggregator.builder().mutationResultsFiles(Arrays.asList(getMutationFile(), null, getMutationFile())); - } - - @Test - public void testMutationResultsFiles_withFake() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(NOT_A_FILE)); - - ReportAggregator.builder().mutationResultsFiles(Arrays.asList(new File("doesnotexist.xml"))); - } - - @Test - public void testMutationResultsFiles_withDir() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(NOT_A_FILE)); - - ReportAggregator.builder().mutationResultsFiles(Arrays.asList(getTestSourceDirectory())); - } - - @Test - public void testSourceCodeDirectories_withNull() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(IS_NULL)); - - ReportAggregator.builder().sourceCodeDirectories(Arrays.asList(getSourceDirectory(), null, getTestSourceDirectory())); - } - - @Test - public void testSourceCodeDirectories_withFake() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(NOT_A_DIR)); - - ReportAggregator.builder().sourceCodeDirectories(Arrays.asList(new File("fakedirectory"))); - } - - @Test - public void testSourceCodeDirectories_withFile() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(NOT_A_DIR)); - - ReportAggregator.builder().sourceCodeDirectories(Arrays.asList(getCoverageFile())); - } - - @Test - public void testCompiledCodeDirectories_withNull() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(IS_NULL)); - - ReportAggregator.builder().compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), null, getTestCompiledDirectory())); - } - - @Test - public void testCompiledCodeDirectories_withFake() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(NOT_A_DIR)); - - ReportAggregator.builder().compiledCodeDirectories(Arrays.asList(new File("fakedirectory"))); - } - - @Test - public void testCompiledCodeDirectories_withFile() { - this.expected.expect(IllegalArgumentException.class); - this.expected.expectMessage(Matchers.containsString(NOT_A_DIR)); - - ReportAggregator.builder().compiledCodeDirectories(Arrays.asList(getMutationFile())); - } - - @Test - public void testBuild() { - assertNotNull(ReportAggregator.builder() // create builder - .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy - .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles - .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles - .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories - .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories - .build()); - } - - @Test - public void testBuild_missingOutputStrategy() { - this.expected.expect(IllegalStateException.class); - this.expected.expectMessage(Matchers.containsString("resultOutputStrategy")); - ReportAggregator.builder() // create builder - .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles - .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles - .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories - .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories - .build(); - } - - @Test - public void testBuild_missingCoverageFiles() { - this.expected.expect(IllegalStateException.class); - this.expected.expectMessage(Matchers.containsString("lineCoverageFiles")); - ReportAggregator.builder() // create builder - .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy - .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles - .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories - .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories - .build(); - } - - @Test - public void testBuild_missingMutationResultsFiles() { - this.expected.expect(IllegalStateException.class); - this.expected.expectMessage(Matchers.containsString("mutationResultsFiles")); - ReportAggregator.builder() // create builder - .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy - .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles - .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories - .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories - .build(); - } - - @Test - public void testBuild_missingCompiledCodeDirectories() { - this.expected.expect(IllegalStateException.class); - this.expected.expectMessage(Matchers.containsString("compiledCodeDirectories")); - ReportAggregator.builder() // create builder - .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy - .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles - .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles - .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories - .build(); - } - - @Test - public void testBuild_missingSourceCodeDirectories() { - this.expected.expect(IllegalStateException.class); - this.expected.expectMessage(Matchers.containsString("sourceCodeDirectories")); - ReportAggregator.builder() // create builder - .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy - .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles - .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles - .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories - .build(); - } - -} +package org.pitest.aggregate; + +import static org.junit.Assert.assertNotNull; +import static org.pitest.aggregate.TestInvocationHelper.getCompiledDirectory; +import static org.pitest.aggregate.TestInvocationHelper.getCoverageFile; +import static org.pitest.aggregate.TestInvocationHelper.getMutationFile; +import static org.pitest.aggregate.TestInvocationHelper.getResultOutputStrategy; +import static org.pitest.aggregate.TestInvocationHelper.getSourceDirectory; +import static org.pitest.aggregate.TestInvocationHelper.getTestCompiledDirectory; +import static org.pitest.aggregate.TestInvocationHelper.getTestSourceDirectory; + +import java.io.File; +import java.util.Arrays; + +import org.hamcrest.Matchers; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class ReportAggregatorBuilderTest { + + private static final String NOT_A_FILE = "does not exist or is not a file"; + private static final String NOT_A_DIR = "does not exist or is not a directory"; + private static final String IS_NULL = "is null"; + @Rule + public ExpectedException expected = ExpectedException.none(); + + @Test + public void testLineCoverageFiles_withNull() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(IS_NULL)); + + ReportAggregator.builder().lineCoverageFiles(Arrays.asList(getCoverageFile(), null, getCoverageFile())); + } + + @Test + public void testLineCoverageFiles_withFake() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(NOT_A_FILE)); + + ReportAggregator.builder().lineCoverageFiles(Arrays.asList(new File("doesnotexist.xml"))); + } + + @Test + public void testLineCoverageFiles_withDir() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(NOT_A_FILE)); + + ReportAggregator.builder().lineCoverageFiles(Arrays.asList(getSourceDirectory())); + } + + @Test + public void testMutationResultsFiles_withNull() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(IS_NULL)); + + ReportAggregator.builder().mutationResultsFiles(Arrays.asList(getMutationFile(), null, getMutationFile())); + } + + @Test + public void testMutationResultsFiles_withFake() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(NOT_A_FILE)); + + ReportAggregator.builder().mutationResultsFiles(Arrays.asList(new File("doesnotexist.xml"))); + } + + @Test + public void testMutationResultsFiles_withDir() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(NOT_A_FILE)); + + ReportAggregator.builder().mutationResultsFiles(Arrays.asList(getTestSourceDirectory())); + } + + @Test + public void testSourceCodeDirectories_withNull() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(IS_NULL)); + + ReportAggregator.builder().sourceCodeDirectories(Arrays.asList(getSourceDirectory(), null, getTestSourceDirectory())); + } + + @Test + public void testSourceCodeDirectories_withFake() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(NOT_A_DIR)); + + ReportAggregator.builder().sourceCodeDirectories(Arrays.asList(new File("fakedirectory"))); + } + + @Test + public void testSourceCodeDirectories_withFile() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(NOT_A_DIR)); + + ReportAggregator.builder().sourceCodeDirectories(Arrays.asList(getCoverageFile())); + } + + @Test + public void testCompiledCodeDirectories_withNull() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(IS_NULL)); + + ReportAggregator.builder().compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), null, getTestCompiledDirectory())); + } + + @Test + public void testCompiledCodeDirectories_withFake() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(NOT_A_DIR)); + + ReportAggregator.builder().compiledCodeDirectories(Arrays.asList(new File("fakedirectory"))); + } + + @Test + public void testCompiledCodeDirectories_withFile() { + this.expected.expect(IllegalArgumentException.class); + this.expected.expectMessage(Matchers.containsString(NOT_A_DIR)); + + ReportAggregator.builder().compiledCodeDirectories(Arrays.asList(getMutationFile())); + } + + @Test + public void testBuild() { + assertNotNull(ReportAggregator.builder() // create builder + .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy + .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles + .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles + .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories + .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories + .build()); + } + + @Test + public void testBuild_missingOutputStrategy() { + this.expected.expect(IllegalStateException.class); + this.expected.expectMessage(Matchers.containsString("resultOutputStrategy")); + ReportAggregator.builder() // create builder + .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles + .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles + .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories + .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories + .build(); + } + + @Test + public void testBuild_missingCoverageFiles() { + this.expected.expect(IllegalStateException.class); + this.expected.expectMessage(Matchers.containsString("lineCoverageFiles")); + ReportAggregator.builder() // create builder + .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy + .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles + .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories + .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories + .build(); + } + + @Test + public void testBuild_missingMutationResultsFiles() { + this.expected.expect(IllegalStateException.class); + this.expected.expectMessage(Matchers.containsString("mutationResultsFiles")); + ReportAggregator.builder() // create builder + .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy + .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles + .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories + .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories + .build(); + } + + @Test + public void testBuild_missingCompiledCodeDirectories() { + this.expected.expect(IllegalStateException.class); + this.expected.expectMessage(Matchers.containsString("compiledCodeDirectories")); + ReportAggregator.builder() // create builder + .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy + .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles + .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles + .sourceCodeDirectories(Arrays.asList(getSourceDirectory(), getTestSourceDirectory())) // sourceCodeDirectories + .build(); + } + + @Test + public void testBuild_missingSourceCodeDirectories() { + this.expected.expect(IllegalStateException.class); + this.expected.expectMessage(Matchers.containsString("sourceCodeDirectories")); + ReportAggregator.builder() // create builder + .resultOutputStrategy(getResultOutputStrategy()) // resultOutputStrategy + .lineCoverageFiles(Arrays.asList(getCoverageFile())) // lineCoverageFiles + .mutationResultsFiles(Arrays.asList(getMutationFile())) // mutationResultsFiles + .compiledCodeDirectories(Arrays.asList(getCompiledDirectory(), getTestCompiledDirectory())) // compiledCodeDirectories + .build(); + } + +} diff --git a/pitest-aggregator/src/test/java/org/pitest/aggregate/TestInvocationHelper.java b/pitest-aggregator/src/test/java/org/pitest/aggregate/TestInvocationHelper.java index e2cc06256..4952ec89e 100644 --- a/pitest-aggregator/src/test/java/org/pitest/aggregate/TestInvocationHelper.java +++ b/pitest-aggregator/src/test/java/org/pitest/aggregate/TestInvocationHelper.java @@ -1,75 +1,75 @@ -package org.pitest.aggregate; - -import java.io.File; -import java.io.IOException; -import java.io.Writer; - -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.Unchecked; - -public class TestInvocationHelper { - - public static ResultOutputStrategy getResultOutputStrategy() { - return sourceFile -> new Writer() { - - @Override - public void write(final char[] cbuf, final int off, final int len) throws IOException { - // ignore - } - - @Override - public void flush() throws IOException { - // ignore - } - - @Override - public void close() throws IOException { - // ignore - } - }; - } - - public static File getMutationFile() { - try { - return new File(ReportAggregatorBuilderTest.class.getResource("/full-data/mutations.xml").toURI()); - } catch (final Exception e) { - throw Unchecked.translateCheckedException(e); - } - } - - public static File getCoverageFile() { - try { - return new File(ReportAggregatorBuilderTest.class.getResource("/full-data/linecoverage.xml").toURI()); - } catch (final Exception e) { - throw Unchecked.translateCheckedException(e); - } - } - - public static File getSourceDirectory() { - return new File("src" + File.separator + "main" + File.separator + "java"); - } - - public static File getTestSourceDirectory() { - return new File("src" + File.separator + "test" + File.separator + "java"); - } - - public static File getCompiledDirectory() { - try { - return new File(ReportAggregatorBuilderTest.class.getResource("/org/pitest/aggregate/DataLoader.class").toURI()).getParentFile() // aggregate - .getParentFile() // pitest - .getParentFile() // org - .getParentFile(); // classes - } catch (final Exception e) { - throw Unchecked.translateCheckedException(e); - } - } - - public static File getTestCompiledDirectory() { - try { - return new File(ReportAggregatorBuilderTest.class.getResource("/").toURI()); - } catch (final Exception e) { - throw Unchecked.translateCheckedException(e); - } - } - -} +package org.pitest.aggregate; + +import java.io.File; +import java.io.IOException; +import java.io.Writer; + +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.Unchecked; + +public class TestInvocationHelper { + + public static ResultOutputStrategy getResultOutputStrategy() { + return sourceFile -> new Writer() { + + @Override + public void write(final char[] cbuf, final int off, final int len) throws IOException { + // ignore + } + + @Override + public void flush() throws IOException { + // ignore + } + + @Override + public void close() throws IOException { + // ignore + } + }; + } + + public static File getMutationFile() { + try { + return new File(ReportAggregatorBuilderTest.class.getResource("/full-data/mutations.xml").toURI()); + } catch (final Exception e) { + throw Unchecked.translateCheckedException(e); + } + } + + public static File getCoverageFile() { + try { + return new File(ReportAggregatorBuilderTest.class.getResource("/full-data/linecoverage.xml").toURI()); + } catch (final Exception e) { + throw Unchecked.translateCheckedException(e); + } + } + + public static File getSourceDirectory() { + return new File("src" + File.separator + "main" + File.separator + "java"); + } + + public static File getTestSourceDirectory() { + return new File("src" + File.separator + "test" + File.separator + "java"); + } + + public static File getCompiledDirectory() { + try { + return new File(ReportAggregatorBuilderTest.class.getResource("/org/pitest/aggregate/DataLoader.class").toURI()).getParentFile() // aggregate + .getParentFile() // pitest + .getParentFile() // org + .getParentFile(); // classes + } catch (final Exception e) { + throw Unchecked.translateCheckedException(e); + } + } + + public static File getTestCompiledDirectory() { + try { + return new File(ReportAggregatorBuilderTest.class.getResource("/").toURI()); + } catch (final Exception e) { + throw Unchecked.translateCheckedException(e); + } + } + +} diff --git a/pitest-aggregator/src/test/resources/full-data/linecoverage.xml b/pitest-aggregator/src/test/resources/full-data/linecoverage.xml index 3100c0721..db8fe5b17 100644 --- a/pitest-aggregator/src/test/resources/full-data/linecoverage.xml +++ b/pitest-aggregator/src/test/resources/full-data/linecoverage.xml @@ -1,28 +1,28 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pitest-aggregator/src/test/resources/full-data/mutations.xml b/pitest-aggregator/src/test/resources/full-data/mutations.xml index 6e16aaef0..f90137254 100644 --- a/pitest-aggregator/src/test/resources/full-data/mutations.xml +++ b/pitest-aggregator/src/test/resources/full-data/mutations.xml @@ -1,27 +1,27 @@ - - - - OrderedWeightedValueSampler.java - com.mycompany.OrderedWeightedValueSampler - <init> - (JLjava/util/function/Consumer;Ljava/util/function/BiFunction;I)V - 77 - org.pitest.mutationtest.engine.gregor.mutators.MathMutator - 61 - com.mycompany.SmallScaleOrderedWeightedValueSamplerTest.shouldSucceedWithVariousGapTimestamps(com.mycompany.SmallScaleOrderedWeightedValueSamplerTest) - Replaced long multiplication with division - 27 - - - OrderedWeightedValueSampler.java - com.mycompany.OrderedWeightedValueSampler - close - ()I - 202 - org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator - 5 - - replaced return of integer sized value with (x == 0 ? 1 : 0) - 38 - + + + + OrderedWeightedValueSampler.java + com.mycompany.OrderedWeightedValueSampler + <init> + (JLjava/util/function/Consumer;Ljava/util/function/BiFunction;I)V + 77 + org.pitest.mutationtest.engine.gregor.mutators.MathMutator + 61 + com.mycompany.SmallScaleOrderedWeightedValueSamplerTest.shouldSucceedWithVariousGapTimestamps(com.mycompany.SmallScaleOrderedWeightedValueSamplerTest) + Replaced long multiplication with division + 27 + + + OrderedWeightedValueSampler.java + com.mycompany.OrderedWeightedValueSampler + close + ()I + 202 + org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator + 5 + + replaced return of integer sized value with (x == 0 ? 1 : 0) + 38 + \ No newline at end of file diff --git a/pitest-aggregator/src/test/resources/snippets/linecoverage.xml b/pitest-aggregator/src/test/resources/snippets/linecoverage.xml index 35b203288..39c12a716 100644 --- a/pitest-aggregator/src/test/resources/snippets/linecoverage.xml +++ b/pitest-aggregator/src/test/resources/snippets/linecoverage.xml @@ -1,5 +1,5 @@ - - - - + + + + \ No newline at end of file diff --git a/pitest-aggregator/src/test/resources/snippets/mutation.xml b/pitest-aggregator/src/test/resources/snippets/mutation.xml index 48413a089..75d015b5d 100644 --- a/pitest-aggregator/src/test/resources/snippets/mutation.xml +++ b/pitest-aggregator/src/test/resources/snippets/mutation.xml @@ -1,12 +1,12 @@ - - OrderedWeightedValueSampler.java - com.mycompany.OrderedWeightedValueSampler - <init> - (JLjava/util/function/Consumer;Ljava/util/function/BiFunction;I)V - 77 - org.pitest.mutationtest.engine.gregor.mutators.MathMutator - 61 - com.mycompany.SmallScaleOrderedWeightedValueSamplerTest.shouldSucceedWithVariousGapTimestamps(com.mycompany.SmallScaleOrderedWeightedValueSamplerTest) - Replaced long multiplication with division - 27 + + OrderedWeightedValueSampler.java + com.mycompany.OrderedWeightedValueSampler + <init> + (JLjava/util/function/Consumer;Ljava/util/function/BiFunction;I)V + 77 + org.pitest.mutationtest.engine.gregor.mutators.MathMutator + 61 + com.mycompany.SmallScaleOrderedWeightedValueSamplerTest.shouldSucceedWithVariousGapTimestamps(com.mycompany.SmallScaleOrderedWeightedValueSamplerTest) + Replaced long multiplication with division + 27 \ No newline at end of file diff --git a/pitest-ant/pom.xml b/pitest-ant/pom.xml index dbaf4e853..da6b272c5 100644 --- a/pitest-ant/pom.xml +++ b/pitest-ant/pom.xml @@ -1,84 +1,84 @@ - - - 4.0.0 - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - pitest-ant - pitest-ant - http://pitest.org - Pitest Ant task. - - - - org.pitest - pitest-command-line - ${project.version} - - - - org.apache.ant - ant - ${ant.version} - provided - - - - - xmlunit - xmlunit - 1.6 - jar - test - - - org.apache.ant - ant-testutil - ${ant.version} - jar - test - - - org.apache.maven - maven-ant-tasks - 2.1.3 - jar - test - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - - - - - - org.pitest:pitest-command-line - - - - - - - - - - - + + + 4.0.0 + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + pitest-ant + pitest-ant + http://pitest.org + Pitest Ant task. + + + + org.pitest + pitest-command-line + ${project.version} + + + + org.apache.ant + ant + ${ant.version} + provided + + + + + xmlunit + xmlunit + 1.6 + jar + test + + + org.apache.ant + ant-testutil + ${ant.version} + jar + test + + + org.apache.maven + maven-ant-tasks + 2.1.3 + jar + test + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + + + + org.pitest:pitest-command-line + + + + + + + + + + + diff --git a/pitest-ant/src/test/java/com/example/PartCovered.java b/pitest-ant/src/test/java/com/example/PartCovered.java index 5026e7b0f..e0234011c 100644 --- a/pitest-ant/src/test/java/com/example/PartCovered.java +++ b/pitest-ant/src/test/java/com/example/PartCovered.java @@ -1,17 +1,17 @@ -package com.example; - -public class PartCovered { - - public int returnsOneProperlytestedByTest() { - return 1; - } - - public int returnsTwoNotCoveredByTest() { - return 2; - } - - public int returnsThreeCoveredButNotTestedByTest() { - return 3; - } - -} +package com.example; + +public class PartCovered { + + public int returnsOneProperlytestedByTest() { + return 1; + } + + public int returnsTwoNotCoveredByTest() { + return 2; + } + + public int returnsThreeCoveredButNotTestedByTest() { + return 3; + } + +} diff --git a/pitest-ant/src/test/java/com/example/PartCoveredTest.java b/pitest-ant/src/test/java/com/example/PartCoveredTest.java index e78ea0374..2419efe77 100644 --- a/pitest-ant/src/test/java/com/example/PartCoveredTest.java +++ b/pitest-ant/src/test/java/com/example/PartCoveredTest.java @@ -1,27 +1,27 @@ -package com.example; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -public class PartCoveredTest { - - private PartCovered testee; - - @Before - public void setUp() { - this.testee = new PartCovered(); - } - - @Test - public void fullyTestReturnsOne() { - assertEquals(1, this.testee.returnsOneProperlytestedByTest()); - } - - @Test - public void coverButDoNotTestReturnsThree() { - this.testee.returnsThreeCoveredButNotTestedByTest(); - } - -} +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class PartCoveredTest { + + private PartCovered testee; + + @Before + public void setUp() { + this.testee = new PartCovered(); + } + + @Test + public void fullyTestReturnsOne() { + assertEquals(1, this.testee.returnsOneProperlytestedByTest()); + } + + @Test + public void coverButDoNotTestReturnsThree() { + this.testee.returnsThreeCoveredButNotTestedByTest(); + } + +} diff --git a/pitest-build-config/pom.xml b/pitest-build-config/pom.xml index 0167397b1..c09eff4e0 100644 --- a/pitest-build-config/pom.xml +++ b/pitest-build-config/pom.xml @@ -1,11 +1,11 @@ - - 4.0.0 - pitest-build-config - Build Config - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - - + + 4.0.0 + pitest-build-config + Build Config + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + + diff --git a/pitest-command-line/pom.xml b/pitest-command-line/pom.xml index 5d190b601..b59e8eaf7 100644 --- a/pitest-command-line/pom.xml +++ b/pitest-command-line/pom.xml @@ -1,84 +1,84 @@ - - - - 4.0.0 - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - pitest-command-line - pitest-command-line - http://pitest.org - Pitest command line tool. - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - org.pitest.mutationtest.commandline.MutationCoverageReport - true - - true - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - - - net.sf.jopt-simple:* - org.pitest:pitest-html-report - - - - - - - - - - - - - - - - - - org.pitest - pitest-entry - ${project.version} - - - org.pitest - pitest-html-report - ${project.version} - - - net.sf.jopt-simple - jopt-simple - 4.9 - - - - - - + + + + 4.0.0 + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + pitest-command-line + pitest-command-line + http://pitest.org + Pitest command line tool. + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.pitest.mutationtest.commandline.MutationCoverageReport + true + + true + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + net.sf.jopt-simple:* + org.pitest:pitest-html-report + + + + + + + + + + + + + + + + + + org.pitest + pitest-entry + ${project.version} + + + org.pitest + pitest-html-report + ${project.version} + + + net.sf.jopt-simple + jopt-simple + 4.9 + + + + + + diff --git a/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/MutationCoverageReport.java b/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/MutationCoverageReport.java index 1b91d45c1..890edd602 100644 --- a/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/MutationCoverageReport.java +++ b/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/MutationCoverageReport.java @@ -1,96 +1,96 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.commandline; - -import java.util.HashMap; - -import org.pitest.coverage.CoverageSummary; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.statistics.MutationStatistics; -import org.pitest.mutationtest.tooling.AnalysisResult; -import org.pitest.mutationtest.tooling.CombinedStatistics; -import org.pitest.mutationtest.tooling.EntryPoint; -import org.pitest.util.Unchecked; - -/** - * Entry point for command line interface - */ -public class MutationCoverageReport { - - public static void main(final String[] args) { - - final PluginServices plugins = PluginServices.makeForContextLoader(); - final OptionsParser parser = new OptionsParser(new PluginFilter(plugins)); - final ParseResult pr = parser.parse(args); - - if (!pr.isOk()) { - parser.printHelp(); - System.out.println(">>>> " + pr.getErrorMessage().get()); - } else { - final ReportOptions data = pr.getOptions(); - - final CombinedStatistics stats = runReport(data, plugins); - - throwErrorIfScoreBelowCoverageThreshold(stats.getCoverageSummary(), - data.getCoverageThreshold()); - throwErrorIfScoreBelowMutationThreshold(stats.getMutationStatistics(), - data.getMutationThreshold()); - throwErrorIfMoreThanMaxSuvivingMutants(stats.getMutationStatistics(), data.getMaximumAllowedSurvivors()); - } - - } - - private static void throwErrorIfScoreBelowCoverageThreshold( - CoverageSummary stats, int threshold) { - if ((threshold != 0) && (stats.getCoverage() < threshold)) { - throw new RuntimeException("Line coverage of " + stats.getCoverage() - + " is below threshold of " + threshold); - } - } - - private static void throwErrorIfScoreBelowMutationThreshold( - final MutationStatistics stats, final int threshold) { - if ((threshold != 0) && (stats.getPercentageDetected() < threshold)) { - throw new RuntimeException("Mutation score of " - + stats.getPercentageDetected() + " is below threshold of " - + threshold); - } - } - - private static void throwErrorIfMoreThanMaxSuvivingMutants( - final MutationStatistics stats, final long threshold) { - if ((threshold > 0) - && (stats.getTotalSurvivingMutations() > threshold)) { - throw new RuntimeException("Had " - + stats.getTotalSurvivingMutations() + " surviving mutants, but only " - + threshold + " survivors allowed"); - } - } - - private static CombinedStatistics runReport(ReportOptions data, - PluginServices plugins) { - - final EntryPoint e = new EntryPoint(); - final AnalysisResult result = e.execute(null, data, plugins, - new HashMap()); - if (result.getError().isPresent()) { - throw Unchecked.translateCheckedException(result.getError().get()); - } - return result.getStatistics().get(); - - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.commandline; + +import java.util.HashMap; + +import org.pitest.coverage.CoverageSummary; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.statistics.MutationStatistics; +import org.pitest.mutationtest.tooling.AnalysisResult; +import org.pitest.mutationtest.tooling.CombinedStatistics; +import org.pitest.mutationtest.tooling.EntryPoint; +import org.pitest.util.Unchecked; + +/** + * Entry point for command line interface + */ +public class MutationCoverageReport { + + public static void main(final String[] args) { + + final PluginServices plugins = PluginServices.makeForContextLoader(); + final OptionsParser parser = new OptionsParser(new PluginFilter(plugins)); + final ParseResult pr = parser.parse(args); + + if (!pr.isOk()) { + parser.printHelp(); + System.out.println(">>>> " + pr.getErrorMessage().get()); + } else { + final ReportOptions data = pr.getOptions(); + + final CombinedStatistics stats = runReport(data, plugins); + + throwErrorIfScoreBelowCoverageThreshold(stats.getCoverageSummary(), + data.getCoverageThreshold()); + throwErrorIfScoreBelowMutationThreshold(stats.getMutationStatistics(), + data.getMutationThreshold()); + throwErrorIfMoreThanMaxSuvivingMutants(stats.getMutationStatistics(), data.getMaximumAllowedSurvivors()); + } + + } + + private static void throwErrorIfScoreBelowCoverageThreshold( + CoverageSummary stats, int threshold) { + if ((threshold != 0) && (stats.getCoverage() < threshold)) { + throw new RuntimeException("Line coverage of " + stats.getCoverage() + + " is below threshold of " + threshold); + } + } + + private static void throwErrorIfScoreBelowMutationThreshold( + final MutationStatistics stats, final int threshold) { + if ((threshold != 0) && (stats.getPercentageDetected() < threshold)) { + throw new RuntimeException("Mutation score of " + + stats.getPercentageDetected() + " is below threshold of " + + threshold); + } + } + + private static void throwErrorIfMoreThanMaxSuvivingMutants( + final MutationStatistics stats, final long threshold) { + if ((threshold > 0) + && (stats.getTotalSurvivingMutations() > threshold)) { + throw new RuntimeException("Had " + + stats.getTotalSurvivingMutations() + " surviving mutants, but only " + + threshold + " survivors allowed"); + } + } + + private static CombinedStatistics runReport(ReportOptions data, + PluginServices plugins) { + + final EntryPoint e = new EntryPoint(); + final AnalysisResult result = e.execute(null, data, plugins, + new HashMap()); + if (result.getError().isPresent()) { + throw Unchecked.translateCheckedException(result.getError().get()); + } + return result.getStatistics().get(); + + } + +} diff --git a/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/OptionsParser.java b/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/OptionsParser.java index abbc1603d..7455cf923 100644 --- a/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/OptionsParser.java +++ b/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/OptionsParser.java @@ -1,475 +1,475 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.commandline; - -import static org.pitest.mutationtest.config.ConfigOption.AVOID_CALLS; -import static org.pitest.mutationtest.config.ConfigOption.CHILD_JVM; -import static org.pitest.mutationtest.config.ConfigOption.CLASSPATH; -import static org.pitest.mutationtest.config.ConfigOption.CLASSPATH_FILE; -import static org.pitest.mutationtest.config.ConfigOption.CODE_PATHS; -import static org.pitest.mutationtest.config.ConfigOption.COVERAGE_THRESHOLD; -import static org.pitest.mutationtest.config.ConfigOption.DEPENDENCY_DISTANCE; -import static org.pitest.mutationtest.config.ConfigOption.EXCLUDED_CLASSES; -import static org.pitest.mutationtest.config.ConfigOption.EXCLUDED_GROUPS; -import static org.pitest.mutationtest.config.ConfigOption.EXCLUDED_METHOD; -import static org.pitest.mutationtest.config.ConfigOption.EXCLUDED_TEST_CLASSES; -import static org.pitest.mutationtest.config.ConfigOption.EXPORT_LINE_COVERAGE; -import static org.pitest.mutationtest.config.ConfigOption.FAIL_WHEN_NOT_MUTATIONS; -import static org.pitest.mutationtest.config.ConfigOption.FEATURES; -import static org.pitest.mutationtest.config.ConfigOption.HISTORY_INPUT_LOCATION; -import static org.pitest.mutationtest.config.ConfigOption.HISTORY_OUTPUT_LOCATION; -import static org.pitest.mutationtest.config.ConfigOption.INCLUDED_GROUPS; -import static org.pitest.mutationtest.config.ConfigOption.INCLUDED_TEST_METHODS; -import static org.pitest.mutationtest.config.ConfigOption.INCLUDE_LAUNCH_CLASSPATH; -import static org.pitest.mutationtest.config.ConfigOption.JVM_PATH; -import static org.pitest.mutationtest.config.ConfigOption.MAX_MUTATIONS_PER_CLASS; -import static org.pitest.mutationtest.config.ConfigOption.MAX_SURVIVING; -import static org.pitest.mutationtest.config.ConfigOption.MUTATIONS; -import static org.pitest.mutationtest.config.ConfigOption.MUTATION_ENGINE; -import static org.pitest.mutationtest.config.ConfigOption.MUTATION_THRESHOLD; -import static org.pitest.mutationtest.config.ConfigOption.MUTATION_UNIT_SIZE; -import static org.pitest.mutationtest.config.ConfigOption.OUTPUT_FORMATS; -import static org.pitest.mutationtest.config.ConfigOption.PLUGIN_CONFIGURATION; -import static org.pitest.mutationtest.config.ConfigOption.REPORT_DIR; -import static org.pitest.mutationtest.config.ConfigOption.SOURCE_DIR; -import static org.pitest.mutationtest.config.ConfigOption.TARGET_CLASSES; -import static org.pitest.mutationtest.config.ConfigOption.TEST_FILTER; -import static org.pitest.mutationtest.config.ConfigOption.TEST_PLUGIN; -import static org.pitest.mutationtest.config.ConfigOption.THREADS; -import static org.pitest.mutationtest.config.ConfigOption.TIMEOUT_CONST; -import static org.pitest.mutationtest.config.ConfigOption.TIMEOUT_FACTOR; -import static org.pitest.mutationtest.config.ConfigOption.TIME_STAMPED_REPORTS; -import static org.pitest.mutationtest.config.ConfigOption.USE_INLINED_CODE_DETECTION; -import static org.pitest.mutationtest.config.ConfigOption.VERBOSE; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.function.Predicate; -import java.util.logging.Logger; - -import org.pitest.classpath.ClassPath; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.config.ConfigOption; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.util.Glob; -import org.pitest.util.Log; -import org.pitest.util.Unchecked; - -import joptsimple.ArgumentAcceptingOptionSpec; -import joptsimple.OptionException; -import joptsimple.OptionParser; -import joptsimple.OptionSet; -import joptsimple.OptionSpec; -import joptsimple.OptionSpecBuilder; -import joptsimple.util.KeyValuePair; - -public class OptionsParser { - - private final Predicate dependencyFilter; - - private static final Logger LOG = Log.getLogger(); - - private final OptionParser parser; - private final ArgumentAcceptingOptionSpec reportDirSpec; - private final OptionSpec targetClassesSpec; - private final OptionSpec targetTestsSpec; - private final OptionSpec avoidCallsSpec; - private final OptionSpec depth; - private final OptionSpec threadsSpec; - private final OptionSpec sourceDirSpec; - private final OptionSpec historyOutputSpec; - private final OptionSpec historyInputSpec; - private final OptionSpec mutators; - private final OptionSpec features; - private final OptionSpec jvmArgs; - private final OptionSpec timeoutFactorSpec; - private final OptionSpec timeoutConstSpec; - private final OptionSpec excludedMethodsSpec; - private final ArgumentAcceptingOptionSpec verboseSpec; - private final OptionSpec excludedClassesSpec; - private final OptionSpec excludedTestClassesSpec; - private final OptionSpec outputFormatSpec; - private final OptionSpec additionalClassPathSpec; - private final OptionSpec classPathFile; - private final ArgumentAcceptingOptionSpec failWhenNoMutations; - private final ArgumentAcceptingOptionSpec codePaths; - private final OptionSpec excludedGroupsSpec; - private final OptionSpec includedGroupsSpec; - private final OptionSpec includedTestMethodsSpec; - private final OptionSpec mutationUnitSizeSpec; - private final ArgumentAcceptingOptionSpec timestampedReportsSpec; - private final ArgumentAcceptingOptionSpec detectInlinedCode; - private final ArgumentAcceptingOptionSpec mutationThreshHoldSpec; - private final ArgumentAcceptingOptionSpec coverageThreshHoldSpec; - private final ArgumentAcceptingOptionSpec maxSurvivingSpec; - private final OptionSpec mutationEngine; - private final ArgumentAcceptingOptionSpec exportLineCoverageSpec; - private final OptionSpec javaExecutable; - private final OptionSpec pluginPropertiesSpec; - private final OptionSpec testPluginSpec; - - private final ArgumentAcceptingOptionSpec includeLaunchClasspathSpec; - - public OptionsParser(Predicate dependencyFilter) { - - this.dependencyFilter = dependencyFilter; - - this.parser = new OptionParser(); - this.parser.acceptsAll(Arrays.asList("h", "?"), "show help"); - - this.testPluginSpec = parserAccepts(TEST_PLUGIN) - .withRequiredArg() - .ofType(String.class) - .defaultsTo("junit") - .describedAs("test plugin to use"); - - this.reportDirSpec = parserAccepts(REPORT_DIR).withRequiredArg() - .describedAs("directory to create report folder in").required(); - - this.targetClassesSpec = parserAccepts(TARGET_CLASSES) - .withRequiredArg() - .ofType(String.class) - .withValuesSeparatedBy(',') - .describedAs( - "comma separated list of filters to match against classes to test") - .required(); - - this.avoidCallsSpec = parserAccepts(AVOID_CALLS) - .withRequiredArg() - .ofType(String.class) - .withValuesSeparatedBy(',') - .describedAs( - "comma separated list of packages to consider as untouchable logging calls"); - - this.targetTestsSpec = parserAccepts(TEST_FILTER) - .withRequiredArg() - .ofType(String.class) - .withValuesSeparatedBy(',') - .describedAs( - "comma separated list of filters to match against tests to run"); - - this.depth = parserAccepts(DEPENDENCY_DISTANCE).withRequiredArg() - .ofType(Integer.class) - .defaultsTo(DEPENDENCY_DISTANCE.getDefault(Integer.class)) - .describedAs("maximum distance to look from test for covered classes"); - - this.threadsSpec = parserAccepts(THREADS).withRequiredArg() - .ofType(Integer.class).defaultsTo(THREADS.getDefault(Integer.class)) - .describedAs("number of threads to use for testing"); - - parserAccepts(MAX_MUTATIONS_PER_CLASS) - .withRequiredArg().ofType(Integer.class) - .defaultsTo(MAX_MUTATIONS_PER_CLASS.getDefault(Integer.class)) - .describedAs("No longer supported. Use CLASSLIMIT(limit[42]) feature instead"); - - this.sourceDirSpec = parserAccepts(SOURCE_DIR).withRequiredArg() - .ofType(File.class).withValuesSeparatedBy(',') - .describedAs("comma separated list of source directories").required(); - - this.mutators = parserAccepts(MUTATIONS).withRequiredArg() - .ofType(String.class).withValuesSeparatedBy(',') - .describedAs("comma separated list of mutation operators"); - - this.features = parserAccepts(FEATURES).withRequiredArg() - .ofType(String.class).withValuesSeparatedBy(',') - .describedAs("comma separated list of features to enable/disable."); - - this.jvmArgs = parserAccepts(CHILD_JVM).withRequiredArg() - .withValuesSeparatedBy(',') - .describedAs("comma separated list of child JVM args"); - - this.detectInlinedCode = parserAccepts(USE_INLINED_CODE_DETECTION) - .withOptionalArg() - .ofType(Boolean.class) - .defaultsTo(true) - .describedAs( - "whether or not to try and detect code inlined from finally blocks"); - - this.timestampedReportsSpec = parserAccepts(TIME_STAMPED_REPORTS) - .withOptionalArg().ofType(Boolean.class).defaultsTo(true) - .describedAs("whether or not to generated timestamped directories"); - - this.timeoutFactorSpec = parserAccepts(TIMEOUT_FACTOR).withOptionalArg() - .ofType(Float.class) - .describedAs("factor to apply to calculate maximum test duration") - .defaultsTo(TIMEOUT_FACTOR.getDefault(Float.class)); - - this.timeoutConstSpec = parserAccepts(TIMEOUT_CONST).withOptionalArg() - .ofType(Long.class) - .describedAs("constant to apply to calculate maximum test duration") - .defaultsTo(TIMEOUT_CONST.getDefault(Long.class)); - - this.excludedMethodsSpec = parserAccepts(EXCLUDED_METHOD) - .withRequiredArg() - .ofType(String.class) - .withValuesSeparatedBy(',') - .describedAs( - "comma separated list of filters to match against methods to exclude from mutation analysis"); - - this.excludedClassesSpec = parserAccepts(EXCLUDED_CLASSES) - .withRequiredArg() - .ofType(String.class) - .withValuesSeparatedBy(',') - .describedAs( - "comma separated list of globs for classes to exclude when mutating"); - - this.excludedTestClassesSpec = parserAccepts(EXCLUDED_TEST_CLASSES) - .withRequiredArg() - .ofType(String.class) - .withValuesSeparatedBy(',') - .describedAs( - "comma separated list of globs of test classes to exclude"); - - this.verboseSpec = parserAccepts(VERBOSE).withOptionalArg() - .ofType(Boolean.class).defaultsTo(true) - .describedAs("whether or not to generate verbose output"); - - this.exportLineCoverageSpec = parserAccepts(EXPORT_LINE_COVERAGE) - .withOptionalArg() - .ofType(Boolean.class) - .defaultsTo(true) - .describedAs( - "whether or not to dump per test line coverage data to disk"); - - this.includeLaunchClasspathSpec = parserAccepts(INCLUDE_LAUNCH_CLASSPATH) - .withOptionalArg().ofType(Boolean.class).defaultsTo(true) - .describedAs("whether or not to analyse launch classpath"); - - this.outputFormatSpec = parserAccepts(OUTPUT_FORMATS) - .withRequiredArg() - .ofType(String.class) - .withValuesSeparatedBy(',') - .describedAs( - "comma separated list of listeners to receive mutation results") - .defaultsTo("HTML"); - - this.additionalClassPathSpec = parserAccepts(CLASSPATH).withRequiredArg() - .ofType(String.class).withValuesSeparatedBy(',') - .describedAs("coma separated list of additional classpath elements"); - - this.classPathFile = this.parserAccepts(CLASSPATH_FILE).withRequiredArg() - .ofType(File.class).describedAs("File with a list of additional classpath elements (one per line)"); - - this.failWhenNoMutations = parserAccepts(FAIL_WHEN_NOT_MUTATIONS) - .withOptionalArg().ofType(Boolean.class).defaultsTo(true) - .describedAs("whether to throw error if no mutations found"); - - this.codePaths = parserAccepts(CODE_PATHS) - .withRequiredArg() - .ofType(String.class) - .withValuesSeparatedBy(',') - .describedAs( - "Globs identifying classpath roots containing mutable code"); - - this.includedGroupsSpec = parserAccepts(INCLUDED_GROUPS).withRequiredArg() - .ofType(String.class).withValuesSeparatedBy(',') - .describedAs("TestNG groups/JUnit categories to include"); - - this.includedTestMethodsSpec = parserAccepts(INCLUDED_TEST_METHODS).withRequiredArg() - .ofType(String.class).withValuesSeparatedBy(',') - .describedAs("Test methods that should be included for challenging the mutants"); - - this.excludedGroupsSpec = parserAccepts(EXCLUDED_GROUPS).withRequiredArg() - .ofType(String.class).withValuesSeparatedBy(',') - .describedAs("TestNG groups/JUnit categories to include"); - - this.mutationUnitSizeSpec = parserAccepts(MUTATION_UNIT_SIZE) - .withRequiredArg() - .ofType(Integer.class) - .describedAs( - "Maximum number of mutations to include within a single unit of analysis") - .defaultsTo(MUTATION_UNIT_SIZE.getDefault(Integer.class)); - - this.historyInputSpec = parserAccepts(HISTORY_INPUT_LOCATION) - .withRequiredArg().ofType(File.class) - .describedAs("File to read history from for incremental analysis"); - - this.historyOutputSpec = parserAccepts(HISTORY_OUTPUT_LOCATION) - .withRequiredArg().ofType(File.class) - .describedAs("File to write history to for incremental analysis"); - - this.mutationThreshHoldSpec = parserAccepts(MUTATION_THRESHOLD) - .withRequiredArg().ofType(Integer.class) - .describedAs("Mutation score below which to throw an error") - .defaultsTo(MUTATION_THRESHOLD.getDefault(Integer.class)); - - this.maxSurvivingSpec = parserAccepts(MAX_SURVIVING) - .withRequiredArg().ofType(Integer.class) - .describedAs("Maximum number of surviving mutants to allow without throwing an error") - .defaultsTo(MAX_SURVIVING.getDefault(Integer.class)); - - this.coverageThreshHoldSpec = parserAccepts(COVERAGE_THRESHOLD) - .withRequiredArg().ofType(Integer.class) - .describedAs("Line coverage below which to throw an error") - .defaultsTo(COVERAGE_THRESHOLD.getDefault(Integer.class)); - - this.mutationEngine = parserAccepts(MUTATION_ENGINE).withRequiredArg() - .ofType(String.class).describedAs("mutation engine to use") - .defaultsTo(MUTATION_ENGINE.getDefault(String.class)); - - this.javaExecutable = parserAccepts(JVM_PATH).withRequiredArg() - .ofType(String.class).describedAs("path to java executable"); - - this.pluginPropertiesSpec = parserAccepts(PLUGIN_CONFIGURATION) - .withRequiredArg().ofType(KeyValuePair.class) - .describedAs("custom plugin properties"); - - } - - private OptionSpecBuilder parserAccepts(final ConfigOption option) { - return this.parser.accepts(option.getParamName()); - } - - public ParseResult parse(final String[] args) { - final ReportOptions data = new ReportOptions(); - try { - final OptionSet userArgs = this.parser.parse(args); - return parseCommandLine(data, userArgs); - - } catch (final OptionException uoe) { - return new ParseResult(data, uoe.getLocalizedMessage()); - } - } - - /** - * Creates a new ParseResult object using the command line arguments. - * - * @param data - * the ReportOptions to populate. - * @param userArgs - * the OptionSet which contains the command line arguments. - * @return a new ParseResult, correctly configured using the command line - * arguments. - */ - private ParseResult parseCommandLine(final ReportOptions data, - final OptionSet userArgs) { - data.setTestPlugin(userArgs.valueOf(this.testPluginSpec)); - data.setReportDir(userArgs.valueOf(this.reportDirSpec)); - data.setTargetClasses(this.targetClassesSpec.values(userArgs)); - data.setTargetTests(FCollection.map(this.targetTestsSpec.values(userArgs), - Glob.toGlobPredicate())); - data.setSourceDirs(this.sourceDirSpec.values(userArgs)); - data.setMutators(this.mutators.values(userArgs)); - data.setFeatures(this.features.values(userArgs)); - data.setDependencyAnalysisMaxDistance(this.depth.value(userArgs)); - data.addChildJVMArgs(this.jvmArgs.values(userArgs)); - - - data.setDetectInlinedCode(userArgs.has(this.detectInlinedCode) - && userArgs.valueOf(this.detectInlinedCode)); - - data.setIncludeLaunchClasspath(userArgs - .valueOf(this.includeLaunchClasspathSpec)); - - data.setShouldCreateTimestampedReports(userArgs - .valueOf(this.timestampedReportsSpec)); - data.setNumberOfThreads(this.threadsSpec.value(userArgs)); - data.setTimeoutFactor(this.timeoutFactorSpec.value(userArgs)); - data.setTimeoutConstant(this.timeoutConstSpec.value(userArgs)); - data.setLoggingClasses(this.avoidCallsSpec.values(userArgs)); - data.setExcludedMethods(this.excludedMethodsSpec.values(userArgs)); - data.setExcludedClasses(this.excludedClassesSpec.values(userArgs)); - data.setExcludedTestClasses(FCollection.map( - this.excludedTestClassesSpec.values(userArgs), Glob.toGlobPredicate())); - data.setVerbose(userArgs.has(this.verboseSpec) - && userArgs.valueOf(this.verboseSpec)); - - data.addOutputFormats(this.outputFormatSpec.values(userArgs)); - data.setFailWhenNoMutations(this.failWhenNoMutations.value(userArgs)); - data.setCodePaths(this.codePaths.values(userArgs)); - data.setMutationUnitSize(this.mutationUnitSizeSpec.value(userArgs)); - - data.setHistoryInputLocation(this.historyInputSpec.value(userArgs)); - data.setHistoryOutputLocation(this.historyOutputSpec.value(userArgs)); - data.setMutationThreshold(this.mutationThreshHoldSpec.value(userArgs)); - data.setMaximumAllowedSurvivors(this.maxSurvivingSpec.value(userArgs)); - data.setCoverageThreshold(this.coverageThreshHoldSpec.value(userArgs)); - data.setMutationEngine(this.mutationEngine.value(userArgs)); - data.setFreeFormProperties(listToProperties(this.pluginPropertiesSpec - .values(userArgs))); - - data.setExportLineCoverage(userArgs.has(this.exportLineCoverageSpec) - && userArgs.valueOf(this.exportLineCoverageSpec)); - - setClassPath(userArgs, data); - - setTestGroups(userArgs, data); - - data.setIncludedTestMethods(this.includedTestMethodsSpec.values(userArgs)); - data.setJavaExecutable(this.javaExecutable.value(userArgs)); - - if (userArgs.has("?")) { - return new ParseResult(data, "See above for supported parameters."); - } else { - return new ParseResult(data, null); - } - } - - private void setClassPath(final OptionSet userArgs, final ReportOptions data) { - - final List elements = new ArrayList<>(); - if (data.isIncludeLaunchClasspath()) { - elements.addAll(ClassPath.getClassPathElementsAsPaths()); - } else { - elements.addAll(FCollection.filter( - ClassPath.getClassPathElementsAsPaths(), this.dependencyFilter)); - } - if (userArgs.has(this.classPathFile)) { - try (BufferedReader classPathFileBR = new BufferedReader(new FileReader(userArgs.valueOf(this.classPathFile).getAbsoluteFile()))) { - String element; - while ((element = classPathFileBR.readLine()) != null) { - elements.add(element); - } - } catch (final IOException ioe) { - LOG.warning("Unable to read class path file:" + userArgs.valueOf(this.classPathFile).getAbsolutePath() + " - " - + ioe.getMessage()); - } - } - elements.addAll(userArgs.valuesOf(this.additionalClassPathSpec)); - data.setClassPathElements(elements); - } - - private void setTestGroups(final OptionSet userArgs, final ReportOptions data) { - final TestGroupConfig conf = new TestGroupConfig( - this.excludedGroupsSpec.values(userArgs), - this.includedGroupsSpec.values(userArgs)); - - data.setGroupConfig(conf); - } - - private Properties listToProperties(List kvps) { - final Properties p = new Properties(); - for (final KeyValuePair kvp : kvps) { - p.put(kvp.key, kvp.value); - } - return p; - } - - public void printHelp() { - try { - this.parser.printHelpOn(System.out); - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.commandline; + +import static org.pitest.mutationtest.config.ConfigOption.AVOID_CALLS; +import static org.pitest.mutationtest.config.ConfigOption.CHILD_JVM; +import static org.pitest.mutationtest.config.ConfigOption.CLASSPATH; +import static org.pitest.mutationtest.config.ConfigOption.CLASSPATH_FILE; +import static org.pitest.mutationtest.config.ConfigOption.CODE_PATHS; +import static org.pitest.mutationtest.config.ConfigOption.COVERAGE_THRESHOLD; +import static org.pitest.mutationtest.config.ConfigOption.DEPENDENCY_DISTANCE; +import static org.pitest.mutationtest.config.ConfigOption.EXCLUDED_CLASSES; +import static org.pitest.mutationtest.config.ConfigOption.EXCLUDED_GROUPS; +import static org.pitest.mutationtest.config.ConfigOption.EXCLUDED_METHOD; +import static org.pitest.mutationtest.config.ConfigOption.EXCLUDED_TEST_CLASSES; +import static org.pitest.mutationtest.config.ConfigOption.EXPORT_LINE_COVERAGE; +import static org.pitest.mutationtest.config.ConfigOption.FAIL_WHEN_NOT_MUTATIONS; +import static org.pitest.mutationtest.config.ConfigOption.FEATURES; +import static org.pitest.mutationtest.config.ConfigOption.HISTORY_INPUT_LOCATION; +import static org.pitest.mutationtest.config.ConfigOption.HISTORY_OUTPUT_LOCATION; +import static org.pitest.mutationtest.config.ConfigOption.INCLUDED_GROUPS; +import static org.pitest.mutationtest.config.ConfigOption.INCLUDED_TEST_METHODS; +import static org.pitest.mutationtest.config.ConfigOption.INCLUDE_LAUNCH_CLASSPATH; +import static org.pitest.mutationtest.config.ConfigOption.JVM_PATH; +import static org.pitest.mutationtest.config.ConfigOption.MAX_MUTATIONS_PER_CLASS; +import static org.pitest.mutationtest.config.ConfigOption.MAX_SURVIVING; +import static org.pitest.mutationtest.config.ConfigOption.MUTATIONS; +import static org.pitest.mutationtest.config.ConfigOption.MUTATION_ENGINE; +import static org.pitest.mutationtest.config.ConfigOption.MUTATION_THRESHOLD; +import static org.pitest.mutationtest.config.ConfigOption.MUTATION_UNIT_SIZE; +import static org.pitest.mutationtest.config.ConfigOption.OUTPUT_FORMATS; +import static org.pitest.mutationtest.config.ConfigOption.PLUGIN_CONFIGURATION; +import static org.pitest.mutationtest.config.ConfigOption.REPORT_DIR; +import static org.pitest.mutationtest.config.ConfigOption.SOURCE_DIR; +import static org.pitest.mutationtest.config.ConfigOption.TARGET_CLASSES; +import static org.pitest.mutationtest.config.ConfigOption.TEST_FILTER; +import static org.pitest.mutationtest.config.ConfigOption.TEST_PLUGIN; +import static org.pitest.mutationtest.config.ConfigOption.THREADS; +import static org.pitest.mutationtest.config.ConfigOption.TIMEOUT_CONST; +import static org.pitest.mutationtest.config.ConfigOption.TIMEOUT_FACTOR; +import static org.pitest.mutationtest.config.ConfigOption.TIME_STAMPED_REPORTS; +import static org.pitest.mutationtest.config.ConfigOption.USE_INLINED_CODE_DETECTION; +import static org.pitest.mutationtest.config.ConfigOption.VERBOSE; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import java.util.function.Predicate; +import java.util.logging.Logger; + +import org.pitest.classpath.ClassPath; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.config.ConfigOption; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.util.Glob; +import org.pitest.util.Log; +import org.pitest.util.Unchecked; + +import joptsimple.ArgumentAcceptingOptionSpec; +import joptsimple.OptionException; +import joptsimple.OptionParser; +import joptsimple.OptionSet; +import joptsimple.OptionSpec; +import joptsimple.OptionSpecBuilder; +import joptsimple.util.KeyValuePair; + +public class OptionsParser { + + private final Predicate dependencyFilter; + + private static final Logger LOG = Log.getLogger(); + + private final OptionParser parser; + private final ArgumentAcceptingOptionSpec reportDirSpec; + private final OptionSpec targetClassesSpec; + private final OptionSpec targetTestsSpec; + private final OptionSpec avoidCallsSpec; + private final OptionSpec depth; + private final OptionSpec threadsSpec; + private final OptionSpec sourceDirSpec; + private final OptionSpec historyOutputSpec; + private final OptionSpec historyInputSpec; + private final OptionSpec mutators; + private final OptionSpec features; + private final OptionSpec jvmArgs; + private final OptionSpec timeoutFactorSpec; + private final OptionSpec timeoutConstSpec; + private final OptionSpec excludedMethodsSpec; + private final ArgumentAcceptingOptionSpec verboseSpec; + private final OptionSpec excludedClassesSpec; + private final OptionSpec excludedTestClassesSpec; + private final OptionSpec outputFormatSpec; + private final OptionSpec additionalClassPathSpec; + private final OptionSpec classPathFile; + private final ArgumentAcceptingOptionSpec failWhenNoMutations; + private final ArgumentAcceptingOptionSpec codePaths; + private final OptionSpec excludedGroupsSpec; + private final OptionSpec includedGroupsSpec; + private final OptionSpec includedTestMethodsSpec; + private final OptionSpec mutationUnitSizeSpec; + private final ArgumentAcceptingOptionSpec timestampedReportsSpec; + private final ArgumentAcceptingOptionSpec detectInlinedCode; + private final ArgumentAcceptingOptionSpec mutationThreshHoldSpec; + private final ArgumentAcceptingOptionSpec coverageThreshHoldSpec; + private final ArgumentAcceptingOptionSpec maxSurvivingSpec; + private final OptionSpec mutationEngine; + private final ArgumentAcceptingOptionSpec exportLineCoverageSpec; + private final OptionSpec javaExecutable; + private final OptionSpec pluginPropertiesSpec; + private final OptionSpec testPluginSpec; + + private final ArgumentAcceptingOptionSpec includeLaunchClasspathSpec; + + public OptionsParser(Predicate dependencyFilter) { + + this.dependencyFilter = dependencyFilter; + + this.parser = new OptionParser(); + this.parser.acceptsAll(Arrays.asList("h", "?"), "show help"); + + this.testPluginSpec = parserAccepts(TEST_PLUGIN) + .withRequiredArg() + .ofType(String.class) + .defaultsTo("junit") + .describedAs("test plugin to use"); + + this.reportDirSpec = parserAccepts(REPORT_DIR).withRequiredArg() + .describedAs("directory to create report folder in").required(); + + this.targetClassesSpec = parserAccepts(TARGET_CLASSES) + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .describedAs( + "comma separated list of filters to match against classes to test") + .required(); + + this.avoidCallsSpec = parserAccepts(AVOID_CALLS) + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .describedAs( + "comma separated list of packages to consider as untouchable logging calls"); + + this.targetTestsSpec = parserAccepts(TEST_FILTER) + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .describedAs( + "comma separated list of filters to match against tests to run"); + + this.depth = parserAccepts(DEPENDENCY_DISTANCE).withRequiredArg() + .ofType(Integer.class) + .defaultsTo(DEPENDENCY_DISTANCE.getDefault(Integer.class)) + .describedAs("maximum distance to look from test for covered classes"); + + this.threadsSpec = parserAccepts(THREADS).withRequiredArg() + .ofType(Integer.class).defaultsTo(THREADS.getDefault(Integer.class)) + .describedAs("number of threads to use for testing"); + + parserAccepts(MAX_MUTATIONS_PER_CLASS) + .withRequiredArg().ofType(Integer.class) + .defaultsTo(MAX_MUTATIONS_PER_CLASS.getDefault(Integer.class)) + .describedAs("No longer supported. Use CLASSLIMIT(limit[42]) feature instead"); + + this.sourceDirSpec = parserAccepts(SOURCE_DIR).withRequiredArg() + .ofType(File.class).withValuesSeparatedBy(',') + .describedAs("comma separated list of source directories").required(); + + this.mutators = parserAccepts(MUTATIONS).withRequiredArg() + .ofType(String.class).withValuesSeparatedBy(',') + .describedAs("comma separated list of mutation operators"); + + this.features = parserAccepts(FEATURES).withRequiredArg() + .ofType(String.class).withValuesSeparatedBy(',') + .describedAs("comma separated list of features to enable/disable."); + + this.jvmArgs = parserAccepts(CHILD_JVM).withRequiredArg() + .withValuesSeparatedBy(',') + .describedAs("comma separated list of child JVM args"); + + this.detectInlinedCode = parserAccepts(USE_INLINED_CODE_DETECTION) + .withOptionalArg() + .ofType(Boolean.class) + .defaultsTo(true) + .describedAs( + "whether or not to try and detect code inlined from finally blocks"); + + this.timestampedReportsSpec = parserAccepts(TIME_STAMPED_REPORTS) + .withOptionalArg().ofType(Boolean.class).defaultsTo(true) + .describedAs("whether or not to generated timestamped directories"); + + this.timeoutFactorSpec = parserAccepts(TIMEOUT_FACTOR).withOptionalArg() + .ofType(Float.class) + .describedAs("factor to apply to calculate maximum test duration") + .defaultsTo(TIMEOUT_FACTOR.getDefault(Float.class)); + + this.timeoutConstSpec = parserAccepts(TIMEOUT_CONST).withOptionalArg() + .ofType(Long.class) + .describedAs("constant to apply to calculate maximum test duration") + .defaultsTo(TIMEOUT_CONST.getDefault(Long.class)); + + this.excludedMethodsSpec = parserAccepts(EXCLUDED_METHOD) + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .describedAs( + "comma separated list of filters to match against methods to exclude from mutation analysis"); + + this.excludedClassesSpec = parserAccepts(EXCLUDED_CLASSES) + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .describedAs( + "comma separated list of globs for classes to exclude when mutating"); + + this.excludedTestClassesSpec = parserAccepts(EXCLUDED_TEST_CLASSES) + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .describedAs( + "comma separated list of globs of test classes to exclude"); + + this.verboseSpec = parserAccepts(VERBOSE).withOptionalArg() + .ofType(Boolean.class).defaultsTo(true) + .describedAs("whether or not to generate verbose output"); + + this.exportLineCoverageSpec = parserAccepts(EXPORT_LINE_COVERAGE) + .withOptionalArg() + .ofType(Boolean.class) + .defaultsTo(true) + .describedAs( + "whether or not to dump per test line coverage data to disk"); + + this.includeLaunchClasspathSpec = parserAccepts(INCLUDE_LAUNCH_CLASSPATH) + .withOptionalArg().ofType(Boolean.class).defaultsTo(true) + .describedAs("whether or not to analyse launch classpath"); + + this.outputFormatSpec = parserAccepts(OUTPUT_FORMATS) + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .describedAs( + "comma separated list of listeners to receive mutation results") + .defaultsTo("HTML"); + + this.additionalClassPathSpec = parserAccepts(CLASSPATH).withRequiredArg() + .ofType(String.class).withValuesSeparatedBy(',') + .describedAs("coma separated list of additional classpath elements"); + + this.classPathFile = this.parserAccepts(CLASSPATH_FILE).withRequiredArg() + .ofType(File.class).describedAs("File with a list of additional classpath elements (one per line)"); + + this.failWhenNoMutations = parserAccepts(FAIL_WHEN_NOT_MUTATIONS) + .withOptionalArg().ofType(Boolean.class).defaultsTo(true) + .describedAs("whether to throw error if no mutations found"); + + this.codePaths = parserAccepts(CODE_PATHS) + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .describedAs( + "Globs identifying classpath roots containing mutable code"); + + this.includedGroupsSpec = parserAccepts(INCLUDED_GROUPS).withRequiredArg() + .ofType(String.class).withValuesSeparatedBy(',') + .describedAs("TestNG groups/JUnit categories to include"); + + this.includedTestMethodsSpec = parserAccepts(INCLUDED_TEST_METHODS).withRequiredArg() + .ofType(String.class).withValuesSeparatedBy(',') + .describedAs("Test methods that should be included for challenging the mutants"); + + this.excludedGroupsSpec = parserAccepts(EXCLUDED_GROUPS).withRequiredArg() + .ofType(String.class).withValuesSeparatedBy(',') + .describedAs("TestNG groups/JUnit categories to include"); + + this.mutationUnitSizeSpec = parserAccepts(MUTATION_UNIT_SIZE) + .withRequiredArg() + .ofType(Integer.class) + .describedAs( + "Maximum number of mutations to include within a single unit of analysis") + .defaultsTo(MUTATION_UNIT_SIZE.getDefault(Integer.class)); + + this.historyInputSpec = parserAccepts(HISTORY_INPUT_LOCATION) + .withRequiredArg().ofType(File.class) + .describedAs("File to read history from for incremental analysis"); + + this.historyOutputSpec = parserAccepts(HISTORY_OUTPUT_LOCATION) + .withRequiredArg().ofType(File.class) + .describedAs("File to write history to for incremental analysis"); + + this.mutationThreshHoldSpec = parserAccepts(MUTATION_THRESHOLD) + .withRequiredArg().ofType(Integer.class) + .describedAs("Mutation score below which to throw an error") + .defaultsTo(MUTATION_THRESHOLD.getDefault(Integer.class)); + + this.maxSurvivingSpec = parserAccepts(MAX_SURVIVING) + .withRequiredArg().ofType(Integer.class) + .describedAs("Maximum number of surviving mutants to allow without throwing an error") + .defaultsTo(MAX_SURVIVING.getDefault(Integer.class)); + + this.coverageThreshHoldSpec = parserAccepts(COVERAGE_THRESHOLD) + .withRequiredArg().ofType(Integer.class) + .describedAs("Line coverage below which to throw an error") + .defaultsTo(COVERAGE_THRESHOLD.getDefault(Integer.class)); + + this.mutationEngine = parserAccepts(MUTATION_ENGINE).withRequiredArg() + .ofType(String.class).describedAs("mutation engine to use") + .defaultsTo(MUTATION_ENGINE.getDefault(String.class)); + + this.javaExecutable = parserAccepts(JVM_PATH).withRequiredArg() + .ofType(String.class).describedAs("path to java executable"); + + this.pluginPropertiesSpec = parserAccepts(PLUGIN_CONFIGURATION) + .withRequiredArg().ofType(KeyValuePair.class) + .describedAs("custom plugin properties"); + + } + + private OptionSpecBuilder parserAccepts(final ConfigOption option) { + return this.parser.accepts(option.getParamName()); + } + + public ParseResult parse(final String[] args) { + final ReportOptions data = new ReportOptions(); + try { + final OptionSet userArgs = this.parser.parse(args); + return parseCommandLine(data, userArgs); + + } catch (final OptionException uoe) { + return new ParseResult(data, uoe.getLocalizedMessage()); + } + } + + /** + * Creates a new ParseResult object using the command line arguments. + * + * @param data + * the ReportOptions to populate. + * @param userArgs + * the OptionSet which contains the command line arguments. + * @return a new ParseResult, correctly configured using the command line + * arguments. + */ + private ParseResult parseCommandLine(final ReportOptions data, + final OptionSet userArgs) { + data.setTestPlugin(userArgs.valueOf(this.testPluginSpec)); + data.setReportDir(userArgs.valueOf(this.reportDirSpec)); + data.setTargetClasses(this.targetClassesSpec.values(userArgs)); + data.setTargetTests(FCollection.map(this.targetTestsSpec.values(userArgs), + Glob.toGlobPredicate())); + data.setSourceDirs(this.sourceDirSpec.values(userArgs)); + data.setMutators(this.mutators.values(userArgs)); + data.setFeatures(this.features.values(userArgs)); + data.setDependencyAnalysisMaxDistance(this.depth.value(userArgs)); + data.addChildJVMArgs(this.jvmArgs.values(userArgs)); + + + data.setDetectInlinedCode(userArgs.has(this.detectInlinedCode) + && userArgs.valueOf(this.detectInlinedCode)); + + data.setIncludeLaunchClasspath(userArgs + .valueOf(this.includeLaunchClasspathSpec)); + + data.setShouldCreateTimestampedReports(userArgs + .valueOf(this.timestampedReportsSpec)); + data.setNumberOfThreads(this.threadsSpec.value(userArgs)); + data.setTimeoutFactor(this.timeoutFactorSpec.value(userArgs)); + data.setTimeoutConstant(this.timeoutConstSpec.value(userArgs)); + data.setLoggingClasses(this.avoidCallsSpec.values(userArgs)); + data.setExcludedMethods(this.excludedMethodsSpec.values(userArgs)); + data.setExcludedClasses(this.excludedClassesSpec.values(userArgs)); + data.setExcludedTestClasses(FCollection.map( + this.excludedTestClassesSpec.values(userArgs), Glob.toGlobPredicate())); + data.setVerbose(userArgs.has(this.verboseSpec) + && userArgs.valueOf(this.verboseSpec)); + + data.addOutputFormats(this.outputFormatSpec.values(userArgs)); + data.setFailWhenNoMutations(this.failWhenNoMutations.value(userArgs)); + data.setCodePaths(this.codePaths.values(userArgs)); + data.setMutationUnitSize(this.mutationUnitSizeSpec.value(userArgs)); + + data.setHistoryInputLocation(this.historyInputSpec.value(userArgs)); + data.setHistoryOutputLocation(this.historyOutputSpec.value(userArgs)); + data.setMutationThreshold(this.mutationThreshHoldSpec.value(userArgs)); + data.setMaximumAllowedSurvivors(this.maxSurvivingSpec.value(userArgs)); + data.setCoverageThreshold(this.coverageThreshHoldSpec.value(userArgs)); + data.setMutationEngine(this.mutationEngine.value(userArgs)); + data.setFreeFormProperties(listToProperties(this.pluginPropertiesSpec + .values(userArgs))); + + data.setExportLineCoverage(userArgs.has(this.exportLineCoverageSpec) + && userArgs.valueOf(this.exportLineCoverageSpec)); + + setClassPath(userArgs, data); + + setTestGroups(userArgs, data); + + data.setIncludedTestMethods(this.includedTestMethodsSpec.values(userArgs)); + data.setJavaExecutable(this.javaExecutable.value(userArgs)); + + if (userArgs.has("?")) { + return new ParseResult(data, "See above for supported parameters."); + } else { + return new ParseResult(data, null); + } + } + + private void setClassPath(final OptionSet userArgs, final ReportOptions data) { + + final List elements = new ArrayList<>(); + if (data.isIncludeLaunchClasspath()) { + elements.addAll(ClassPath.getClassPathElementsAsPaths()); + } else { + elements.addAll(FCollection.filter( + ClassPath.getClassPathElementsAsPaths(), this.dependencyFilter)); + } + if (userArgs.has(this.classPathFile)) { + try (BufferedReader classPathFileBR = new BufferedReader(new FileReader(userArgs.valueOf(this.classPathFile).getAbsoluteFile()))) { + String element; + while ((element = classPathFileBR.readLine()) != null) { + elements.add(element); + } + } catch (final IOException ioe) { + LOG.warning("Unable to read class path file:" + userArgs.valueOf(this.classPathFile).getAbsolutePath() + " - " + + ioe.getMessage()); + } + } + elements.addAll(userArgs.valuesOf(this.additionalClassPathSpec)); + data.setClassPathElements(elements); + } + + private void setTestGroups(final OptionSet userArgs, final ReportOptions data) { + final TestGroupConfig conf = new TestGroupConfig( + this.excludedGroupsSpec.values(userArgs), + this.includedGroupsSpec.values(userArgs)); + + data.setGroupConfig(conf); + } + + private Properties listToProperties(List kvps) { + final Properties p = new Properties(); + for (final KeyValuePair kvp : kvps) { + p.put(kvp.key, kvp.value); + } + return p; + } + + public void printHelp() { + try { + this.parser.printHelpOn(System.out); + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex); + } + } + +} diff --git a/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/ParseResult.java b/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/ParseResult.java index eab29e2e1..4dcdb412f 100644 --- a/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/ParseResult.java +++ b/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/ParseResult.java @@ -1,42 +1,42 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.commandline; - -import java.util.Optional; -import org.pitest.mutationtest.config.ReportOptions; - -public class ParseResult { - - private final ReportOptions options; - private final Optional errorMessage; - - public ParseResult(final ReportOptions options, final String errorMessage) { - this.options = options; - this.errorMessage = Optional.ofNullable(errorMessage); - } - - public boolean isOk() { - return !this.errorMessage.isPresent(); - } - - public ReportOptions getOptions() { - return this.options; - } - - public Optional getErrorMessage() { - return this.errorMessage; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.commandline; + +import java.util.Optional; +import org.pitest.mutationtest.config.ReportOptions; + +public class ParseResult { + + private final ReportOptions options; + private final Optional errorMessage; + + public ParseResult(final ReportOptions options, final String errorMessage) { + this.options = options; + this.errorMessage = Optional.ofNullable(errorMessage); + } + + public boolean isOk() { + return !this.errorMessage.isPresent(); + } + + public ReportOptions getOptions() { + return this.options; + } + + public Optional getErrorMessage() { + return this.errorMessage; + } + +} diff --git a/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/PluginFilter.java b/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/PluginFilter.java index 7aed7d443..db2da0dea 100644 --- a/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/PluginFilter.java +++ b/pitest-command-line/src/main/java/org/pitest/mutationtest/commandline/PluginFilter.java @@ -1,51 +1,51 @@ -package org.pitest.mutationtest.commandline; - -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.plugin.ClientClasspathPlugin; -import org.pitest.util.PitError; - -public class PluginFilter implements Predicate { - - private final Set includedClassPathElement = new HashSet<>(); - - public PluginFilter(final PluginServices plugin) { - FCollection.mapTo(plugin.findClientClasspathPlugins(), classToLocation(), - this.includedClassPathElement); - } - - private static Function classToLocation() { - return new Function() { - @Override - public String apply(final ClientClasspathPlugin a) { - try { - return new File(a.getClass().getProtectionDomain().getCodeSource() - .getLocation().toURI()).getCanonicalPath(); - } catch (final IOException ex) { - throw createPitErrorForExceptionOnClass(ex, a); - } catch (final URISyntaxException ex) { - throw createPitErrorForExceptionOnClass(ex, a); - } - } - - private PitError createPitErrorForExceptionOnClass(final Exception ex, - final ClientClasspathPlugin clazz) { - return new PitError("Error getting location of class " + clazz, ex); - } - }; - } - - @Override - public boolean test(final String a) { - return this.includedClassPathElement.contains(a); - } - -} +package org.pitest.mutationtest.commandline; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.plugin.ClientClasspathPlugin; +import org.pitest.util.PitError; + +public class PluginFilter implements Predicate { + + private final Set includedClassPathElement = new HashSet<>(); + + public PluginFilter(final PluginServices plugin) { + FCollection.mapTo(plugin.findClientClasspathPlugins(), classToLocation(), + this.includedClassPathElement); + } + + private static Function classToLocation() { + return new Function() { + @Override + public String apply(final ClientClasspathPlugin a) { + try { + return new File(a.getClass().getProtectionDomain().getCodeSource() + .getLocation().toURI()).getCanonicalPath(); + } catch (final IOException ex) { + throw createPitErrorForExceptionOnClass(ex, a); + } catch (final URISyntaxException ex) { + throw createPitErrorForExceptionOnClass(ex, a); + } + } + + private PitError createPitErrorForExceptionOnClass(final Exception ex, + final ClientClasspathPlugin clazz) { + return new PitError("Error getting location of class " + clazz, ex); + } + }; + } + + @Override + public boolean test(final String a) { + return this.includedClassPathElement.contains(a); + } + +} diff --git a/pitest-command-line/src/test/java/org/pitest/mutationtest/commandline/OptionsParserTest.java b/pitest-command-line/src/test/java/org/pitest/mutationtest/commandline/OptionsParserTest.java index 05b90a56f..a7cb70837 100644 --- a/pitest-command-line/src/test/java/org/pitest/mutationtest/commandline/OptionsParserTest.java +++ b/pitest-command-line/src/test/java/org/pitest/mutationtest/commandline/OptionsParserTest.java @@ -1,525 +1,525 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.commandline; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.mutationtest.config.ConfigOption; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.engine.gregor.GregorMutationEngine; -import org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator; -import org.pitest.mutationtest.engine.gregor.mutators.MathMutator; - -public class OptionsParserTest { - - private static final String JAVA_PATH_SEPARATOR = "/"; - - private static final String JAVA_CLASS_PATH_PROPERTY = "java.class.path"; - - private OptionsParser testee; - - @Mock - private Predicate filter; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - when(this.filter.test(any(String.class))).thenReturn(true); - this.testee = new OptionsParser(this.filter); - } - - @Test - public void shouldParseTestPlugin() { - final String value = "foo"; - final ReportOptions actual = parseAddingRequiredArgs("--testPlugin", value); - assertEquals(value, actual.getTestPlugin()); - } - - @Test - public void shouldParseReportDir() { - final String value = "foo"; - final ReportOptions actual = parseAddingRequiredArgs("--reportDir", value); - assertEquals(value, actual.getReportDir()); - } - - @Test - public void shouldCreatePredicateFromCommaSeparatedListOfTargetClassGlobs() { - final ReportOptions actual = parseAddingRequiredArgs("--targetClasses", - "foo*,bar*"); - final Predicate actualPredicate = actual.getTargetClassesFilter(); - assertTrue(actualPredicate.test("foo_anything")); - assertTrue(actualPredicate.test("bar_anything")); - assertFalse(actualPredicate.test("notfoobar")); - } - - @Test - public void shouldParseCommaSeparatedListOfSourceDirectories() { - final ReportOptions actual = parseAddingRequiredArgs("--sourceDirs", - "foo/bar,bar/far"); - assertEquals(Arrays.asList(new File("foo/bar"), new File("bar/far")), actual.getSourceDirs()); - } - - @Test - public void shouldParseMaxDepenencyDistance() { - final ReportOptions actual = parseAddingRequiredArgs( - "--dependencyDistance", "42"); - assertEquals(42, actual.getDependencyAnalysisMaxDistance()); - } - - @Test - public void shouldParseCommaSeparatedListOfJVMArgs() { - final ReportOptions actual = parseAddingRequiredArgs("--jvmArgs", "foo,bar"); - assertEquals(Arrays.asList("foo", "bar"), actual.getJvmArgs()); - } - - @Test - public void shouldParseCommaSeparatedListOfMutationOperators() { - final ReportOptions actual = parseAddingRequiredArgs("--mutators", - ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR.name() + "," - + MathMutator.MATH_MUTATOR.name()); - assertEquals(Arrays.asList( - ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR.name(), - MathMutator.MATH_MUTATOR.name()), actual.getMutators()); - } - - @Test - public void shouldParseCommaSeparatedListOfFeatures() { - final ReportOptions actual = parseAddingRequiredArgs("--features", "+FOO(),-BAR(value=1 & value=2)"); - assertThat(actual.getFeatures()).contains("+FOO()", "-BAR(value=1 & value=2)"); - } - - @Test - public void shouldNotDetectInlinedCodeByDefault() { - final ReportOptions actual = parseAddingRequiredArgs(""); - assertFalse(actual.isDetectInlinedCode()); - } - - @Test - public void shouldDetermineIfInlinedCodeFlagIsSet() { - final ReportOptions actual = parseAddingRequiredArgs("--detectInlinedCode"); - assertTrue(actual.isDetectInlinedCode()); - } - - @Test - public void shouldDetermineIfInlinedCodeFlagIsSetWhenFalseSupplied() { - final ReportOptions actual = parseAddingRequiredArgs("--detectInlinedCode=false"); - assertFalse(actual.isDetectInlinedCode()); - } - - @Test - public void shouldCreateTimestampedReportsByDefault() { - final ReportOptions actual = parseAddingRequiredArgs(); - assertTrue(actual.shouldCreateTimeStampedReports()); - } - - @Test - public void shouldDetermineIfSuppressTimestampedReportsFlagIsSet() { - final ReportOptions actual = parseAddingRequiredArgs("--timestampedReports"); - assertTrue(actual.shouldCreateTimeStampedReports()); - } - - @Test - public void shouldDetermineIfSuppressTimestampedReportsFlagIsSetWhenFalseSupplied() { - final ReportOptions actual = parseAddingRequiredArgs("--timestampedReports=false"); - assertFalse(actual.shouldCreateTimeStampedReports()); - } - - @Test - public void shouldParseNumberOfThreads() { - final ReportOptions actual = parseAddingRequiredArgs("--threads", "42"); - assertEquals(42, actual.getNumberOfThreads()); - } - - @Test - public void shouldParseTimeOutFactor() { - final ReportOptions actual = parseAddingRequiredArgs("--timeoutFactor", - "1.32"); - assertEquals(1.32f, actual.getTimeoutFactor(), 0.1); - } - - @Test - public void shouldParseTimeOutConstant() { - final ReportOptions actual = parseAddingRequiredArgs("--timeoutConst", "42"); - assertEquals(42, actual.getTimeoutConstant()); - } - - @Test - public void shouldParseCommaSeparatedListOfTargetTestClassGlobs() { - final ReportOptions actual = parseAddingRequiredArgs("--targetTest", - "foo*,bar*"); - final Predicate actualPredicate = actual.getTargetTestsFilter(); - assertTrue(actualPredicate.test("foo_anything")); - assertTrue(actualPredicate.test("bar_anything")); - assertFalse(actualPredicate.test("notfoobar")); - } - - @Test - public void shouldParseCommaSeparatedListOfTargetTestClassGlobAsRegex() { - ReportOptions actual = parseAddingRequiredArgs("--targetTest", - "~foo\\w*,~bar.*"); - Predicate actualPredicate = actual.getTargetTestsFilter(); - assertTrue(actualPredicate.test("foo_anything")); - assertTrue(actualPredicate.test("bar_anything")); - assertFalse(actualPredicate.test("notfoobar")); - actual = parseAddingRequiredArgs("--targetTest", - "~.*?foo\\w*,~bar.*"); - actualPredicate = actual.getTargetTestsFilter(); - assertTrue(actualPredicate.test("notfoobar")); - } - - @Test - public void shouldUseTargetClassesFilterForTestsWhenNoTargetTestsFilterSupplied() { - final ReportOptions actual = parseAddingRequiredArgs("--targetClasses", - "foo*,bar*"); - final Predicate actualPredicate = actual.getTargetTestsFilter(); - assertTrue(actualPredicate.test("foo_anything")); - assertTrue(actualPredicate.test("bar_anything")); - assertFalse(actualPredicate.test("notfoobar")); - } - - @Test - public void shouldParseCommaSeparatedListOfExcludedTestClassGlobs() { - final ReportOptions actual = parseAddingRequiredArgs("--excludedTestClasses", - "foo*", "--targetTests", "foo*,bar*", "--targetClasses", "foo*,bar*"); - final Predicate testPredicate = actual.getTargetTestsFilter(); - assertFalse(testPredicate.test("foo_anything")); - assertTrue(testPredicate.test("bar_anything")); - } - - @Test - public void shouldParseCommaSeparatedListOfExcludedClassGlobsAndApplyTheseToTargets() { - final ReportOptions actual = parseAddingRequiredArgs("--excludedClasses", - "foo*", "--targetTests", "foo*,bar*", "--targetClasses", "foo*,bar*"); - - final Predicate targetPredicate = actual.getTargetClassesFilter(); - assertFalse(targetPredicate.test("foo_anything")); - assertTrue(targetPredicate.test("bar_anything")); - } - - @Test - public void shouldDefaultLoggingPackagesToDefaultsDefinedByDefaultMutationConfigFactory() { - final ReportOptions actual = parseAddingRequiredArgs(); - assertEquals(ReportOptions.LOGGING_CLASSES, actual.getLoggingClasses()); - } - - @Test - public void shouldParseCommaSeparatedListOfClassesToAvoidCallTo() { - final ReportOptions actual = parseAddingRequiredArgs("--avoidCallsTo", - "foo,bar,foo.bar"); - assertEquals(Arrays.asList("foo", "bar", "foo.bar"), - actual.getLoggingClasses()); - } - - @Test - public void shouldParseCommaSeparatedListOfExcludedMethods() { - final ReportOptions actual = parseAddingRequiredArgs("--excludedMethods", - "foo*,bar*,car"); - final Collection actualPredicate = actual - .getExcludedMethods(); - assertThat(actualPredicate).containsExactlyInAnyOrder("foo*", "bar*", "car"); - } - - @Test - public void shouldParseVerboseFlag() { - final ReportOptions actual = parseAddingRequiredArgs("--verbose"); - assertTrue(actual.isVerbose()); - } - - @Test - public void shouldDefaultToHtmlReportWhenNoOutputFormatsSpecified() { - final ReportOptions actual = parseAddingRequiredArgs(); - assertEquals(new HashSet<>(Arrays.asList("HTML")), - actual.getOutputFormats()); - } - - @Test - public void shouldParseCommaSeparatedListOfOutputFormatsWhenSupplied() { - final ReportOptions actual = parseAddingRequiredArgs("--outputFormats", - "HTML,CSV"); - assertEquals(new HashSet<>(Arrays.asList("HTML", "CSV")), - actual.getOutputFormats()); - } - - @Test - public void shouldAcceptCommaSeparatedListOfAdditionalClassPathElements() { - final ReportOptions ro = parseAddingRequiredArgs("--classPath", - "/foo/bar,./boo"); - final Collection actual = ro.getClassPathElements(); - assertTrue(actual.contains("/foo/bar")); - assertTrue(actual.contains("./boo")); - } - - @Test - public void shouldAcceptFileWithListOfAdditionalClassPathElements() { - final ClassLoader classLoader = getClass().getClassLoader(); - final File classPathFile = new File(classLoader.getResource("testClassPathFile.txt").getFile()); - final ReportOptions ro = parseAddingRequiredArgs("--classPathFile", - classPathFile.getAbsolutePath()); - final Collection actual = ro.getClassPathElements(); - assertTrue(actual.contains("C:/foo")); - assertTrue(actual.contains("/etc/bar")); - } - - @Test - public void shouldDetermineIfFailWhenNoMutationsFlagIsSet() { - assertTrue(parseAddingRequiredArgs("--failWhenNoMutations", "true") - .shouldFailWhenNoMutations()); - assertFalse(parseAddingRequiredArgs("--failWhenNoMutations", "false") - .shouldFailWhenNoMutations()); - } - - @Test - public void shouldFailWhenNoMutationsSetByDefault() { - assertTrue(parseAddingRequiredArgs("").shouldFailWhenNoMutations()); - } - - @Test - public void shouldParseCommaSeparatedListOfMutableCodePaths() { - final ReportOptions actual = parseAddingRequiredArgs("--mutableCodePaths", - "foo,bar"); - assertEquals(Arrays.asList("foo", "bar"), actual.getCodePaths()); - } - - @Test - public void shouldParseCommaSeparatedListOfExcludedTestGroups() { - final ReportOptions actual = parseAddingRequiredArgs("--excludedGroups", - "foo,bar"); - assertEquals(Arrays.asList("foo", "bar"), actual.getGroupConfig() - .getExcludedGroups()); - } - - @Test - public void shouldParseCommaSeparatedListOfIncludedTestGroups() { - final ReportOptions actual = parseAddingRequiredArgs("--includedGroups", - "foo,bar"); - assertEquals(Arrays.asList("foo", "bar"), actual.getGroupConfig() - .getIncludedGroups()); - } - - @Test - public void shouldParseCommaSeparatedListOfIncludedTestMethods() { - final ReportOptions actual = parseAddingRequiredArgs("--includedTestMethods", - "foo,bar"); - assertEquals(Arrays.asList("foo", "bar"), actual - .getIncludedTestMethods()); - } - - @Test - public void shouldParseMutationUnitSize() { - final ReportOptions actual = parseAddingRequiredArgs("--mutationUnitSize", - "50"); - assertEquals(50, actual.getMutationUnitSize()); - } - - @Test - public void shouldDefaultMutationUnitSizeToCorrectValue() { - final ReportOptions actual = parseAddingRequiredArgs(""); - assertEquals( - (int) ConfigOption.MUTATION_UNIT_SIZE.getDefault(Integer.class), - actual.getMutationUnitSize()); - } - - @Test - public void shouldDefaultToNoHistory() { - final ReportOptions actual = parseAddingRequiredArgs(""); - assertNull(actual.getHistoryInputLocation()); - assertNull(actual.getHistoryOutputLocation()); - } - - @Test - public void shouldParseHistoryInputLocation() { - final ReportOptions actual = parseAddingRequiredArgs( - "--historyInputLocation", "foo"); - assertEquals(new File("foo"), actual.getHistoryInputLocation()); - } - - @Test - public void shouldParseHistoryOutputLocation() { - final ReportOptions actual = parseAddingRequiredArgs( - "--historyOutputLocation", "foo"); - assertEquals(new File("foo"), actual.getHistoryOutputLocation()); - } - - @Test - public void shouldParseMutationThreshold() { - final ReportOptions actual = parseAddingRequiredArgs("--mutationThreshold", - "42"); - assertEquals(42, actual.getMutationThreshold()); - } - - @Test - public void shouldParseMaximumAllowedSurvivingMutants() { - final ReportOptions actual = parseAddingRequiredArgs("--maxSurviving", - "42"); - assertEquals(42, actual.getMaximumAllowedSurvivors()); - } - - @Test - public void shouldParseCoverageThreshold() { - final ReportOptions actual = parseAddingRequiredArgs("--coverageThreshold", - "42"); - assertEquals(42, actual.getCoverageThreshold()); - } - - @Test - public void shouldDefaultToGregorEngineWhenNoOptionSupplied() { - final ReportOptions actual = parseAddingRequiredArgs(); - assertEquals("gregor", actual.getMutationEngine()); - } - - @Test - public void shouldParseMutationEnigne() { - final ReportOptions actual = parseAddingRequiredArgs("--mutationEngine", - "foo"); - assertEquals("foo", actual.getMutationEngine()); - } - - @Test - public void shouldDefaultJVMToNull() { - final ReportOptions actual = parseAddingRequiredArgs(); - assertEquals(null, actual.getJavaExecutable()); - } - - @Test - public void shouldParseJVM() { - final ReportOptions actual = parseAddingRequiredArgs("--jvmPath", "foo"); - assertEquals("foo", actual.getJavaExecutable()); - } - - @Test - public void shouldParseExportLineCoverageFlag() { - final ReportOptions actual = parseAddingRequiredArgs("--exportLineCoverage"); - assertTrue(actual.shouldExportLineCoverage()); - } - - @Test - public void shouldNotExportLineCoverageWhenFlagNotSet() { - final ReportOptions actual = parseAddingRequiredArgs(""); - assertFalse(actual.shouldExportLineCoverage()); - } - - @Test - public void shouldIncludeLaunchClasspathByDefault() { - final ReportOptions actual = parseAddingRequiredArgs(""); - assertTrue(actual.isIncludeLaunchClasspath()); - } - - @Test - public void shouldNotIncludeLaunchClasspathWhenFlagUnset() { - final ReportOptions actual = parseAddingRequiredArgs("--includeLaunchClasspath=false"); - assertFalse(actual.isIncludeLaunchClasspath()); - } - - @Test - public void shouldIncludeLaunchClasspathWhenFlag() { - final ReportOptions actual = parseAddingRequiredArgs("--includeLaunchClasspath=true"); - assertTrue(actual.isIncludeLaunchClasspath()); - } - - @Test - public void shouldHandleNotCanonicalLaunchClasspathElements() { - final String oldClasspath = System.getProperty(JAVA_CLASS_PATH_PROPERTY); - try { - // given - final PluginServices plugins = PluginServices.makeForContextLoader(); - this.testee = new OptionsParser(new PluginFilter(plugins)); - // and - System.setProperty(JAVA_CLASS_PATH_PROPERTY, - getNonCanonicalGregorEngineClassPath()); - // when - final ReportOptions actual = parseAddingRequiredArgs("--includeLaunchClasspath=false"); - // then - assertThat(actual.getClassPath().findClasses(gregorClass())).hasSize(1); - } finally { - System.setProperty(JAVA_CLASS_PATH_PROPERTY, oldClasspath); - } - } - - @Test - public void shouldCreateEmptyPluginPropertiesWhenNoneSupplied() { - final ReportOptions actual = parseAddingRequiredArgs(""); - assertNotNull(actual.getFreeFormProperties()); - } - - @Test - public void shouldIncludePluginPropertyValuesWhenSingleKey() { - final ReportOptions actual = parseAddingRequiredArgs("-pluginConfiguration=foo=1"); - assertEquals("1", actual.getFreeFormProperties().getProperty("foo")); - } - - @Test - public void shouldIncludePluginPropertyValuesWhenMultipleKeys() { - final ReportOptions actual = parseAddingRequiredArgs( - "-pluginConfiguration=foo=1", "-pluginConfiguration=bar=2"); - assertEquals("1", actual.getFreeFormProperties().getProperty("foo")); - assertEquals("2", actual.getFreeFormProperties().getProperty("bar")); - } - - private String getNonCanonicalGregorEngineClassPath() { - final String gregorEngineClassPath = GregorMutationEngine.class - .getProtectionDomain().getCodeSource().getLocation().getFile(); - final int lastOccurrenceOfFileSeparator = gregorEngineClassPath - .lastIndexOf(JAVA_PATH_SEPARATOR); - return new StringBuilder(gregorEngineClassPath).replace( - lastOccurrenceOfFileSeparator, lastOccurrenceOfFileSeparator + 1, - JAVA_PATH_SEPARATOR + "." + JAVA_PATH_SEPARATOR).toString(); - } - - private Predicate gregorClass() { - return s -> GregorMutationEngine.class.getName().equals(s); - } - - private ReportOptions parseAddingRequiredArgs(final String... args) { - - final List a = new ArrayList<>(); - a.addAll(Arrays.asList(args)); - addIfNotPresent(a, "--targetClasses"); - addIfNotPresent(a, "--reportDir"); - addIfNotPresent(a, "--sourceDirs"); - return parse(a.toArray(new String[a.size()])); - } - - private void addIfNotPresent(final List uniqueArgs, final String value) { - if (!uniqueArgs.contains(value)) { - uniqueArgs.add(value); - uniqueArgs.add("ignore"); - } - } - - private ReportOptions parse(final String... args) { - return this.testee.parse(args).getOptions(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.commandline; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.mutationtest.config.ConfigOption; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.engine.gregor.GregorMutationEngine; +import org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator; +import org.pitest.mutationtest.engine.gregor.mutators.MathMutator; + +public class OptionsParserTest { + + private static final String JAVA_PATH_SEPARATOR = "/"; + + private static final String JAVA_CLASS_PATH_PROPERTY = "java.class.path"; + + private OptionsParser testee; + + @Mock + private Predicate filter; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + when(this.filter.test(any(String.class))).thenReturn(true); + this.testee = new OptionsParser(this.filter); + } + + @Test + public void shouldParseTestPlugin() { + final String value = "foo"; + final ReportOptions actual = parseAddingRequiredArgs("--testPlugin", value); + assertEquals(value, actual.getTestPlugin()); + } + + @Test + public void shouldParseReportDir() { + final String value = "foo"; + final ReportOptions actual = parseAddingRequiredArgs("--reportDir", value); + assertEquals(value, actual.getReportDir()); + } + + @Test + public void shouldCreatePredicateFromCommaSeparatedListOfTargetClassGlobs() { + final ReportOptions actual = parseAddingRequiredArgs("--targetClasses", + "foo*,bar*"); + final Predicate actualPredicate = actual.getTargetClassesFilter(); + assertTrue(actualPredicate.test("foo_anything")); + assertTrue(actualPredicate.test("bar_anything")); + assertFalse(actualPredicate.test("notfoobar")); + } + + @Test + public void shouldParseCommaSeparatedListOfSourceDirectories() { + final ReportOptions actual = parseAddingRequiredArgs("--sourceDirs", + "foo/bar,bar/far"); + assertEquals(Arrays.asList(new File("foo/bar"), new File("bar/far")), actual.getSourceDirs()); + } + + @Test + public void shouldParseMaxDepenencyDistance() { + final ReportOptions actual = parseAddingRequiredArgs( + "--dependencyDistance", "42"); + assertEquals(42, actual.getDependencyAnalysisMaxDistance()); + } + + @Test + public void shouldParseCommaSeparatedListOfJVMArgs() { + final ReportOptions actual = parseAddingRequiredArgs("--jvmArgs", "foo,bar"); + assertEquals(Arrays.asList("foo", "bar"), actual.getJvmArgs()); + } + + @Test + public void shouldParseCommaSeparatedListOfMutationOperators() { + final ReportOptions actual = parseAddingRequiredArgs("--mutators", + ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR.name() + "," + + MathMutator.MATH_MUTATOR.name()); + assertEquals(Arrays.asList( + ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR.name(), + MathMutator.MATH_MUTATOR.name()), actual.getMutators()); + } + + @Test + public void shouldParseCommaSeparatedListOfFeatures() { + final ReportOptions actual = parseAddingRequiredArgs("--features", "+FOO(),-BAR(value=1 & value=2)"); + assertThat(actual.getFeatures()).contains("+FOO()", "-BAR(value=1 & value=2)"); + } + + @Test + public void shouldNotDetectInlinedCodeByDefault() { + final ReportOptions actual = parseAddingRequiredArgs(""); + assertFalse(actual.isDetectInlinedCode()); + } + + @Test + public void shouldDetermineIfInlinedCodeFlagIsSet() { + final ReportOptions actual = parseAddingRequiredArgs("--detectInlinedCode"); + assertTrue(actual.isDetectInlinedCode()); + } + + @Test + public void shouldDetermineIfInlinedCodeFlagIsSetWhenFalseSupplied() { + final ReportOptions actual = parseAddingRequiredArgs("--detectInlinedCode=false"); + assertFalse(actual.isDetectInlinedCode()); + } + + @Test + public void shouldCreateTimestampedReportsByDefault() { + final ReportOptions actual = parseAddingRequiredArgs(); + assertTrue(actual.shouldCreateTimeStampedReports()); + } + + @Test + public void shouldDetermineIfSuppressTimestampedReportsFlagIsSet() { + final ReportOptions actual = parseAddingRequiredArgs("--timestampedReports"); + assertTrue(actual.shouldCreateTimeStampedReports()); + } + + @Test + public void shouldDetermineIfSuppressTimestampedReportsFlagIsSetWhenFalseSupplied() { + final ReportOptions actual = parseAddingRequiredArgs("--timestampedReports=false"); + assertFalse(actual.shouldCreateTimeStampedReports()); + } + + @Test + public void shouldParseNumberOfThreads() { + final ReportOptions actual = parseAddingRequiredArgs("--threads", "42"); + assertEquals(42, actual.getNumberOfThreads()); + } + + @Test + public void shouldParseTimeOutFactor() { + final ReportOptions actual = parseAddingRequiredArgs("--timeoutFactor", + "1.32"); + assertEquals(1.32f, actual.getTimeoutFactor(), 0.1); + } + + @Test + public void shouldParseTimeOutConstant() { + final ReportOptions actual = parseAddingRequiredArgs("--timeoutConst", "42"); + assertEquals(42, actual.getTimeoutConstant()); + } + + @Test + public void shouldParseCommaSeparatedListOfTargetTestClassGlobs() { + final ReportOptions actual = parseAddingRequiredArgs("--targetTest", + "foo*,bar*"); + final Predicate actualPredicate = actual.getTargetTestsFilter(); + assertTrue(actualPredicate.test("foo_anything")); + assertTrue(actualPredicate.test("bar_anything")); + assertFalse(actualPredicate.test("notfoobar")); + } + + @Test + public void shouldParseCommaSeparatedListOfTargetTestClassGlobAsRegex() { + ReportOptions actual = parseAddingRequiredArgs("--targetTest", + "~foo\\w*,~bar.*"); + Predicate actualPredicate = actual.getTargetTestsFilter(); + assertTrue(actualPredicate.test("foo_anything")); + assertTrue(actualPredicate.test("bar_anything")); + assertFalse(actualPredicate.test("notfoobar")); + actual = parseAddingRequiredArgs("--targetTest", + "~.*?foo\\w*,~bar.*"); + actualPredicate = actual.getTargetTestsFilter(); + assertTrue(actualPredicate.test("notfoobar")); + } + + @Test + public void shouldUseTargetClassesFilterForTestsWhenNoTargetTestsFilterSupplied() { + final ReportOptions actual = parseAddingRequiredArgs("--targetClasses", + "foo*,bar*"); + final Predicate actualPredicate = actual.getTargetTestsFilter(); + assertTrue(actualPredicate.test("foo_anything")); + assertTrue(actualPredicate.test("bar_anything")); + assertFalse(actualPredicate.test("notfoobar")); + } + + @Test + public void shouldParseCommaSeparatedListOfExcludedTestClassGlobs() { + final ReportOptions actual = parseAddingRequiredArgs("--excludedTestClasses", + "foo*", "--targetTests", "foo*,bar*", "--targetClasses", "foo*,bar*"); + final Predicate testPredicate = actual.getTargetTestsFilter(); + assertFalse(testPredicate.test("foo_anything")); + assertTrue(testPredicate.test("bar_anything")); + } + + @Test + public void shouldParseCommaSeparatedListOfExcludedClassGlobsAndApplyTheseToTargets() { + final ReportOptions actual = parseAddingRequiredArgs("--excludedClasses", + "foo*", "--targetTests", "foo*,bar*", "--targetClasses", "foo*,bar*"); + + final Predicate targetPredicate = actual.getTargetClassesFilter(); + assertFalse(targetPredicate.test("foo_anything")); + assertTrue(targetPredicate.test("bar_anything")); + } + + @Test + public void shouldDefaultLoggingPackagesToDefaultsDefinedByDefaultMutationConfigFactory() { + final ReportOptions actual = parseAddingRequiredArgs(); + assertEquals(ReportOptions.LOGGING_CLASSES, actual.getLoggingClasses()); + } + + @Test + public void shouldParseCommaSeparatedListOfClassesToAvoidCallTo() { + final ReportOptions actual = parseAddingRequiredArgs("--avoidCallsTo", + "foo,bar,foo.bar"); + assertEquals(Arrays.asList("foo", "bar", "foo.bar"), + actual.getLoggingClasses()); + } + + @Test + public void shouldParseCommaSeparatedListOfExcludedMethods() { + final ReportOptions actual = parseAddingRequiredArgs("--excludedMethods", + "foo*,bar*,car"); + final Collection actualPredicate = actual + .getExcludedMethods(); + assertThat(actualPredicate).containsExactlyInAnyOrder("foo*", "bar*", "car"); + } + + @Test + public void shouldParseVerboseFlag() { + final ReportOptions actual = parseAddingRequiredArgs("--verbose"); + assertTrue(actual.isVerbose()); + } + + @Test + public void shouldDefaultToHtmlReportWhenNoOutputFormatsSpecified() { + final ReportOptions actual = parseAddingRequiredArgs(); + assertEquals(new HashSet<>(Arrays.asList("HTML")), + actual.getOutputFormats()); + } + + @Test + public void shouldParseCommaSeparatedListOfOutputFormatsWhenSupplied() { + final ReportOptions actual = parseAddingRequiredArgs("--outputFormats", + "HTML,CSV"); + assertEquals(new HashSet<>(Arrays.asList("HTML", "CSV")), + actual.getOutputFormats()); + } + + @Test + public void shouldAcceptCommaSeparatedListOfAdditionalClassPathElements() { + final ReportOptions ro = parseAddingRequiredArgs("--classPath", + "/foo/bar,./boo"); + final Collection actual = ro.getClassPathElements(); + assertTrue(actual.contains("/foo/bar")); + assertTrue(actual.contains("./boo")); + } + + @Test + public void shouldAcceptFileWithListOfAdditionalClassPathElements() { + final ClassLoader classLoader = getClass().getClassLoader(); + final File classPathFile = new File(classLoader.getResource("testClassPathFile.txt").getFile()); + final ReportOptions ro = parseAddingRequiredArgs("--classPathFile", + classPathFile.getAbsolutePath()); + final Collection actual = ro.getClassPathElements(); + assertTrue(actual.contains("C:/foo")); + assertTrue(actual.contains("/etc/bar")); + } + + @Test + public void shouldDetermineIfFailWhenNoMutationsFlagIsSet() { + assertTrue(parseAddingRequiredArgs("--failWhenNoMutations", "true") + .shouldFailWhenNoMutations()); + assertFalse(parseAddingRequiredArgs("--failWhenNoMutations", "false") + .shouldFailWhenNoMutations()); + } + + @Test + public void shouldFailWhenNoMutationsSetByDefault() { + assertTrue(parseAddingRequiredArgs("").shouldFailWhenNoMutations()); + } + + @Test + public void shouldParseCommaSeparatedListOfMutableCodePaths() { + final ReportOptions actual = parseAddingRequiredArgs("--mutableCodePaths", + "foo,bar"); + assertEquals(Arrays.asList("foo", "bar"), actual.getCodePaths()); + } + + @Test + public void shouldParseCommaSeparatedListOfExcludedTestGroups() { + final ReportOptions actual = parseAddingRequiredArgs("--excludedGroups", + "foo,bar"); + assertEquals(Arrays.asList("foo", "bar"), actual.getGroupConfig() + .getExcludedGroups()); + } + + @Test + public void shouldParseCommaSeparatedListOfIncludedTestGroups() { + final ReportOptions actual = parseAddingRequiredArgs("--includedGroups", + "foo,bar"); + assertEquals(Arrays.asList("foo", "bar"), actual.getGroupConfig() + .getIncludedGroups()); + } + + @Test + public void shouldParseCommaSeparatedListOfIncludedTestMethods() { + final ReportOptions actual = parseAddingRequiredArgs("--includedTestMethods", + "foo,bar"); + assertEquals(Arrays.asList("foo", "bar"), actual + .getIncludedTestMethods()); + } + + @Test + public void shouldParseMutationUnitSize() { + final ReportOptions actual = parseAddingRequiredArgs("--mutationUnitSize", + "50"); + assertEquals(50, actual.getMutationUnitSize()); + } + + @Test + public void shouldDefaultMutationUnitSizeToCorrectValue() { + final ReportOptions actual = parseAddingRequiredArgs(""); + assertEquals( + (int) ConfigOption.MUTATION_UNIT_SIZE.getDefault(Integer.class), + actual.getMutationUnitSize()); + } + + @Test + public void shouldDefaultToNoHistory() { + final ReportOptions actual = parseAddingRequiredArgs(""); + assertNull(actual.getHistoryInputLocation()); + assertNull(actual.getHistoryOutputLocation()); + } + + @Test + public void shouldParseHistoryInputLocation() { + final ReportOptions actual = parseAddingRequiredArgs( + "--historyInputLocation", "foo"); + assertEquals(new File("foo"), actual.getHistoryInputLocation()); + } + + @Test + public void shouldParseHistoryOutputLocation() { + final ReportOptions actual = parseAddingRequiredArgs( + "--historyOutputLocation", "foo"); + assertEquals(new File("foo"), actual.getHistoryOutputLocation()); + } + + @Test + public void shouldParseMutationThreshold() { + final ReportOptions actual = parseAddingRequiredArgs("--mutationThreshold", + "42"); + assertEquals(42, actual.getMutationThreshold()); + } + + @Test + public void shouldParseMaximumAllowedSurvivingMutants() { + final ReportOptions actual = parseAddingRequiredArgs("--maxSurviving", + "42"); + assertEquals(42, actual.getMaximumAllowedSurvivors()); + } + + @Test + public void shouldParseCoverageThreshold() { + final ReportOptions actual = parseAddingRequiredArgs("--coverageThreshold", + "42"); + assertEquals(42, actual.getCoverageThreshold()); + } + + @Test + public void shouldDefaultToGregorEngineWhenNoOptionSupplied() { + final ReportOptions actual = parseAddingRequiredArgs(); + assertEquals("gregor", actual.getMutationEngine()); + } + + @Test + public void shouldParseMutationEnigne() { + final ReportOptions actual = parseAddingRequiredArgs("--mutationEngine", + "foo"); + assertEquals("foo", actual.getMutationEngine()); + } + + @Test + public void shouldDefaultJVMToNull() { + final ReportOptions actual = parseAddingRequiredArgs(); + assertEquals(null, actual.getJavaExecutable()); + } + + @Test + public void shouldParseJVM() { + final ReportOptions actual = parseAddingRequiredArgs("--jvmPath", "foo"); + assertEquals("foo", actual.getJavaExecutable()); + } + + @Test + public void shouldParseExportLineCoverageFlag() { + final ReportOptions actual = parseAddingRequiredArgs("--exportLineCoverage"); + assertTrue(actual.shouldExportLineCoverage()); + } + + @Test + public void shouldNotExportLineCoverageWhenFlagNotSet() { + final ReportOptions actual = parseAddingRequiredArgs(""); + assertFalse(actual.shouldExportLineCoverage()); + } + + @Test + public void shouldIncludeLaunchClasspathByDefault() { + final ReportOptions actual = parseAddingRequiredArgs(""); + assertTrue(actual.isIncludeLaunchClasspath()); + } + + @Test + public void shouldNotIncludeLaunchClasspathWhenFlagUnset() { + final ReportOptions actual = parseAddingRequiredArgs("--includeLaunchClasspath=false"); + assertFalse(actual.isIncludeLaunchClasspath()); + } + + @Test + public void shouldIncludeLaunchClasspathWhenFlag() { + final ReportOptions actual = parseAddingRequiredArgs("--includeLaunchClasspath=true"); + assertTrue(actual.isIncludeLaunchClasspath()); + } + + @Test + public void shouldHandleNotCanonicalLaunchClasspathElements() { + final String oldClasspath = System.getProperty(JAVA_CLASS_PATH_PROPERTY); + try { + // given + final PluginServices plugins = PluginServices.makeForContextLoader(); + this.testee = new OptionsParser(new PluginFilter(plugins)); + // and + System.setProperty(JAVA_CLASS_PATH_PROPERTY, + getNonCanonicalGregorEngineClassPath()); + // when + final ReportOptions actual = parseAddingRequiredArgs("--includeLaunchClasspath=false"); + // then + assertThat(actual.getClassPath().findClasses(gregorClass())).hasSize(1); + } finally { + System.setProperty(JAVA_CLASS_PATH_PROPERTY, oldClasspath); + } + } + + @Test + public void shouldCreateEmptyPluginPropertiesWhenNoneSupplied() { + final ReportOptions actual = parseAddingRequiredArgs(""); + assertNotNull(actual.getFreeFormProperties()); + } + + @Test + public void shouldIncludePluginPropertyValuesWhenSingleKey() { + final ReportOptions actual = parseAddingRequiredArgs("-pluginConfiguration=foo=1"); + assertEquals("1", actual.getFreeFormProperties().getProperty("foo")); + } + + @Test + public void shouldIncludePluginPropertyValuesWhenMultipleKeys() { + final ReportOptions actual = parseAddingRequiredArgs( + "-pluginConfiguration=foo=1", "-pluginConfiguration=bar=2"); + assertEquals("1", actual.getFreeFormProperties().getProperty("foo")); + assertEquals("2", actual.getFreeFormProperties().getProperty("bar")); + } + + private String getNonCanonicalGregorEngineClassPath() { + final String gregorEngineClassPath = GregorMutationEngine.class + .getProtectionDomain().getCodeSource().getLocation().getFile(); + final int lastOccurrenceOfFileSeparator = gregorEngineClassPath + .lastIndexOf(JAVA_PATH_SEPARATOR); + return new StringBuilder(gregorEngineClassPath).replace( + lastOccurrenceOfFileSeparator, lastOccurrenceOfFileSeparator + 1, + JAVA_PATH_SEPARATOR + "." + JAVA_PATH_SEPARATOR).toString(); + } + + private Predicate gregorClass() { + return s -> GregorMutationEngine.class.getName().equals(s); + } + + private ReportOptions parseAddingRequiredArgs(final String... args) { + + final List a = new ArrayList<>(); + a.addAll(Arrays.asList(args)); + addIfNotPresent(a, "--targetClasses"); + addIfNotPresent(a, "--reportDir"); + addIfNotPresent(a, "--sourceDirs"); + return parse(a.toArray(new String[a.size()])); + } + + private void addIfNotPresent(final List uniqueArgs, final String value) { + if (!uniqueArgs.contains(value)) { + uniqueArgs.add(value); + uniqueArgs.add("ignore"); + } + } + + private ReportOptions parse(final String... args) { + return this.testee.parse(args).getOptions(); + } + +} diff --git a/pitest-command-line/src/test/java/org/pitest/mutationtest/commandline/PluginFilterTest.java b/pitest-command-line/src/test/java/org/pitest/mutationtest/commandline/PluginFilterTest.java index e92c2a1f7..1a5dd3a67 100644 --- a/pitest-command-line/src/test/java/org/pitest/mutationtest/commandline/PluginFilterTest.java +++ b/pitest-command-line/src/test/java/org/pitest/mutationtest/commandline/PluginFilterTest.java @@ -1,38 +1,38 @@ -package org.pitest.mutationtest.commandline; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; - -import org.junit.Test; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.engine.gregor.GregorMutationEngine; -import org.pitest.mutationtest.report.html.HtmlReportFactory; -import org.pitest.util.IsolationUtils; - -public class PluginFilterTest { - - private final PluginFilter testee = new PluginFilter(new PluginServices( - IsolationUtils.getContextClassLoader())); - - @Test - public void shouldExcludeHtmlReportPlugin() throws Exception { - final String pluginLocation = getClassLocationAsCanonicalPath(HtmlReportFactory.class); - assertFalse(this.testee.test(pluginLocation)); - } - - @Test - public void shouldIncludeMutationEngine() throws Exception { - final String pluginLocation = getClassLocationAsCanonicalPath(GregorMutationEngine.class); - assertTrue(this.testee.test(pluginLocation)); - } - - private String getClassLocationAsCanonicalPath(Class clazz) - throws URISyntaxException, IOException { - return new File(clazz.getProtectionDomain().getCodeSource().getLocation() - .toURI()).getCanonicalPath(); - } -} +package org.pitest.mutationtest.commandline; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; + +import org.junit.Test; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.engine.gregor.GregorMutationEngine; +import org.pitest.mutationtest.report.html.HtmlReportFactory; +import org.pitest.util.IsolationUtils; + +public class PluginFilterTest { + + private final PluginFilter testee = new PluginFilter(new PluginServices( + IsolationUtils.getContextClassLoader())); + + @Test + public void shouldExcludeHtmlReportPlugin() throws Exception { + final String pluginLocation = getClassLocationAsCanonicalPath(HtmlReportFactory.class); + assertFalse(this.testee.test(pluginLocation)); + } + + @Test + public void shouldIncludeMutationEngine() throws Exception { + final String pluginLocation = getClassLocationAsCanonicalPath(GregorMutationEngine.class); + assertTrue(this.testee.test(pluginLocation)); + } + + private String getClassLocationAsCanonicalPath(Class clazz) + throws URISyntaxException, IOException { + return new File(clazz.getProtectionDomain().getCodeSource().getLocation() + .toURI()).getCanonicalPath(); + } +} diff --git a/pitest-command-line/src/test/resources/testClassPathFile.txt b/pitest-command-line/src/test/resources/testClassPathFile.txt index bd64cc8e4..44adeb876 100644 --- a/pitest-command-line/src/test/resources/testClassPathFile.txt +++ b/pitest-command-line/src/test/resources/testClassPathFile.txt @@ -1,2 +1,2 @@ -C:/foo +C:/foo /etc/bar \ No newline at end of file diff --git a/pitest-entry/pom.xml b/pitest-entry/pom.xml index e04efc337..da8cbca28 100644 --- a/pitest-entry/pom.xml +++ b/pitest-entry/pom.xml @@ -1,181 +1,181 @@ - - - - 4.0.0 - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - pitest-entry - pitest-entry - http://pitest.org - Pitest entry point - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - - - org.ow2.asm:* - - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - true - - true - - - - - - test-jar - - - - - - maven-surefire-plugin - - none:none - - - org/**/Test*.java - org/**/*Test.java - - - **/*$* - com/*/**.java - **/FullyCoveredByTestNGTesteeTest.java - - org.pitest.SystemTest - - - - org.testng - testng - ${testng.version} - - - - - - maven-failsafe-plugin - - - - -Dfoo=foo - - org.pitest.SystemTest - - - - - integration-test - verify - - - - **/*.class - - - - - - - - - src/main/resources - true - - - - - - - org.pitest - pitest - ${project.version} - - - - - org.ow2.asm - asm - ${asm.version} - - - org.ow2.asm - asm-util - ${asm.version} - - - - com.thoughtworks.xstream - xstream - 1.4.8 - test - - - org.pitest - pitest - ${project.version} - test-jar - test - - - nl.jqno.equalsverifier - equalsverifier - 1.7.5 - test - - - - com.google.jimfs - jimfs - 1.1 - test - - - - - org.easymock - easymock - 3.3.1 - test - - - org.testng - testng - ${testng.version} - test - - - - - + + + + 4.0.0 + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + pitest-entry + pitest-entry + http://pitest.org + Pitest entry point + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + org.ow2.asm:* + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + + true + + + + + + test-jar + + + + + + maven-surefire-plugin + + none:none + + + org/**/Test*.java + org/**/*Test.java + + + **/*$* + com/*/**.java + **/FullyCoveredByTestNGTesteeTest.java + + org.pitest.SystemTest + + + + org.testng + testng + ${testng.version} + + + + + + maven-failsafe-plugin + + + + -Dfoo=foo + + org.pitest.SystemTest + + + + + integration-test + verify + + + + **/*.class + + + + + + + + + src/main/resources + true + + + + + + + org.pitest + pitest + ${project.version} + + + + + org.ow2.asm + asm + ${asm.version} + + + org.ow2.asm + asm-util + ${asm.version} + + + + com.thoughtworks.xstream + xstream + 1.4.8 + test + + + org.pitest + pitest + ${project.version} + test-jar + test + + + nl.jqno.equalsverifier + equalsverifier + 1.7.5 + test + + + + com.google.jimfs + jimfs + 1.1 + test + + + + + org.easymock + easymock + 3.3.1 + test + + + org.testng + testng + ${testng.version} + test + + + + + diff --git a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/AnalysisFunctions.java b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/AnalysisFunctions.java index 4a6fc1d34..3922597bc 100644 --- a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/AnalysisFunctions.java +++ b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/AnalysisFunctions.java @@ -1,16 +1,16 @@ -package org.pitest.bytecode.analysis; - -import java.util.function.Function; -import java.util.function.Predicate; - -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MutationDetails; - -public class AnalysisFunctions { - public static Function> matchMutationsInMethod() { - return method -> { - final Location methodLocation = method.asLocation(); - return a -> methodLocation.equals(a.getId().getLocation()); - }; - } -} +package org.pitest.bytecode.analysis; + +import java.util.function.Function; +import java.util.function.Predicate; + +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MutationDetails; + +public class AnalysisFunctions { + public static Function> matchMutationsInMethod() { + return method -> { + final Location methodLocation = method.asLocation(); + return a -> methodLocation.equals(a.getId().getLocation()); + }; + } +} diff --git a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/ClassTree.java b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/ClassTree.java index 38dce1c5b..153a37821 100644 --- a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/ClassTree.java +++ b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/ClassTree.java @@ -1,82 +1,82 @@ -package org.pitest.bytecode.analysis; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; -import org.objectweb.asm.util.Textifier; -import org.objectweb.asm.util.TraceClassVisitor; -import org.pitest.classinfo.ClassName; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.Location; - -public class ClassTree { - - private final ClassNode rawNode; - private List lazyMethods; - - public ClassTree(ClassNode rawNode) { - this.rawNode = rawNode; - } - - public static ClassTree fromBytes(byte[] bytes) { - final ClassReader cr = new ClassReader(bytes); - final ClassNode classNode = new ClassNode(); - cr.accept(classNode, ClassReader.EXPAND_FRAMES); - return new ClassTree(classNode); - } - - - public List methods() { - if (this.lazyMethods != null) { - return this.lazyMethods; - } - this.lazyMethods = FCollection.map(this.rawNode.methods, toTree(name())); - return this.lazyMethods; - } - - public Optional method(Location loc) { - return methods().stream().filter(MethodMatchers.forLocation(loc)).findFirst(); - } - - public List annotations() { - final List annotaions = new ArrayList<>(); - if (this.rawNode.invisibleAnnotations != null) { - annotaions.addAll(this.rawNode.invisibleAnnotations); - } - if (this.rawNode.visibleAnnotations != null) { - annotaions.addAll(this.rawNode.visibleAnnotations); - } - return annotaions; - } - - private static Function toTree(final ClassName name) { - return a -> new MethodTree(name,a); - } - - public ClassName name() { - return ClassName.fromString(this.rawNode.name); - } - - public ClassNode rawNode() { - return this.rawNode; - } - - - @Override - public String toString() { - final StringWriter writer = new StringWriter(); - this.rawNode.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter( - writer))); - return writer.toString(); - - } - -} +package org.pitest.bytecode.analysis; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.util.Textifier; +import org.objectweb.asm.util.TraceClassVisitor; +import org.pitest.classinfo.ClassName; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.Location; + +public class ClassTree { + + private final ClassNode rawNode; + private List lazyMethods; + + public ClassTree(ClassNode rawNode) { + this.rawNode = rawNode; + } + + public static ClassTree fromBytes(byte[] bytes) { + final ClassReader cr = new ClassReader(bytes); + final ClassNode classNode = new ClassNode(); + cr.accept(classNode, ClassReader.EXPAND_FRAMES); + return new ClassTree(classNode); + } + + + public List methods() { + if (this.lazyMethods != null) { + return this.lazyMethods; + } + this.lazyMethods = FCollection.map(this.rawNode.methods, toTree(name())); + return this.lazyMethods; + } + + public Optional method(Location loc) { + return methods().stream().filter(MethodMatchers.forLocation(loc)).findFirst(); + } + + public List annotations() { + final List annotaions = new ArrayList<>(); + if (this.rawNode.invisibleAnnotations != null) { + annotaions.addAll(this.rawNode.invisibleAnnotations); + } + if (this.rawNode.visibleAnnotations != null) { + annotaions.addAll(this.rawNode.visibleAnnotations); + } + return annotaions; + } + + private static Function toTree(final ClassName name) { + return a -> new MethodTree(name,a); + } + + public ClassName name() { + return ClassName.fromString(this.rawNode.name); + } + + public ClassNode rawNode() { + return this.rawNode; + } + + + @Override + public String toString() { + final StringWriter writer = new StringWriter(); + this.rawNode.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter( + writer))); + return writer.toString(); + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/InstructionMatchers.java b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/InstructionMatchers.java index ab0f26639..2cb45fbf3 100644 --- a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/InstructionMatchers.java +++ b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/InstructionMatchers.java @@ -1,206 +1,206 @@ -package org.pitest.bytecode.analysis; - -import static org.objectweb.asm.Opcodes.ICONST_0; -import static org.objectweb.asm.Opcodes.ICONST_1; -import static org.objectweb.asm.Opcodes.ICONST_2; -import static org.objectweb.asm.Opcodes.ICONST_3; -import static org.objectweb.asm.Opcodes.ICONST_4; -import static org.objectweb.asm.Opcodes.ICONST_5; -import static org.objectweb.asm.Opcodes.ICONST_M1; -import static org.objectweb.asm.Opcodes.ILOAD; -import static org.objectweb.asm.Opcodes.ISTORE; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.IincInsnNode; -import org.objectweb.asm.tree.JumpInsnNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.VarInsnNode; -import org.pitest.classinfo.ClassName; -import org.pitest.functional.prelude.Prelude; -import org.pitest.sequence.Match; -import org.pitest.sequence.Slot; -import org.pitest.sequence.SlotRead; -import org.pitest.sequence.SlotWrite; - -public class InstructionMatchers { - - public static Match anyInstruction() { - return Match.always(); - } - - public static Match opCode(final int opcode) { - return (c, a) -> a.getOpcode() == opcode; - } - - public static Match isA( - final Class cls) { - return (c, a) -> a.getClass().isAssignableFrom(cls); - } - - public static Match incrementsVariable(final SlotRead counterVariable) { - return (context, a) -> (a instanceof IincInsnNode) - && context.retrieve(counterVariable).filter(Prelude.isEqualTo(((IincInsnNode)a).var)).isPresent(); - } - - public static Match anIStore( - final SlotWrite counterVariable) { - return opCode(Opcodes.ISTORE).and(aVariableAccess(counterVariable)); - } - - public static Match aVariableAccess( - final SlotWrite counterVariable) { - return (c, t) -> (t instanceof VarInsnNode) && c.store(counterVariable, ((VarInsnNode) t).var); - } - - public static Match anIStoreTo( - final SlotRead counterVariable) { - return opCode(ISTORE).and(variableMatches(counterVariable)); - } - - public static Match anILoadOf( - final SlotRead counterVariable) { - return opCode(ILOAD).and(variableMatches(counterVariable)); - } - - public static Match variableMatches( - final SlotRead counterVariable) { - return (c, t) -> (t instanceof VarInsnNode) - && c.retrieve(counterVariable).filter(Prelude.isEqualTo(((VarInsnNode)t).var)).isPresent(); - } - - - public static Match anIntegerConstant() { - return opCode(ICONST_M1) - .or(opCode(ICONST_0)) - .or(opCode(ICONST_1)) - .or(opCode(ICONST_2)) - .or(opCode(ICONST_3)) - .or(opCode(ICONST_4)) - .or(opCode(ICONST_5)); - } - - public static Match aLabelNode(SlotWrite slot) { - return isA(LabelNode.class).and(writeNodeToSlot(slot, LabelNode.class)); - } - - public static Match aJump() { - return isA(JumpInsnNode.class); - } - - public static Match aConditionalJump() { - return (c, t) -> (t instanceof JumpInsnNode) - && (t.getOpcode() != Opcodes.GOTO) - && (t.getOpcode() != Opcodes.JSR); - } - - public static Match aConditionalJumpTo(Slot label) { - return jumpsTo(label.read()).and(aConditionalJump()); - } - - - public static Match writeNodeToSlot(final SlotWrite slot, final Class clazz) { - return (c, t) -> { - if (clazz.isAssignableFrom(t.getClass()) ) { - c.store(slot, clazz.cast(t)); - return true; - } - return false; - }; - } - - public static Match methodCallThatReturns(final ClassName type) { - return (c, t) -> { - if ( t instanceof MethodInsnNode ) { - return ((MethodInsnNode) t).desc.endsWith(type.asInternalName() + ";"); - } - return false; - }; - } - - public static Match methodCall() { - return isA(MethodInsnNode.class); - } - - public static Match methodCallTo(final ClassName owner, final String name) { - return (c, t) -> { - if ( t instanceof MethodInsnNode ) { - final MethodInsnNode call = (MethodInsnNode) t; - return call.name.equals(name) && call.owner.equals(owner.asInternalName()); - } - return false; - }; - } - - - public static Match isInstruction(final SlotRead target) { - return (c, t) -> c.retrieve(target).get() == t; - } - - /** - * Records if a instruction matches the target, but always returns true - */ - public static Match recordTarget(final SlotRead target, final SlotWrite found) { - return (c, t) -> { - if (c.retrieve(target).get() == t) { - c.store(found, true); - } - return true; - }; - } - - - private static Match storeJumpTarget( - final SlotWrite label) { - return (c, t) -> { - if (t instanceof JumpInsnNode ) { - c.store(label, ((JumpInsnNode) t).label); - return true; - } - return false; - }; - } - - public static Match jumpsTo( - final SlotRead loopStart) { - return (context, a) -> { - if (!(a instanceof JumpInsnNode)) { - return false; - } - final JumpInsnNode jump = (JumpInsnNode) a; - - return context.retrieve(loopStart).filter(Prelude.isEqualTo(jump.label)).isPresent(); - }; - } - - public static Match jumpsTo( - final SlotWrite label) { - return storeJumpTarget(label); - } - - public static Match gotoLabel( - final SlotWrite loopEnd) { - return opCode(Opcodes.GOTO).and(storeJumpTarget(loopEnd)); - } - - public static Match labelNode( - final SlotRead loopEnd) { - return (c, t) -> { - if (!(t instanceof LabelNode)) { - return false; - } - - final LabelNode l = (LabelNode) t; - return c.retrieve(loopEnd).filter(Prelude.isEqualTo(l)).isPresent(); - - }; - } - - public static Match debug(final String msg) { - return (context, a) -> { - context.debug(msg); - return true; - }; - } -} +package org.pitest.bytecode.analysis; + +import static org.objectweb.asm.Opcodes.ICONST_0; +import static org.objectweb.asm.Opcodes.ICONST_1; +import static org.objectweb.asm.Opcodes.ICONST_2; +import static org.objectweb.asm.Opcodes.ICONST_3; +import static org.objectweb.asm.Opcodes.ICONST_4; +import static org.objectweb.asm.Opcodes.ICONST_5; +import static org.objectweb.asm.Opcodes.ICONST_M1; +import static org.objectweb.asm.Opcodes.ILOAD; +import static org.objectweb.asm.Opcodes.ISTORE; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.IincInsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.VarInsnNode; +import org.pitest.classinfo.ClassName; +import org.pitest.functional.prelude.Prelude; +import org.pitest.sequence.Match; +import org.pitest.sequence.Slot; +import org.pitest.sequence.SlotRead; +import org.pitest.sequence.SlotWrite; + +public class InstructionMatchers { + + public static Match anyInstruction() { + return Match.always(); + } + + public static Match opCode(final int opcode) { + return (c, a) -> a.getOpcode() == opcode; + } + + public static Match isA( + final Class cls) { + return (c, a) -> a.getClass().isAssignableFrom(cls); + } + + public static Match incrementsVariable(final SlotRead counterVariable) { + return (context, a) -> (a instanceof IincInsnNode) + && context.retrieve(counterVariable).filter(Prelude.isEqualTo(((IincInsnNode)a).var)).isPresent(); + } + + public static Match anIStore( + final SlotWrite counterVariable) { + return opCode(Opcodes.ISTORE).and(aVariableAccess(counterVariable)); + } + + public static Match aVariableAccess( + final SlotWrite counterVariable) { + return (c, t) -> (t instanceof VarInsnNode) && c.store(counterVariable, ((VarInsnNode) t).var); + } + + public static Match anIStoreTo( + final SlotRead counterVariable) { + return opCode(ISTORE).and(variableMatches(counterVariable)); + } + + public static Match anILoadOf( + final SlotRead counterVariable) { + return opCode(ILOAD).and(variableMatches(counterVariable)); + } + + public static Match variableMatches( + final SlotRead counterVariable) { + return (c, t) -> (t instanceof VarInsnNode) + && c.retrieve(counterVariable).filter(Prelude.isEqualTo(((VarInsnNode)t).var)).isPresent(); + } + + + public static Match anIntegerConstant() { + return opCode(ICONST_M1) + .or(opCode(ICONST_0)) + .or(opCode(ICONST_1)) + .or(opCode(ICONST_2)) + .or(opCode(ICONST_3)) + .or(opCode(ICONST_4)) + .or(opCode(ICONST_5)); + } + + public static Match aLabelNode(SlotWrite slot) { + return isA(LabelNode.class).and(writeNodeToSlot(slot, LabelNode.class)); + } + + public static Match aJump() { + return isA(JumpInsnNode.class); + } + + public static Match aConditionalJump() { + return (c, t) -> (t instanceof JumpInsnNode) + && (t.getOpcode() != Opcodes.GOTO) + && (t.getOpcode() != Opcodes.JSR); + } + + public static Match aConditionalJumpTo(Slot label) { + return jumpsTo(label.read()).and(aConditionalJump()); + } + + + public static Match writeNodeToSlot(final SlotWrite slot, final Class clazz) { + return (c, t) -> { + if (clazz.isAssignableFrom(t.getClass()) ) { + c.store(slot, clazz.cast(t)); + return true; + } + return false; + }; + } + + public static Match methodCallThatReturns(final ClassName type) { + return (c, t) -> { + if ( t instanceof MethodInsnNode ) { + return ((MethodInsnNode) t).desc.endsWith(type.asInternalName() + ";"); + } + return false; + }; + } + + public static Match methodCall() { + return isA(MethodInsnNode.class); + } + + public static Match methodCallTo(final ClassName owner, final String name) { + return (c, t) -> { + if ( t instanceof MethodInsnNode ) { + final MethodInsnNode call = (MethodInsnNode) t; + return call.name.equals(name) && call.owner.equals(owner.asInternalName()); + } + return false; + }; + } + + + public static Match isInstruction(final SlotRead target) { + return (c, t) -> c.retrieve(target).get() == t; + } + + /** + * Records if a instruction matches the target, but always returns true + */ + public static Match recordTarget(final SlotRead target, final SlotWrite found) { + return (c, t) -> { + if (c.retrieve(target).get() == t) { + c.store(found, true); + } + return true; + }; + } + + + private static Match storeJumpTarget( + final SlotWrite label) { + return (c, t) -> { + if (t instanceof JumpInsnNode ) { + c.store(label, ((JumpInsnNode) t).label); + return true; + } + return false; + }; + } + + public static Match jumpsTo( + final SlotRead loopStart) { + return (context, a) -> { + if (!(a instanceof JumpInsnNode)) { + return false; + } + final JumpInsnNode jump = (JumpInsnNode) a; + + return context.retrieve(loopStart).filter(Prelude.isEqualTo(jump.label)).isPresent(); + }; + } + + public static Match jumpsTo( + final SlotWrite label) { + return storeJumpTarget(label); + } + + public static Match gotoLabel( + final SlotWrite loopEnd) { + return opCode(Opcodes.GOTO).and(storeJumpTarget(loopEnd)); + } + + public static Match labelNode( + final SlotRead loopEnd) { + return (c, t) -> { + if (!(t instanceof LabelNode)) { + return false; + } + + final LabelNode l = (LabelNode) t; + return c.retrieve(loopEnd).filter(Prelude.isEqualTo(l)).isPresent(); + + }; + } + + public static Match debug(final String msg) { + return (context, a) -> { + context.debug(msg); + return true; + }; + } +} diff --git a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/MethodMatchers.java b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/MethodMatchers.java index f1b634142..b9c9d1f0f 100644 --- a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/MethodMatchers.java +++ b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/MethodMatchers.java @@ -1,21 +1,21 @@ -package org.pitest.bytecode.analysis; - -import java.util.function.Predicate; - -import org.pitest.mutationtest.engine.Location; - -public class MethodMatchers { - /** - * Match a method based on its name, as methods can be overloaded - * this should be used with caution. - * @param name the methods name - * @return true if matched - */ - public static Predicate named(final String name) { - return a -> a.rawNode().name.equals(name); - } - - public static Predicate forLocation(final Location location) { - return a -> a.asLocation().equals(location); - } -} +package org.pitest.bytecode.analysis; + +import java.util.function.Predicate; + +import org.pitest.mutationtest.engine.Location; + +public class MethodMatchers { + /** + * Match a method based on its name, as methods can be overloaded + * this should be used with caution. + * @param name the methods name + * @return true if matched + */ + public static Predicate named(final String name) { + return a -> a.rawNode().name.equals(name); + } + + public static Predicate forLocation(final Location location) { + return a -> a.asLocation().equals(location); + } +} diff --git a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/MethodTree.java b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/MethodTree.java index 9c92ffeb2..8465b5241 100644 --- a/pitest-entry/src/main/java/org/pitest/bytecode/analysis/MethodTree.java +++ b/pitest-entry/src/main/java/org/pitest/bytecode/analysis/MethodTree.java @@ -1,68 +1,68 @@ -package org.pitest.bytecode.analysis; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.MethodNode; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; - -public class MethodTree { - - private final ClassName owner; - private final MethodNode rawNode; - private List lazyInstructions; - - public MethodTree(ClassName owner, MethodNode rawNode) { - this.owner = owner; - this.rawNode = rawNode; - } - - public MethodNode rawNode() { - return this.rawNode; - } - - public Location asLocation() { - return Location.location(this.owner,MethodName.fromString(this.rawNode.name), this.rawNode.desc); - } - - public List instructions() { - if (this.lazyInstructions != null) { - return this.lazyInstructions; - } - - return createInstructionList(); - } - - public boolean isSynthetic() { - return (this.rawNode.access & Opcodes.ACC_SYNTHETIC) != 0; - } - - public List annotations() { - final List annotaions = new ArrayList<>(); - if (this.rawNode.invisibleAnnotations != null) { - annotaions.addAll(this.rawNode.invisibleAnnotations); - } - if (this.rawNode.visibleAnnotations != null) { - annotaions.addAll(this.rawNode.visibleAnnotations); - } - return annotaions; - } - - private List createInstructionList() { - final List list = new LinkedList<>(); - final ListIterator it = this.rawNode.instructions.iterator(); - while (it.hasNext()) { - list.add(it.next()); - } - this.lazyInstructions = new ArrayList<>(list); - return this.lazyInstructions; - } - -} +package org.pitest.bytecode.analysis; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; + +public class MethodTree { + + private final ClassName owner; + private final MethodNode rawNode; + private List lazyInstructions; + + public MethodTree(ClassName owner, MethodNode rawNode) { + this.owner = owner; + this.rawNode = rawNode; + } + + public MethodNode rawNode() { + return this.rawNode; + } + + public Location asLocation() { + return Location.location(this.owner,MethodName.fromString(this.rawNode.name), this.rawNode.desc); + } + + public List instructions() { + if (this.lazyInstructions != null) { + return this.lazyInstructions; + } + + return createInstructionList(); + } + + public boolean isSynthetic() { + return (this.rawNode.access & Opcodes.ACC_SYNTHETIC) != 0; + } + + public List annotations() { + final List annotaions = new ArrayList<>(); + if (this.rawNode.invisibleAnnotations != null) { + annotaions.addAll(this.rawNode.invisibleAnnotations); + } + if (this.rawNode.visibleAnnotations != null) { + annotaions.addAll(this.rawNode.visibleAnnotations); + } + return annotaions; + } + + private List createInstructionList() { + final List list = new LinkedList<>(); + final ListIterator it = this.rawNode.instructions.iterator(); + while (it.hasNext()) { + list.add(it.next()); + } + this.lazyInstructions = new ArrayList<>(list); + return this.lazyInstructions; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/classinfo/AddlerHash.java b/pitest-entry/src/main/java/org/pitest/classinfo/AddlerHash.java index a48510b71..09980e600 100644 --- a/pitest-entry/src/main/java/org/pitest/classinfo/AddlerHash.java +++ b/pitest-entry/src/main/java/org/pitest/classinfo/AddlerHash.java @@ -1,14 +1,14 @@ -package org.pitest.classinfo; - -import java.util.zip.Adler32; - -public class AddlerHash implements HashFunction { - - @Override - public long hash(final byte[] value) { - final Adler32 adler = new Adler32(); - adler.update(value); - return adler.getValue(); - } - -} +package org.pitest.classinfo; + +import java.util.zip.Adler32; + +public class AddlerHash implements HashFunction { + + @Override + public long hash(final byte[] value) { + final Adler32 adler = new Adler32(); + adler.update(value); + return adler.getValue(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/classinfo/ClassInfoSource.java b/pitest-entry/src/main/java/org/pitest/classinfo/ClassInfoSource.java index 6c225c49d..8dac93fd2 100644 --- a/pitest-entry/src/main/java/org/pitest/classinfo/ClassInfoSource.java +++ b/pitest-entry/src/main/java/org/pitest/classinfo/ClassInfoSource.java @@ -1,7 +1,7 @@ -package org.pitest.classinfo; - -import java.util.Optional; - -public interface ClassInfoSource { - Optional fetchClass(ClassName name); -} +package org.pitest.classinfo; + +import java.util.Optional; + +public interface ClassInfoSource { + Optional fetchClass(ClassName name); +} diff --git a/pitest-entry/src/main/java/org/pitest/classinfo/NameToClassInfo.java b/pitest-entry/src/main/java/org/pitest/classinfo/NameToClassInfo.java index 89e6da00c..b0c0a3f32 100644 --- a/pitest-entry/src/main/java/org/pitest/classinfo/NameToClassInfo.java +++ b/pitest-entry/src/main/java/org/pitest/classinfo/NameToClassInfo.java @@ -1,20 +1,20 @@ -package org.pitest.classinfo; - -import java.util.function.Function; - -import java.util.Optional; - -public class NameToClassInfo implements Function> { - - private final ClassInfoSource repository; - - public NameToClassInfo(final ClassInfoSource repository) { - this.repository = repository; - } - - @Override - public Optional apply(final ClassName a) { - return this.repository.fetchClass(a); - } - +package org.pitest.classinfo; + +import java.util.function.Function; + +import java.util.Optional; + +public class NameToClassInfo implements Function> { + + private final ClassInfoSource repository; + + public NameToClassInfo(final ClassInfoSource repository) { + this.repository = repository; + } + + @Override + public Optional apply(final ClassName a) { + return this.repository.fetchClass(a); + } + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/classinfo/Repository.java b/pitest-entry/src/main/java/org/pitest/classinfo/Repository.java index db58a203b..71f20e374 100644 --- a/pitest-entry/src/main/java/org/pitest/classinfo/Repository.java +++ b/pitest-entry/src/main/java/org/pitest/classinfo/Repository.java @@ -1,110 +1,110 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import java.util.Optional; - -public class Repository implements ClassInfoSource { - - private final HashFunction hashFunction; - private final Map knownClasses = new HashMap<>(); - private final Set unknownClasses = new HashSet<>(); - private final ClassByteArraySource source; - - public Repository(final ClassByteArraySource source) { - this(source, new AddlerHash()); - } - - Repository(final ClassByteArraySource source, final HashFunction hashFunction) { - this.source = source; - this.hashFunction = hashFunction; - } - - public boolean hasClass(final ClassName name) { - return this.knownClasses.containsKey(name) || querySource(name).isPresent(); - } - - public Optional fetchClass(final Class clazz) { // NO_UCD (test - // only) - return fetchClass(clazz.getName()); - } - - private Optional fetchClass(final String name) { - return fetchClass(ClassName.fromString(name)); - } - - @Override - public Optional fetchClass(final ClassName name) { - final ClassInfo info = this.knownClasses.get(name); - if (info != null) { - return Optional.ofNullable(info); - } - - final Optional maybeInfo = nameToClassInfo(name); - if (maybeInfo.isPresent()) { - this.knownClasses.put(name, maybeInfo.get()); - } - return maybeInfo; - } - - private Optional nameToClassInfo(final ClassName name) { - final Optional bytes = querySource(name); - if (bytes.isPresent()) { - final ClassInfoBuilder classData = ClassInfoVisitor.getClassInfo(name, - bytes.get(), this.hashFunction.hash(bytes.get())); - return contructClassInfo(classData); - } else { - return Optional.empty(); - } - } - - public Optional querySource(final ClassName name) { - if (this.unknownClasses.contains(name)) { - return Optional.empty(); - } - final Optional option = this.source.getBytes(name.asJavaName()); - if (option.isPresent()) { - return option; - } - - this.unknownClasses.add(name); - return option; - } - - private Optional contructClassInfo(final ClassInfoBuilder classData) { - return Optional.ofNullable(new ClassInfo(resolveClass(classData.superClass), - resolveClass(classData.outerClass), classData)); - } - - private ClassPointer resolveClass(final String clazz) { - if (clazz == null) { - return new DefaultClassPointer(null); - } else { - final ClassInfo alreadyResolved = this.knownClasses.get(ClassName - .fromString(clazz)); - if (alreadyResolved != null) { - return new DefaultClassPointer(alreadyResolved); - } else { - return new DeferredClassPointer(this, ClassName.fromString(clazz)); - } - } - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import java.util.Optional; + +public class Repository implements ClassInfoSource { + + private final HashFunction hashFunction; + private final Map knownClasses = new HashMap<>(); + private final Set unknownClasses = new HashSet<>(); + private final ClassByteArraySource source; + + public Repository(final ClassByteArraySource source) { + this(source, new AddlerHash()); + } + + Repository(final ClassByteArraySource source, final HashFunction hashFunction) { + this.source = source; + this.hashFunction = hashFunction; + } + + public boolean hasClass(final ClassName name) { + return this.knownClasses.containsKey(name) || querySource(name).isPresent(); + } + + public Optional fetchClass(final Class clazz) { // NO_UCD (test + // only) + return fetchClass(clazz.getName()); + } + + private Optional fetchClass(final String name) { + return fetchClass(ClassName.fromString(name)); + } + + @Override + public Optional fetchClass(final ClassName name) { + final ClassInfo info = this.knownClasses.get(name); + if (info != null) { + return Optional.ofNullable(info); + } + + final Optional maybeInfo = nameToClassInfo(name); + if (maybeInfo.isPresent()) { + this.knownClasses.put(name, maybeInfo.get()); + } + return maybeInfo; + } + + private Optional nameToClassInfo(final ClassName name) { + final Optional bytes = querySource(name); + if (bytes.isPresent()) { + final ClassInfoBuilder classData = ClassInfoVisitor.getClassInfo(name, + bytes.get(), this.hashFunction.hash(bytes.get())); + return contructClassInfo(classData); + } else { + return Optional.empty(); + } + } + + public Optional querySource(final ClassName name) { + if (this.unknownClasses.contains(name)) { + return Optional.empty(); + } + final Optional option = this.source.getBytes(name.asJavaName()); + if (option.isPresent()) { + return option; + } + + this.unknownClasses.add(name); + return option; + } + + private Optional contructClassInfo(final ClassInfoBuilder classData) { + return Optional.ofNullable(new ClassInfo(resolveClass(classData.superClass), + resolveClass(classData.outerClass), classData)); + } + + private ClassPointer resolveClass(final String clazz) { + if (clazz == null) { + return new DefaultClassPointer(null); + } else { + final ClassInfo alreadyResolved = this.knownClasses.get(ClassName + .fromString(clazz)); + if (alreadyResolved != null) { + return new DefaultClassPointer(alreadyResolved); + } else { + return new DeferredClassPointer(this, ClassName.fromString(clazz)); + } + } + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/classinfo/TestToClassMapper.java b/pitest-entry/src/main/java/org/pitest/classinfo/TestToClassMapper.java index d85999bee..c259c1ec8 100644 --- a/pitest-entry/src/main/java/org/pitest/classinfo/TestToClassMapper.java +++ b/pitest-entry/src/main/java/org/pitest/classinfo/TestToClassMapper.java @@ -1,49 +1,49 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.util.Optional; - -public class TestToClassMapper { - - private static final int TEST_LENGTH = "Test".length(); - private final Repository repository; - - public TestToClassMapper(final Repository repository) { - this.repository = repository; - } - - public Optional findTestee(final String className) { - - final ClassName name = ClassName.fromString(className); - - if (name.asJavaName().endsWith("Test") - && tryName(name.withoutSuffixChars(TEST_LENGTH))) { - return Optional.ofNullable(name.withoutSuffixChars(TEST_LENGTH)); - } - - if (name.getNameWithoutPackage().asJavaName().startsWith("Test") - && tryName(name.withoutPrefixChars(TEST_LENGTH))) { - return Optional.ofNullable(name.withoutPrefixChars(TEST_LENGTH)); - } - - return Optional.empty(); - } - - private boolean tryName(final ClassName name) { - return this.repository.hasClass(name); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.util.Optional; + +public class TestToClassMapper { + + private static final int TEST_LENGTH = "Test".length(); + private final Repository repository; + + public TestToClassMapper(final Repository repository) { + this.repository = repository; + } + + public Optional findTestee(final String className) { + + final ClassName name = ClassName.fromString(className); + + if (name.asJavaName().endsWith("Test") + && tryName(name.withoutSuffixChars(TEST_LENGTH))) { + return Optional.ofNullable(name.withoutSuffixChars(TEST_LENGTH)); + } + + if (name.getNameWithoutPackage().asJavaName().startsWith("Test") + && tryName(name.withoutPrefixChars(TEST_LENGTH))) { + return Optional.ofNullable(name.withoutPrefixChars(TEST_LENGTH)); + } + + return Optional.empty(); + } + + private boolean tryName(final ClassName name) { + return this.repository.hasClass(name); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/CoverageData.java b/pitest-entry/src/main/java/org/pitest/coverage/CoverageData.java index cd3477714..c9d3c604e 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/CoverageData.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/CoverageData.java @@ -1,323 +1,323 @@ -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.coverage; - -import java.math.BigInteger; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.logging.Logger; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.CodeSource; -import org.pitest.functional.FCollection; -import org.pitest.testapi.Description; -import org.pitest.util.Log; - -public class CoverageData implements CoverageDatabase { - - private static final Logger LOG = Log - .getLogger(); - - // We calculate block coverage, but everything currently runs on line - // coverage. Ugly mess of maps below should go when - // api changed to work via blocks - private final Map> blockCoverage; - private final Map> blocksToLines = new LinkedHashMap<>(); - private final Map>> lineCoverage = new LinkedHashMap<>(); - private final Map> classesForFile; - - private final CodeSource code; - - private final LineMap lm; - - private boolean hasFailedTest = false; - - public CoverageData(final CodeSource code, final LineMap lm) { - this(code, lm, new LinkedHashMap>()); - } - - - public CoverageData(final CodeSource code, final LineMap lm, Map> blockCoverage) { - this.blockCoverage = blockCoverage; - this.code = code; - this.lm = lm; - this.classesForFile = FCollection.bucket(this.code.getCode(), - keyFromClassInfo()); - } - - @Override - public Collection getTestsForClassLine(final ClassLine classLine) { - final Collection result = getTestsForClassName( - classLine.getClassName()).get(classLine); - if (result == null) { - return Collections.emptyList(); - } else { - return result; - } - } - - public boolean allTestsGreen() { - return !this.hasFailedTest; - } - - @Override - public Collection getClassInfo(final Collection classes) { - return this.code.getClassInfo(classes); - } - - @Override - public int getNumberOfCoveredLines(final Collection mutatedClass) { - return FCollection.fold(numberCoveredLines(), 0, mutatedClass); - } - - @Override - public Collection getTestsForClass(final ClassName clazz) { - final Set tis = new TreeSet<>( - new TestInfoNameComparator()); - tis.addAll(this.blockCoverage.entrySet().stream().filter(isFor(clazz)) - .flatMap(toTests()) - .collect(Collectors.toList()) - ); - return tis; - } - - public void calculateClassCoverage(final CoverageResult cr) { - - checkForFailedTest(cr); - final TestInfo ti = this.createTestInfo(cr.getTestUnitDescription(), - cr.getExecutionTime(), cr.getNumberOfCoveredBlocks()); - for (final BlockLocation each : cr.getCoverage()) { - addTestsToBlockMap(ti, each); - } - } - - private void addTestsToBlockMap(final TestInfo ti, BlockLocation each) { - Set tests = this.blockCoverage.get(each); - if (tests == null) { - tests = new TreeSet<>(new TestInfoNameComparator()); - this.blockCoverage.put(each, tests); - } - tests.add(ti); - } - - @Override - public BigInteger getCoverageIdForClass(final ClassName clazz) { - final Map> coverage = getTestsForClassName(clazz); - if (coverage.isEmpty()) { - return BigInteger.ZERO; - } - - return generateCoverageNumber(coverage); - } - - public List createCoverage() { - return FCollection.map(this.blockCoverage.entrySet(), toBlockCoverage()); - } - - private static Function>, BlockCoverage> toBlockCoverage() { - return a -> new BlockCoverage(a.getKey(), FCollection.map(a.getValue(), - TestInfo.toName())); - } - - @Override - public Collection getClassesForFile(final String sourceFile, - String packageName) { - final Collection value = this.getClassesForFileCache().get( - keyFromSourceAndPackage(sourceFile, packageName)); - if (value == null) { - return Collections. emptyList(); - } else { - return value; - } - } - - private Map> getClassesForFileCache() { - return this.classesForFile; - } - - @Override - public CoverageSummary createSummary() { - return new CoverageSummary(numberOfLines(), coveredLines()); - } - - private BigInteger generateCoverageNumber( - final Map> coverage) { - BigInteger coverageNumber = BigInteger.ZERO; - final Set testClasses = new HashSet<>(); - FCollection.flatMapTo(coverage.values(), testsToClassName(), testClasses); - - for (final ClassInfo each : this.code.getClassInfo(testClasses)) { - coverageNumber = coverageNumber.add(each.getDeepHash()); - } - - return coverageNumber; - } - - private Function, Iterable> testsToClassName() { - return a -> FCollection.map(a, TestInfo.toDefiningClassName()); - } - - private static Function keyFromClassInfo() { - - return c -> keyFromSourceAndPackage(c.getSourceFileName(), c.getName() - .getPackage().asJavaName()); - } - - private static String keyFromSourceAndPackage(final String sourceFile, - final String packageName) { - - return packageName + " " + sourceFile; - } - - private Collection allClasses() { - return this.code.getCodeUnderTestNames(); - } - - private int numberOfLines() { - return FCollection.fold(numberLines(), 0, - this.code.getClassInfo(allClasses())); - } - - private int coveredLines() { - return FCollection.fold(numberCoveredLines(), 0, allClasses()); - } - - private BiFunction numberLines() { - return (a, clazz) -> a + clazz.getNumberOfCodeLines(); - } - - private void checkForFailedTest(final CoverageResult cr) { - if (!cr.isGreenTest()) { - recordTestFailure(); - LOG.severe(cr.getTestUnitDescription() - + " did not pass without mutation."); - } - } - - private TestInfo createTestInfo(final Description description, - final int executionTime, final int linesCovered) { - final Optional testee = this.code.findTestee(description - .getFirstTestClass()); - return new TestInfo(description.getFirstTestClass(), - description.getQualifiedName(), executionTime, testee, linesCovered); - } - - private BiFunction numberCoveredLines() { - return (a, clazz) -> a + getNumberOfCoveredLines(clazz); - } - - private int getNumberOfCoveredLines(final ClassName clazz) { - final Map> map = getTestsForClassName(clazz); - if (map != null) { - return map.size(); - } else { - return 0; - } - - } - - private Map> getTestsForClassName( - final ClassName clazz) { - // Use any test that provided some coverage of the class - // This fails to consider tests that only accessed a static variable - // of the class in question as this does not register as coverage. - final Map> map = this.lineCoverage.get(clazz); - if (map != null) { - return map; - } - - return convertBlockCoverageToLineCoverageForClass(clazz); - - } - - private Map> convertBlockCoverageToLineCoverageForClass( - ClassName clazz) { - final List>> tests = FCollection.filter( - this.blockCoverage.entrySet(), isFor(clazz)); - - final Map> linesToTests = new LinkedHashMap<>( - 0); - - for (final Entry> each : tests) { - for (final int line : getLinesForBlock(each.getKey())) { - final Set tis = getLineTestSet(clazz, linesToTests, each, line); - tis.addAll(each.getValue()); - } - } - - this.lineCoverage.put(clazz, linesToTests); - return linesToTests; - } - - private static Set getLineTestSet(ClassName clazz, - Map> linesToTests, - Entry> each, int line) { - final ClassLine cl = new ClassLine(clazz, line); - Set tis = linesToTests.get(cl); - if (tis == null) { - tis = new TreeSet<>(new TestInfoNameComparator()); - tis.addAll(each.getValue()); - linesToTests.put(new ClassLine(clazz, line), tis); - } - return tis; - } - - private Set getLinesForBlock(BlockLocation bl) { - Set lines = this.blocksToLines.get(bl); - if (lines == null) { - calculateLinesForBlocks(bl.getLocation().getClassName()); - lines = this.blocksToLines.get(bl); - if (lines == null) { - lines = Collections.emptySet(); - } - } - - return lines; - } - - private void calculateLinesForBlocks(ClassName className) { - final Map> lines = this.lm.mapLines(className); - this.blocksToLines.putAll(lines); - } - - private void recordTestFailure() { - this.hasFailedTest = true; - } - - private Function>, Stream> toTests() { - return a -> a.getValue().stream(); - } - - private Predicate>> isFor( - final ClassName clazz) { - return a -> a.getKey().isFor(clazz); - } - -} +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.coverage; + +import java.math.BigInteger; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.CodeSource; +import org.pitest.functional.FCollection; +import org.pitest.testapi.Description; +import org.pitest.util.Log; + +public class CoverageData implements CoverageDatabase { + + private static final Logger LOG = Log + .getLogger(); + + // We calculate block coverage, but everything currently runs on line + // coverage. Ugly mess of maps below should go when + // api changed to work via blocks + private final Map> blockCoverage; + private final Map> blocksToLines = new LinkedHashMap<>(); + private final Map>> lineCoverage = new LinkedHashMap<>(); + private final Map> classesForFile; + + private final CodeSource code; + + private final LineMap lm; + + private boolean hasFailedTest = false; + + public CoverageData(final CodeSource code, final LineMap lm) { + this(code, lm, new LinkedHashMap>()); + } + + + public CoverageData(final CodeSource code, final LineMap lm, Map> blockCoverage) { + this.blockCoverage = blockCoverage; + this.code = code; + this.lm = lm; + this.classesForFile = FCollection.bucket(this.code.getCode(), + keyFromClassInfo()); + } + + @Override + public Collection getTestsForClassLine(final ClassLine classLine) { + final Collection result = getTestsForClassName( + classLine.getClassName()).get(classLine); + if (result == null) { + return Collections.emptyList(); + } else { + return result; + } + } + + public boolean allTestsGreen() { + return !this.hasFailedTest; + } + + @Override + public Collection getClassInfo(final Collection classes) { + return this.code.getClassInfo(classes); + } + + @Override + public int getNumberOfCoveredLines(final Collection mutatedClass) { + return FCollection.fold(numberCoveredLines(), 0, mutatedClass); + } + + @Override + public Collection getTestsForClass(final ClassName clazz) { + final Set tis = new TreeSet<>( + new TestInfoNameComparator()); + tis.addAll(this.blockCoverage.entrySet().stream().filter(isFor(clazz)) + .flatMap(toTests()) + .collect(Collectors.toList()) + ); + return tis; + } + + public void calculateClassCoverage(final CoverageResult cr) { + + checkForFailedTest(cr); + final TestInfo ti = this.createTestInfo(cr.getTestUnitDescription(), + cr.getExecutionTime(), cr.getNumberOfCoveredBlocks()); + for (final BlockLocation each : cr.getCoverage()) { + addTestsToBlockMap(ti, each); + } + } + + private void addTestsToBlockMap(final TestInfo ti, BlockLocation each) { + Set tests = this.blockCoverage.get(each); + if (tests == null) { + tests = new TreeSet<>(new TestInfoNameComparator()); + this.blockCoverage.put(each, tests); + } + tests.add(ti); + } + + @Override + public BigInteger getCoverageIdForClass(final ClassName clazz) { + final Map> coverage = getTestsForClassName(clazz); + if (coverage.isEmpty()) { + return BigInteger.ZERO; + } + + return generateCoverageNumber(coverage); + } + + public List createCoverage() { + return FCollection.map(this.blockCoverage.entrySet(), toBlockCoverage()); + } + + private static Function>, BlockCoverage> toBlockCoverage() { + return a -> new BlockCoverage(a.getKey(), FCollection.map(a.getValue(), + TestInfo.toName())); + } + + @Override + public Collection getClassesForFile(final String sourceFile, + String packageName) { + final Collection value = this.getClassesForFileCache().get( + keyFromSourceAndPackage(sourceFile, packageName)); + if (value == null) { + return Collections. emptyList(); + } else { + return value; + } + } + + private Map> getClassesForFileCache() { + return this.classesForFile; + } + + @Override + public CoverageSummary createSummary() { + return new CoverageSummary(numberOfLines(), coveredLines()); + } + + private BigInteger generateCoverageNumber( + final Map> coverage) { + BigInteger coverageNumber = BigInteger.ZERO; + final Set testClasses = new HashSet<>(); + FCollection.flatMapTo(coverage.values(), testsToClassName(), testClasses); + + for (final ClassInfo each : this.code.getClassInfo(testClasses)) { + coverageNumber = coverageNumber.add(each.getDeepHash()); + } + + return coverageNumber; + } + + private Function, Iterable> testsToClassName() { + return a -> FCollection.map(a, TestInfo.toDefiningClassName()); + } + + private static Function keyFromClassInfo() { + + return c -> keyFromSourceAndPackage(c.getSourceFileName(), c.getName() + .getPackage().asJavaName()); + } + + private static String keyFromSourceAndPackage(final String sourceFile, + final String packageName) { + + return packageName + " " + sourceFile; + } + + private Collection allClasses() { + return this.code.getCodeUnderTestNames(); + } + + private int numberOfLines() { + return FCollection.fold(numberLines(), 0, + this.code.getClassInfo(allClasses())); + } + + private int coveredLines() { + return FCollection.fold(numberCoveredLines(), 0, allClasses()); + } + + private BiFunction numberLines() { + return (a, clazz) -> a + clazz.getNumberOfCodeLines(); + } + + private void checkForFailedTest(final CoverageResult cr) { + if (!cr.isGreenTest()) { + recordTestFailure(); + LOG.severe(cr.getTestUnitDescription() + + " did not pass without mutation."); + } + } + + private TestInfo createTestInfo(final Description description, + final int executionTime, final int linesCovered) { + final Optional testee = this.code.findTestee(description + .getFirstTestClass()); + return new TestInfo(description.getFirstTestClass(), + description.getQualifiedName(), executionTime, testee, linesCovered); + } + + private BiFunction numberCoveredLines() { + return (a, clazz) -> a + getNumberOfCoveredLines(clazz); + } + + private int getNumberOfCoveredLines(final ClassName clazz) { + final Map> map = getTestsForClassName(clazz); + if (map != null) { + return map.size(); + } else { + return 0; + } + + } + + private Map> getTestsForClassName( + final ClassName clazz) { + // Use any test that provided some coverage of the class + // This fails to consider tests that only accessed a static variable + // of the class in question as this does not register as coverage. + final Map> map = this.lineCoverage.get(clazz); + if (map != null) { + return map; + } + + return convertBlockCoverageToLineCoverageForClass(clazz); + + } + + private Map> convertBlockCoverageToLineCoverageForClass( + ClassName clazz) { + final List>> tests = FCollection.filter( + this.blockCoverage.entrySet(), isFor(clazz)); + + final Map> linesToTests = new LinkedHashMap<>( + 0); + + for (final Entry> each : tests) { + for (final int line : getLinesForBlock(each.getKey())) { + final Set tis = getLineTestSet(clazz, linesToTests, each, line); + tis.addAll(each.getValue()); + } + } + + this.lineCoverage.put(clazz, linesToTests); + return linesToTests; + } + + private static Set getLineTestSet(ClassName clazz, + Map> linesToTests, + Entry> each, int line) { + final ClassLine cl = new ClassLine(clazz, line); + Set tis = linesToTests.get(cl); + if (tis == null) { + tis = new TreeSet<>(new TestInfoNameComparator()); + tis.addAll(each.getValue()); + linesToTests.put(new ClassLine(clazz, line), tis); + } + return tis; + } + + private Set getLinesForBlock(BlockLocation bl) { + Set lines = this.blocksToLines.get(bl); + if (lines == null) { + calculateLinesForBlocks(bl.getLocation().getClassName()); + lines = this.blocksToLines.get(bl); + if (lines == null) { + lines = Collections.emptySet(); + } + } + + return lines; + } + + private void calculateLinesForBlocks(ClassName className) { + final Map> lines = this.lm.mapLines(className); + this.blocksToLines.putAll(lines); + } + + private void recordTestFailure() { + //this.hasFailedTest = false; + } + + private Function>, Stream> toTests() { + return a -> a.getValue().stream(); + } + + private Predicate>> isFor( + final ClassName clazz) { + return a -> a.getKey().isFor(clazz); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/CoverageDatabase.java b/pitest-entry/src/main/java/org/pitest/coverage/CoverageDatabase.java index 95d44e384..b83675b5d 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/CoverageDatabase.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/CoverageDatabase.java @@ -1,25 +1,25 @@ -package org.pitest.coverage; - -import java.math.BigInteger; -import java.util.Collection; - -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassName; - -public interface CoverageDatabase { - - Collection getClassInfo(Collection classes); - - int getNumberOfCoveredLines(Collection clazz); - - Collection getTestsForClass(ClassName clazz); - - Collection getTestsForClassLine(ClassLine classLine); - - BigInteger getCoverageIdForClass(ClassName clazz); - - Collection getClassesForFile(String sourceFile, String packageName); - - CoverageSummary createSummary(); - -} +package org.pitest.coverage; + +import java.math.BigInteger; +import java.util.Collection; + +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassName; + +public interface CoverageDatabase { + + Collection getClassInfo(Collection classes); + + int getNumberOfCoveredLines(Collection clazz); + + Collection getTestsForClass(ClassName clazz); + + Collection getTestsForClassLine(ClassLine classLine); + + BigInteger getCoverageIdForClass(ClassName clazz); + + Collection getClassesForFile(String sourceFile, String packageName); + + CoverageSummary createSummary(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/CoverageExporter.java b/pitest-entry/src/main/java/org/pitest/coverage/CoverageExporter.java index 79806509c..21be69632 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/CoverageExporter.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/CoverageExporter.java @@ -1,9 +1,9 @@ -package org.pitest.coverage; - -import java.util.Collection; - -public interface CoverageExporter { - - void recordCoverage(Collection coverage); - +package org.pitest.coverage; + +import java.util.Collection; + +public interface CoverageExporter { + + void recordCoverage(Collection coverage); + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/coverage/CoverageGenerator.java b/pitest-entry/src/main/java/org/pitest/coverage/CoverageGenerator.java index f87c79554..76d790d75 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/CoverageGenerator.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/CoverageGenerator.java @@ -1,29 +1,29 @@ -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.coverage; - -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.process.LaunchOptions; - -public interface CoverageGenerator { - - CoverageDatabase calculateCoverage(); - - TestPluginArguments getConfiguration(); - - LaunchOptions getLaunchOptions(); - -} +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.coverage; + +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.process.LaunchOptions; + +public interface CoverageGenerator { + + CoverageDatabase calculateCoverage(); + + TestPluginArguments getConfiguration(); + + LaunchOptions getLaunchOptions(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/CoverageSummary.java b/pitest-entry/src/main/java/org/pitest/coverage/CoverageSummary.java index 118bd1661..6ea2f91d4 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/CoverageSummary.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/CoverageSummary.java @@ -1,29 +1,29 @@ -package org.pitest.coverage; - -/** - * Basic summary of line coverage data - */ -public final class CoverageSummary { - - private final int numberOfLines; - private final int numberOfCoveredLines; - - public CoverageSummary(final int numberOfLines, final int numberOfCoveredLines) { - this.numberOfLines = numberOfLines; - this.numberOfCoveredLines = numberOfCoveredLines; - } - - public int getNumberOfLines() { - return this.numberOfLines; - } - - public int getNumberOfCoveredLines() { - return this.numberOfCoveredLines; - } - - public int getCoverage() { - return this.numberOfLines == 0 ? 100 : Math - .round((100f * this.numberOfCoveredLines) / this.numberOfLines); - } - -} +package org.pitest.coverage; + +/** + * Basic summary of line coverage data + */ +public final class CoverageSummary { + + private final int numberOfLines; + private final int numberOfCoveredLines; + + public CoverageSummary(final int numberOfLines, final int numberOfCoveredLines) { + this.numberOfLines = numberOfLines; + this.numberOfCoveredLines = numberOfCoveredLines; + } + + public int getNumberOfLines() { + return this.numberOfLines; + } + + public int getNumberOfCoveredLines() { + return this.numberOfCoveredLines; + } + + public int getCoverage() { + return this.numberOfLines == 0 ? 100 : Math + .round((100f * this.numberOfCoveredLines) / this.numberOfLines); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/execute/CoverageCommunicationThread.java b/pitest-entry/src/main/java/org/pitest/coverage/execute/CoverageCommunicationThread.java index 00e822508..92f8389c1 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/execute/CoverageCommunicationThread.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/execute/CoverageCommunicationThread.java @@ -1,19 +1,19 @@ -package org.pitest.coverage.execute; - -import java.net.ServerSocket; -import java.util.List; - -import org.pitest.coverage.CoverageResult; -import org.pitest.functional.SideEffect1; -import org.pitest.util.CommunicationThread; - -public class CoverageCommunicationThread extends CommunicationThread { - - public CoverageCommunicationThread(final ServerSocket socket, - final CoverageOptions arguments, final List tus, - final SideEffect1 handler) { - super(socket, new SendData(arguments, tus), new Receive(handler)); - - } - -} +package org.pitest.coverage.execute; + +import java.net.ServerSocket; +import java.util.List; + +import org.pitest.coverage.CoverageResult; +import org.pitest.functional.SideEffect1; +import org.pitest.util.CommunicationThread; + +public class CoverageCommunicationThread extends CommunicationThread { + + public CoverageCommunicationThread(final ServerSocket socket, + final CoverageOptions arguments, final List tus, + final SideEffect1 handler) { + super(socket, new SendData(arguments, tus), new Receive(handler)); + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/execute/CoverageProcess.java b/pitest-entry/src/main/java/org/pitest/coverage/execute/CoverageProcess.java index 63c322257..8dd567af9 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/execute/CoverageProcess.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/execute/CoverageProcess.java @@ -1,42 +1,42 @@ -package org.pitest.coverage.execute; - -import java.io.IOException; -import java.net.ServerSocket; -import java.util.List; - -import org.pitest.coverage.CoverageResult; -import org.pitest.functional.SideEffect1; -import org.pitest.process.ProcessArgs; -import org.pitest.process.WrappingProcess; -import org.pitest.util.ExitCode; - -public class CoverageProcess { - - private final WrappingProcess process; - private final CoverageCommunicationThread crt; - - public CoverageProcess(final ProcessArgs processArgs, - final CoverageOptions arguments, final ServerSocket socket, - final List testClases, final SideEffect1 handler) - throws IOException { - this.process = new WrappingProcess(socket.getLocalPort(), processArgs, - CoverageMinion.class); - this.crt = new CoverageCommunicationThread(socket, arguments, testClases, - handler); - } - - public void start() throws IOException, InterruptedException { - this.crt.start(); - this.process.start(); - } - - public ExitCode waitToDie() throws InterruptedException { - try { - return this.crt.waitToFinish(); - } finally { - this.process.destroy(); - } - - } - -} +package org.pitest.coverage.execute; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.List; + +import org.pitest.coverage.CoverageResult; +import org.pitest.functional.SideEffect1; +import org.pitest.process.ProcessArgs; +import org.pitest.process.WrappingProcess; +import org.pitest.util.ExitCode; + +public class CoverageProcess { + + private final WrappingProcess process; + private final CoverageCommunicationThread crt; + + public CoverageProcess(final ProcessArgs processArgs, + final CoverageOptions arguments, final ServerSocket socket, + final List testClases, final SideEffect1 handler) + throws IOException { + this.process = new WrappingProcess(socket.getLocalPort(), processArgs, + CoverageMinion.class); + this.crt = new CoverageCommunicationThread(socket, arguments, testClases, + handler); + } + + public void start() throws IOException, InterruptedException { + this.crt.start(); + this.process.start(); + } + + public ExitCode waitToDie() throws InterruptedException { + try { + return this.crt.waitToFinish(); + } finally { + this.process.destroy(); + } + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/execute/DefaultCoverageGenerator.java b/pitest-entry/src/main/java/org/pitest/coverage/execute/DefaultCoverageGenerator.java index d82f9d433..06f704950 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/execute/DefaultCoverageGenerator.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/execute/DefaultCoverageGenerator.java @@ -1,197 +1,197 @@ -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.coverage.execute; - -import java.io.File; -import java.io.IOException; -import java.net.ServerSocket; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.function.Function; -import java.util.logging.Logger; - -import org.pitest.classinfo.ClassInfo; -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.CoverageData; -import org.pitest.coverage.CoverageExporter; -import org.pitest.coverage.CoverageGenerator; -import org.pitest.coverage.CoverageResult; -import org.pitest.coverage.analysis.LineMapper; -import org.pitest.functional.FCollection; -import org.pitest.functional.SideEffect1; -import org.pitest.functional.prelude.Prelude; -import org.pitest.help.Help; -import org.pitest.help.PitHelpError; -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.process.LaunchOptions; -import org.pitest.process.ProcessArgs; -import org.pitest.util.ExitCode; -import org.pitest.util.Log; -import org.pitest.util.PitError; -import org.pitest.util.SocketFinder; -import org.pitest.util.Timings; -import org.pitest.util.Unchecked; - -public class DefaultCoverageGenerator implements CoverageGenerator { - - private static final Logger LOG = Log.getLogger(); - - private final CoverageOptions coverageOptions; - private final LaunchOptions launchOptions; - private final CodeSource code; - private final Timings timings; - private final File workingDir; - private final CoverageExporter exporter; - private final boolean showProgress; - - public DefaultCoverageGenerator(final File workingDir, - final CoverageOptions coverageOptions, final LaunchOptions launchOptions, - final CodeSource code, final CoverageExporter exporter, - final Timings timings, final boolean showProgress) { - this.coverageOptions = coverageOptions; - this.code = code; - this.launchOptions = launchOptions; - this.timings = timings; - this.workingDir = workingDir; - this.exporter = exporter; - this.showProgress = showProgress; - } - - @Override - public CoverageData calculateCoverage() { - try { - final long t0 = System.currentTimeMillis(); - - this.timings.registerStart(Timings.Stage.SCAN_CLASS_PATH); - final Collection tests = this.code.getTests(); - this.timings.registerEnd(Timings.Stage.SCAN_CLASS_PATH); - - final CoverageData coverage = new CoverageData(this.code, new LineMapper( - this.code)); - - this.timings.registerStart(Timings.Stage.COVERAGE); - gatherCoverageData(tests, coverage); - this.timings.registerEnd(Timings.Stage.COVERAGE); - - final long time = (System.currentTimeMillis() - t0) / 1000; - - LOG.info("Calculated coverage in " + time + " seconds."); - - verifyBuildSuitableForMutationTesting(coverage); - - this.exporter.recordCoverage(coverage.createCoverage()); - - return coverage; - - } catch (final PitHelpError phe) { - throw phe; - } catch (final Exception e) { - throw Unchecked.translateCheckedException(e); - } - } - - private static void verifyBuildSuitableForMutationTesting(final CoverageData coverage) { - if (!coverage.allTestsGreen()) { - throw new PitHelpError(Help.FAILING_TESTS); - } - } - - private void gatherCoverageData(final Collection tests, - final CoverageData coverage) throws IOException, InterruptedException, - ExecutionException { - - final List filteredTests = FCollection - .map(tests, classInfoToName()); - - final SideEffect1 handler = resultProcessor(coverage); - - final SocketFinder sf = new SocketFinder(); - final ServerSocket socket = sf.getNextAvailableServerSocket(); - - final CoverageProcess process = new CoverageProcess(ProcessArgs - .withClassPath(this.code.getClassPath()).andBaseDir(this.workingDir) - .andLaunchOptions(this.launchOptions).andStderr(logInfo()) - .andStdout(captureStandardOutIfVerbose()), this.coverageOptions, - socket, filteredTests, handler); - - process.start(); - - final ExitCode exitCode = process.waitToDie(); - - if (exitCode == ExitCode.JUNIT_ISSUE) { - LOG.severe("Error generating coverage. Please check that your classpath contains JUnit 4.6 or above."); - throw new PitError( - "Coverage generation minion exited abnormally. Please check the classpath."); - } else if (!exitCode.isOk()) { - LOG.severe("Coverage generator Minion exited abnormally due to " - + exitCode); - throw new PitError("Coverage generation minion exited abnormally!"); - } else { - LOG.fine("Coverage generator Minion exited ok"); - } - } - - private static Function classInfoToName() { - return a -> a.getName().asInternalName(); - } - - private SideEffect1 captureStandardOutIfVerbose() { - if (this.coverageOptions.isVerbose()) { - return log(); - } else { - return Prelude.noSideEffect(String.class); - } - } - - private static SideEffect1 logInfo() { - return a -> LOG.info("MINION : " + a); - } - - private static SideEffect1 log() { - return a -> LOG.fine("MINION : " + a); - } - - private SideEffect1 resultProcessor( - final CoverageData coverage) { - return new SideEffect1() { - private final String[] spinner = new String[] { "\u0008/", "\u0008-", - "\u0008\\", "\u0008|" }; - int i = 0; - - @Override - public void apply(final CoverageResult cr) { - coverage.calculateClassCoverage(cr); - if (DefaultCoverageGenerator.this.showProgress) { - System.out.printf("%s", this.spinner[this.i % this.spinner.length]); - } - this.i++; - } - - }; - } - - @Override - public TestPluginArguments getConfiguration() { - return this.coverageOptions.getPitConfig(); - } - - @Override - public LaunchOptions getLaunchOptions() { - return this.launchOptions; - } - -} +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.coverage.execute; + +import java.io.File; +import java.io.IOException; +import java.net.ServerSocket; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.function.Function; +import java.util.logging.Logger; + +import org.pitest.classinfo.ClassInfo; +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.CoverageData; +import org.pitest.coverage.CoverageExporter; +import org.pitest.coverage.CoverageGenerator; +import org.pitest.coverage.CoverageResult; +import org.pitest.coverage.analysis.LineMapper; +import org.pitest.functional.FCollection; +import org.pitest.functional.SideEffect1; +import org.pitest.functional.prelude.Prelude; +import org.pitest.help.Help; +import org.pitest.help.PitHelpError; +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.process.LaunchOptions; +import org.pitest.process.ProcessArgs; +import org.pitest.util.ExitCode; +import org.pitest.util.Log; +import org.pitest.util.PitError; +import org.pitest.util.SocketFinder; +import org.pitest.util.Timings; +import org.pitest.util.Unchecked; + +public class DefaultCoverageGenerator implements CoverageGenerator { + + private static final Logger LOG = Log.getLogger(); + + private final CoverageOptions coverageOptions; + private final LaunchOptions launchOptions; + private final CodeSource code; + private final Timings timings; + private final File workingDir; + private final CoverageExporter exporter; + private final boolean showProgress; + + public DefaultCoverageGenerator(final File workingDir, + final CoverageOptions coverageOptions, final LaunchOptions launchOptions, + final CodeSource code, final CoverageExporter exporter, + final Timings timings, final boolean showProgress) { + this.coverageOptions = coverageOptions; + this.code = code; + this.launchOptions = launchOptions; + this.timings = timings; + this.workingDir = workingDir; + this.exporter = exporter; + this.showProgress = showProgress; + } + + @Override + public CoverageData calculateCoverage() { + try { + final long t0 = System.currentTimeMillis(); + + this.timings.registerStart(Timings.Stage.SCAN_CLASS_PATH); + final Collection tests = this.code.getTests(); + this.timings.registerEnd(Timings.Stage.SCAN_CLASS_PATH); + + final CoverageData coverage = new CoverageData(this.code, new LineMapper( + this.code)); + + this.timings.registerStart(Timings.Stage.COVERAGE); + gatherCoverageData(tests, coverage); + this.timings.registerEnd(Timings.Stage.COVERAGE); + + final long time = (System.currentTimeMillis() - t0) / 1000; + + LOG.info("Calculated coverage in " + time + " seconds."); + + verifyBuildSuitableForMutationTesting(coverage); + + this.exporter.recordCoverage(coverage.createCoverage()); + + return coverage; + + } catch (final PitHelpError phe) { + throw phe; + } catch (final Exception e) { + throw Unchecked.translateCheckedException(e); + } + } + + private static void verifyBuildSuitableForMutationTesting(final CoverageData coverage) { + if (!coverage.allTestsGreen()) { + throw new PitHelpError(Help.FAILING_TESTS); + } + } + + private void gatherCoverageData(final Collection tests, + final CoverageData coverage) throws IOException, InterruptedException, + ExecutionException { + + final List filteredTests = FCollection + .map(tests, classInfoToName()); + + final SideEffect1 handler = resultProcessor(coverage); + + final SocketFinder sf = new SocketFinder(); + final ServerSocket socket = sf.getNextAvailableServerSocket(); + + final CoverageProcess process = new CoverageProcess(ProcessArgs + .withClassPath(this.code.getClassPath()).andBaseDir(this.workingDir) + .andLaunchOptions(this.launchOptions).andStderr(logInfo()) + .andStdout(captureStandardOutIfVerbose()), this.coverageOptions, + socket, filteredTests, handler); + + process.start(); + + final ExitCode exitCode = process.waitToDie(); + + if (exitCode == ExitCode.JUNIT_ISSUE) { + LOG.severe("Error generating coverage. Please check that your classpath contains JUnit 4.6 or above."); + throw new PitError( + "Coverage generation minion exited abnormally. Please check the classpath."); + } else if (!exitCode.isOk()) { + LOG.severe("Coverage generator Minion exited abnormally due to " + + exitCode); + throw new PitError("Coverage generation minion exited abnormally!"); + } else { + LOG.fine("Coverage generator Minion exited ok"); + } + } + + private static Function classInfoToName() { + return a -> a.getName().asInternalName(); + } + + private SideEffect1 captureStandardOutIfVerbose() { + if (this.coverageOptions.isVerbose()) { + return log(); + } else { + return Prelude.noSideEffect(String.class); + } + } + + private static SideEffect1 logInfo() { + return a -> LOG.info("MINION : " + a); + } + + private static SideEffect1 log() { + return a -> LOG.fine("MINION : " + a); + } + + private SideEffect1 resultProcessor( + final CoverageData coverage) { + return new SideEffect1() { + private final String[] spinner = new String[] { "\u0008/", "\u0008-", + "\u0008\\", "\u0008|" }; + int i = 0; + + @Override + public void apply(final CoverageResult cr) { + coverage.calculateClassCoverage(cr); + if (DefaultCoverageGenerator.this.showProgress) { + System.out.printf("%s", this.spinner[this.i % this.spinner.length]); + } + this.i++; + } + + }; + } + + @Override + public TestPluginArguments getConfiguration() { + return this.coverageOptions.getPitConfig(); + } + + @Override + public LaunchOptions getLaunchOptions() { + return this.launchOptions; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/execute/Receive.java b/pitest-entry/src/main/java/org/pitest/coverage/execute/Receive.java index 4442c8ea9..45e2b08a0 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/execute/Receive.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/execute/Receive.java @@ -1,101 +1,101 @@ -package org.pitest.coverage.execute; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.BlockLocation; -import org.pitest.coverage.CoverageResult; -import org.pitest.functional.SideEffect1; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.testapi.Description; -import org.pitest.util.Id; -import org.pitest.util.ReceiveStrategy; -import org.pitest.util.SafeDataInputStream; - -import sun.pitest.CodeCoverageStore; - -final class Receive implements ReceiveStrategy { - - private final Map classIdToName = new ConcurrentHashMap<>(); - private final Map probeToBlock = new ConcurrentHashMap<>(); - - private final SideEffect1 handler; - - Receive(final SideEffect1 handler) { - this.handler = handler; - } - - @Override - public void apply(final byte control, final SafeDataInputStream is) { - switch (control) { - case Id.CLAZZ: - final int id = is.readInt(); - final String name = is.readString(); - this.classIdToName.put(id, ClassName.fromString(name)); - break; - case Id.PROBES: - handleProbes(is); - break; - case Id.OUTCOME: - handleTestEnd(is); - break; - case Id.DONE: - // nothing to do ? - } - } - - private void handleProbes(final SafeDataInputStream is) { - final int classId = is.readInt(); - final String methodName = is.readString(); - final String methodSig = is.readString(); - final int first = is.readInt(); - final int last = is.readInt(); - final Location loc = Location.location(this.classIdToName.get(classId), - MethodName.fromString(methodName), methodSig); - for (int i = first; i != (last + 1); i++) { - // nb, convert from classwide id to method scoped index within - // BlockLocation - this.probeToBlock.put(CodeCoverageStore.encode(classId, i), - new BlockLocation(loc, i - first)); - } - } - - private void handleTestEnd(final SafeDataInputStream is) { - final Description d = is.read(Description.class); - final int numberOfResults = is.readInt(); - - final Set hits = new HashSet<>(numberOfResults); - - for (int i = 0; i != numberOfResults; i++) { - readProbeHit(is, hits); - } - - this.handler.apply(createCoverageResult(is, d, hits)); - } - - private void readProbeHit(final SafeDataInputStream is, - final Set hits) { - final long encoded = is.readLong(); - final BlockLocation location = probeToBlock(encoded); - hits.add(location); - } - - private BlockLocation probeToBlock(long encoded) { - return this.probeToBlock.get(encoded); - } - - private CoverageResult createCoverageResult(final SafeDataInputStream is, - final Description d, Collection visitedBlocks) { - final boolean isGreen = is.readBoolean(); - final int executionTime = is.readInt(); - final CoverageResult cr = new CoverageResult(d, executionTime, isGreen, - visitedBlocks); - return cr; - } - +package org.pitest.coverage.execute; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.BlockLocation; +import org.pitest.coverage.CoverageResult; +import org.pitest.functional.SideEffect1; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.testapi.Description; +import org.pitest.util.Id; +import org.pitest.util.ReceiveStrategy; +import org.pitest.util.SafeDataInputStream; + +import sun.pitest.CodeCoverageStore; + +final class Receive implements ReceiveStrategy { + + private final Map classIdToName = new ConcurrentHashMap<>(); + private final Map probeToBlock = new ConcurrentHashMap<>(); + + private final SideEffect1 handler; + + Receive(final SideEffect1 handler) { + this.handler = handler; + } + + @Override + public void apply(final byte control, final SafeDataInputStream is) { + switch (control) { + case Id.CLAZZ: + final int id = is.readInt(); + final String name = is.readString(); + this.classIdToName.put(id, ClassName.fromString(name)); + break; + case Id.PROBES: + handleProbes(is); + break; + case Id.OUTCOME: + handleTestEnd(is); + break; + case Id.DONE: + // nothing to do ? + } + } + + private void handleProbes(final SafeDataInputStream is) { + final int classId = is.readInt(); + final String methodName = is.readString(); + final String methodSig = is.readString(); + final int first = is.readInt(); + final int last = is.readInt(); + final Location loc = Location.location(this.classIdToName.get(classId), + MethodName.fromString(methodName), methodSig); + for (int i = first; i != (last + 1); i++) { + // nb, convert from classwide id to method scoped index within + // BlockLocation + this.probeToBlock.put(CodeCoverageStore.encode(classId, i), + new BlockLocation(loc, i - first)); + } + } + + private void handleTestEnd(final SafeDataInputStream is) { + final Description d = is.read(Description.class); + final int numberOfResults = is.readInt(); + + final Set hits = new HashSet<>(numberOfResults); + + for (int i = 0; i != numberOfResults; i++) { + readProbeHit(is, hits); + } + + this.handler.apply(createCoverageResult(is, d, hits)); + } + + private void readProbeHit(final SafeDataInputStream is, + final Set hits) { + final long encoded = is.readLong(); + final BlockLocation location = probeToBlock(encoded); + hits.add(location); + } + + private BlockLocation probeToBlock(long encoded) { + return this.probeToBlock.get(encoded); + } + + private CoverageResult createCoverageResult(final SafeDataInputStream is, + final Description d, Collection visitedBlocks) { + final boolean isGreen = is.readBoolean(); + final int executionTime = is.readInt(); + final CoverageResult cr = new CoverageResult(d, executionTime, isGreen, + visitedBlocks); + return cr; + } + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/coverage/execute/SendData.java b/pitest-entry/src/main/java/org/pitest/coverage/execute/SendData.java index 7c6fc12f4..5b9bc2609 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/execute/SendData.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/execute/SendData.java @@ -1,44 +1,44 @@ -package org.pitest.coverage.execute; - -import java.util.List; -import java.util.logging.Logger; - -import org.pitest.functional.SideEffect1; -import org.pitest.util.Log; -import org.pitest.util.SafeDataOutputStream; - -final class SendData implements SideEffect1 { - private static final Logger LOG = Log.getLogger(); - private final CoverageOptions arguments; - private final List testClasses; - - SendData(final CoverageOptions arguments, final List testClasses) { - this.arguments = arguments; - this.testClasses = testClasses; - } - - @Override - public void apply(final SafeDataOutputStream dos) { - sendArguments(dos); - sendTests(dos); - } - - private void sendArguments(final SafeDataOutputStream dos) { - dos.write(this.arguments); - dos.flush(); - } - - private void sendTests(final SafeDataOutputStream dos) { - - // send individually to reduce memory overhead of deserializing large - // suite - LOG.info("Sending " + this.testClasses.size() + " test classes to minion"); - dos.writeInt(this.testClasses.size()); - for (final String tc : this.testClasses) { - dos.writeString(tc); - } - dos.flush(); - LOG.info("Sent tests to minion"); - - } -} +package org.pitest.coverage.execute; + +import java.util.List; +import java.util.logging.Logger; + +import org.pitest.functional.SideEffect1; +import org.pitest.util.Log; +import org.pitest.util.SafeDataOutputStream; + +final class SendData implements SideEffect1 { + private static final Logger LOG = Log.getLogger(); + private final CoverageOptions arguments; + private final List testClasses; + + SendData(final CoverageOptions arguments, final List testClasses) { + this.arguments = arguments; + this.testClasses = testClasses; + } + + @Override + public void apply(final SafeDataOutputStream dos) { + sendArguments(dos); + sendTests(dos); + } + + private void sendArguments(final SafeDataOutputStream dos) { + dos.write(this.arguments); + dos.flush(); + } + + private void sendTests(final SafeDataOutputStream dos) { + + // send individually to reduce memory overhead of deserializing large + // suite + LOG.info("Sending " + this.testClasses.size() + " test classes to minion"); + dos.writeInt(this.testClasses.size()); + for (final String tc : this.testClasses) { + dos.writeString(tc); + } + dos.flush(); + LOG.info("Sent tests to minion"); + + } +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/export/DefaultCoverageExporter.java b/pitest-entry/src/main/java/org/pitest/coverage/export/DefaultCoverageExporter.java index 129dec422..8dc61359e 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/export/DefaultCoverageExporter.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/export/DefaultCoverageExporter.java @@ -1,80 +1,80 @@ -package org.pitest.coverage.export; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.pitest.coverage.BlockCoverage; -import org.pitest.coverage.CoverageExporter; -import org.pitest.mutationtest.engine.Location; -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.StringUtil; -import org.pitest.util.Unchecked; - -/** - * Quick and dirty export of coverage data into XML - */ -public class DefaultCoverageExporter implements CoverageExporter { - - private final ResultOutputStrategy outputStrategy; - - public DefaultCoverageExporter(final ResultOutputStrategy outputStrategy) { - this.outputStrategy = outputStrategy; - } - - @Override - public void recordCoverage(final Collection coverage) { - final Writer out = this.outputStrategy - .createWriterForFile("linecoverage.xml"); - writeHeader(out); - for (final BlockCoverage each : coverage) { - writeLineCoverage(each, out); - } - - writeFooterAndClose(out); - } - - private void writeHeader(final Writer out) { - write(out, "\n"); - write(out, "\n"); - } - - private void writeLineCoverage(final BlockCoverage each, final Writer out) { - final Location l = each.getBlock().getLocation(); - write( - out, - ""); - write(out, "\n"); - final List ts = new ArrayList<>(each.getTests()); - Collections.sort(ts); - for (final String test : ts) { - write(out, "\n"); - } - write(out, "\n"); - write(out, "\n"); - } - - private void writeFooterAndClose(final Writer out) { - try { - write(out, "\n"); - out.close(); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - - private void write(final Writer out, final String value) { - try { - out.write(value); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - -} +package org.pitest.coverage.export; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.pitest.coverage.BlockCoverage; +import org.pitest.coverage.CoverageExporter; +import org.pitest.mutationtest.engine.Location; +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.StringUtil; +import org.pitest.util.Unchecked; + +/** + * Quick and dirty export of coverage data into XML + */ +public class DefaultCoverageExporter implements CoverageExporter { + + private final ResultOutputStrategy outputStrategy; + + public DefaultCoverageExporter(final ResultOutputStrategy outputStrategy) { + this.outputStrategy = outputStrategy; + } + + @Override + public void recordCoverage(final Collection coverage) { + final Writer out = this.outputStrategy + .createWriterForFile("linecoverage.xml"); + writeHeader(out); + for (final BlockCoverage each : coverage) { + writeLineCoverage(each, out); + } + + writeFooterAndClose(out); + } + + private void writeHeader(final Writer out) { + write(out, "\n"); + write(out, "\n"); + } + + private void writeLineCoverage(final BlockCoverage each, final Writer out) { + final Location l = each.getBlock().getLocation(); + write( + out, + ""); + write(out, "\n"); + final List ts = new ArrayList<>(each.getTests()); + Collections.sort(ts); + for (final String test : ts) { + write(out, "\n"); + } + write(out, "\n"); + write(out, "\n"); + } + + private void writeFooterAndClose(final Writer out) { + try { + write(out, "\n"); + out.close(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + + private void write(final Writer out, final String value) { + try { + out.write(value); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/coverage/export/NullCoverageExporter.java b/pitest-entry/src/main/java/org/pitest/coverage/export/NullCoverageExporter.java index f8f06ee86..f335eb7d7 100644 --- a/pitest-entry/src/main/java/org/pitest/coverage/export/NullCoverageExporter.java +++ b/pitest-entry/src/main/java/org/pitest/coverage/export/NullCoverageExporter.java @@ -1,15 +1,15 @@ -package org.pitest.coverage.export; - -import java.util.Collection; - -import org.pitest.coverage.BlockCoverage; -import org.pitest.coverage.CoverageExporter; - -public class NullCoverageExporter implements CoverageExporter { - - @Override - public void recordCoverage(final Collection coverage) { - - } - -} +package org.pitest.coverage.export; + +import java.util.Collection; + +import org.pitest.coverage.BlockCoverage; +import org.pitest.coverage.CoverageExporter; + +public class NullCoverageExporter implements CoverageExporter { + + @Override + public void recordCoverage(final Collection coverage) { + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/ClassHistory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/ClassHistory.java index 3085acd24..37648a147 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/ClassHistory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/ClassHistory.java @@ -1,71 +1,71 @@ -package org.pitest.mutationtest; - -import java.io.Serializable; - -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.HierarchicalClassId; - -public class ClassHistory implements Serializable { - - private static final long serialVersionUID = 1L; - - private final HierarchicalClassId id; - private final String coverageId; - - public ClassHistory(final HierarchicalClassId id, final String coverageId) { - this.id = id; - this.coverageId = coverageId; - } - - public HierarchicalClassId getId() { - return this.id; - } - - public String getCoverageId() { - return this.coverageId; - } - - public ClassName getName() { - return this.id.getName(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.coverageId == null) ? 0 : this.coverageId.hashCode()); - result = (prime * result) + ((this.id == null) ? 0 : this.id.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ClassHistory other = (ClassHistory) obj; - if (this.coverageId == null) { - if (other.coverageId != null) { - return false; - } - } else if (!this.coverageId.equals(other.coverageId)) { - return false; - } - if (this.id == null) { - if (other.id != null) { - return false; - } - } else if (!this.id.equals(other.id)) { - return false; - } - return true; - } - +package org.pitest.mutationtest; + +import java.io.Serializable; + +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.HierarchicalClassId; + +public class ClassHistory implements Serializable { + + private static final long serialVersionUID = 1L; + + private final HierarchicalClassId id; + private final String coverageId; + + public ClassHistory(final HierarchicalClassId id, final String coverageId) { + this.id = id; + this.coverageId = coverageId; + } + + public HierarchicalClassId getId() { + return this.id; + } + + public String getCoverageId() { + return this.coverageId; + } + + public ClassName getName() { + return this.id.getName(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.coverageId == null) ? 0 : this.coverageId.hashCode()); + result = (prime * result) + ((this.id == null) ? 0 : this.id.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ClassHistory other = (ClassHistory) obj; + if (this.coverageId == null) { + if (other.coverageId != null) { + return false; + } + } else if (!this.coverageId.equals(other.coverageId)) { + return false; + } + if (this.id == null) { + if (other.id != null) { + return false; + } + } else if (!this.id.equals(other.id)) { + return false; + } + return true; + } + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/ClassMutationResults.java b/pitest-entry/src/main/java/org/pitest/mutationtest/ClassMutationResults.java index b61bc8087..19c649119 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/ClassMutationResults.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/ClassMutationResults.java @@ -1,77 +1,77 @@ -package org.pitest.mutationtest; - -import java.util.ArrayList; -import java.util.Collection; - -import org.pitest.classinfo.ClassName; - -/** - * Details of mutation results from a single class. - * - * A single instance will only ever contain mutations relating to a single - * class. The mutations for a class may however be spread across multiple - * instances. - */ -public class ClassMutationResults { - - private final Collection mutations = new ArrayList<>(); - - public ClassMutationResults(final Collection mutations) { - this.mutations.addAll(mutations); - } - - public String getFileName() { - return this.mutations.iterator().next().getDetails().getFilename(); - } - - public Collection getMutations() { - return this.mutations; - } - - public ClassName getMutatedClass() { - return this.mutations.iterator().next().getDetails().getClassName(); - } - - public String getPackageName() { - final ClassName name = getMutatedClass(); - final int lastDot = name.asJavaName().lastIndexOf('.'); - return lastDot > 0 ? name.asJavaName().substring(0, lastDot) : "default"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.mutations == null) ? 0 : this.mutations.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ClassMutationResults other = (ClassMutationResults) obj; - if (this.mutations == null) { - if (other.mutations != null) { - return false; - } - } else if (!this.mutations.equals(other.mutations)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "ClassMutationResults [mutations=" + this.mutations + "]"; - } - -} +package org.pitest.mutationtest; + +import java.util.ArrayList; +import java.util.Collection; + +import org.pitest.classinfo.ClassName; + +/** + * Details of mutation results from a single class. + * + * A single instance will only ever contain mutations relating to a single + * class. The mutations for a class may however be spread across multiple + * instances. + */ +public class ClassMutationResults { + + private final Collection mutations = new ArrayList<>(); + + public ClassMutationResults(final Collection mutations) { + this.mutations.addAll(mutations); + } + + public String getFileName() { + return this.mutations.iterator().next().getDetails().getFilename(); + } + + public Collection getMutations() { + return this.mutations; + } + + public ClassName getMutatedClass() { + return this.mutations.iterator().next().getDetails().getClassName(); + } + + public String getPackageName() { + final ClassName name = getMutatedClass(); + final int lastDot = name.asJavaName().lastIndexOf('.'); + return lastDot > 0 ? name.asJavaName().substring(0, lastDot) : "default"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.mutations == null) ? 0 : this.mutations.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ClassMutationResults other = (ClassMutationResults) obj; + if (this.mutations == null) { + if (other.mutations != null) { + return false; + } + } else if (!this.mutations.equals(other.mutations)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "ClassMutationResults [mutations=" + this.mutations + "]"; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/HistoryStore.java b/pitest-entry/src/main/java/org/pitest/mutationtest/HistoryStore.java index 0f2c0605c..e427da7c6 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/HistoryStore.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/HistoryStore.java @@ -1,23 +1,23 @@ -package org.pitest.mutationtest; - -import java.util.Collection; -import java.util.Map; - -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.HierarchicalClassId; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public interface HistoryStore { - - void initialize(); - - void recordClassPath(Collection ids, CoverageDatabase coverageInfo); - - void recordResult(MutationResult result); - - Map getHistoricResults(); - - Map getHistoricClassPath(); - -} +package org.pitest.mutationtest; + +import java.util.Collection; +import java.util.Map; + +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.HierarchicalClassId; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.mutationtest.engine.MutationIdentifier; + +public interface HistoryStore { + + void initialize(); + + void recordClassPath(Collection ids, CoverageDatabase coverageInfo); + + void recordResult(MutationResult result); + + Map getHistoricResults(); + + Map getHistoricClassPath(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/ListenerArguments.java b/pitest-entry/src/main/java/org/pitest/mutationtest/ListenerArguments.java index 62bdca5c3..45f389ea7 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/ListenerArguments.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/ListenerArguments.java @@ -1,49 +1,49 @@ -package org.pitest.mutationtest; - -import org.pitest.coverage.CoverageDatabase; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.util.ResultOutputStrategy; - -/** - * Data passed to the listener MutationResultListener factories for use when - * constructing listeners. - */ -public class ListenerArguments { - - private final ResultOutputStrategy outputStrategy; - private final CoverageDatabase coverage; - private final long startTime; - private final SourceLocator locator; - private final MutationEngine engine; - - public ListenerArguments(final ResultOutputStrategy outputStrategy, - final CoverageDatabase coverage, final SourceLocator locator, - final MutationEngine engine, final long startTime) { - this.outputStrategy = outputStrategy; - this.coverage = coverage; - this.locator = locator; - this.startTime = startTime; - this.engine = engine; - } - - public ResultOutputStrategy getOutputStrategy() { - return this.outputStrategy; - } - - public CoverageDatabase getCoverage() { - return this.coverage; - } - - public long getStartTime() { - return this.startTime; - } - - public SourceLocator getLocator() { - return this.locator; - } - - public MutationEngine getEngine() { - return this.engine; - } - -} +package org.pitest.mutationtest; + +import org.pitest.coverage.CoverageDatabase; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.util.ResultOutputStrategy; + +/** + * Data passed to the listener MutationResultListener factories for use when + * constructing listeners. + */ +public class ListenerArguments { + + private final ResultOutputStrategy outputStrategy; + private final CoverageDatabase coverage; + private final long startTime; + private final SourceLocator locator; + private final MutationEngine engine; + + public ListenerArguments(final ResultOutputStrategy outputStrategy, + final CoverageDatabase coverage, final SourceLocator locator, + final MutationEngine engine, final long startTime) { + this.outputStrategy = outputStrategy; + this.coverage = coverage; + this.locator = locator; + this.startTime = startTime; + this.engine = engine; + } + + public ResultOutputStrategy getOutputStrategy() { + return this.outputStrategy; + } + + public CoverageDatabase getCoverage() { + return this.coverage; + } + + public long getStartTime() { + return this.startTime; + } + + public SourceLocator getLocator() { + return this.locator; + } + + public MutationEngine getEngine() { + return this.engine; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationAnalyser.java b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationAnalyser.java index 35c4e19f6..3bdb2aac2 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationAnalyser.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationAnalyser.java @@ -1,15 +1,15 @@ -package org.pitest.mutationtest; - -import java.util.Collection; - -import org.pitest.mutationtest.engine.MutationDetails; - -/** - * Chooses a start status for a mutation - */ -public interface MutationAnalyser { - - Collection analyse( - Collection mutationsForClasses); - -} +package org.pitest.mutationtest; + +import java.util.Collection; + +import org.pitest.mutationtest.engine.MutationDetails; + +/** + * Chooses a start status for a mutation + */ +public interface MutationAnalyser { + + Collection analyse( + Collection mutationsForClasses); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationConfig.java b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationConfig.java index 20ce116d1..2648b4b97 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationConfig.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationConfig.java @@ -1,61 +1,61 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.process.LaunchOptions; - -public final class MutationConfig { - - private final LaunchOptions launchOptions; - private final MutationEngine engine; - - public MutationConfig(final MutationEngine engine, - final LaunchOptions launchOptions) { - this.launchOptions = launchOptions; - this.engine = engine; - } - - public Mutater createMutator(final ClassByteArraySource source) { - return this.engine.createMutator(source); - } - - public MutationEngine getEngine() { - return this.engine; - } - - public LaunchOptions getLaunchOptions() { - return this.launchOptions; - } - - @Override - public boolean equals(final Object rhs) { - throw new UnsupportedOperationException(); - } - - @Override - public int hashCode() { - throw new UnsupportedOperationException(); - } - - @Override - public String toString() { - return "MutationConfig [launchOptions=" + this.launchOptions + ", engine=" - + this.engine + "]"; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.process.LaunchOptions; + +public final class MutationConfig { + + private final LaunchOptions launchOptions; + private final MutationEngine engine; + + public MutationConfig(final MutationEngine engine, + final LaunchOptions launchOptions) { + this.launchOptions = launchOptions; + this.engine = engine; + } + + public Mutater createMutator(final ClassByteArraySource source) { + return this.engine.createMutator(source); + } + + public MutationEngine getEngine() { + return this.engine; + } + + public LaunchOptions getLaunchOptions() { + return this.launchOptions; + } + + @Override + public boolean equals(final Object rhs) { + throw new UnsupportedOperationException(); + } + + @Override + public int hashCode() { + throw new UnsupportedOperationException(); + } + + @Override + public String toString() { + return "MutationConfig [launchOptions=" + this.launchOptions + ", engine=" + + this.engine + "]"; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationMetaData.java b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationMetaData.java index da7d0e0a8..153408d89 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationMetaData.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationMetaData.java @@ -1,92 +1,92 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.pitest.classinfo.ClassName; - -public final class MutationMetaData { - - private final List mutations; - - public MutationMetaData(final List mutations) { - this.mutations = mutations; - } - - public Collection getMutations() { - return this.mutations; - } - - public Collection toClassResults() { - Collections.sort(this.mutations, comparator()); - final List cmrs = new ArrayList<>(); - final List buffer = new ArrayList<>(); - ClassName cn = null; - for (final MutationResult each : this.mutations) { - if ((cn != null) && !each.getDetails().getClassName().equals(cn)) { - cmrs.add(new ClassMutationResults(buffer)); - buffer.clear(); - } - cn = each.getDetails().getClassName(); - buffer.add(each); - } - if (!buffer.isEmpty()) { - cmrs.add(new ClassMutationResults(buffer)); - } - return cmrs; - - } - - private static Comparator comparator() { - return (arg0, arg1) -> arg0.getDetails().getId().compareTo(arg1.getDetails().getId()); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.mutations == null) ? 0 : this.mutations.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MutationMetaData other = (MutationMetaData) obj; - if (this.mutations == null) { - if (other.mutations != null) { - return false; - } - } else if (!this.mutations.equals(other.mutations)) { - return false; - } - return true; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.pitest.classinfo.ClassName; + +public final class MutationMetaData { + + private final List mutations; + + public MutationMetaData(final List mutations) { + this.mutations = mutations; + } + + public Collection getMutations() { + return this.mutations; + } + + public Collection toClassResults() { + Collections.sort(this.mutations, comparator()); + final List cmrs = new ArrayList<>(); + final List buffer = new ArrayList<>(); + ClassName cn = null; + for (final MutationResult each : this.mutations) { + if ((cn != null) && !each.getDetails().getClassName().equals(cn)) { + cmrs.add(new ClassMutationResults(buffer)); + buffer.clear(); + } + cn = each.getDetails().getClassName(); + buffer.add(each); + } + if (!buffer.isEmpty()) { + cmrs.add(new ClassMutationResults(buffer)); + } + return cmrs; + + } + + private static Comparator comparator() { + return (arg0, arg1) -> arg0.getDetails().getId().compareTo(arg1.getDetails().getId()); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.mutations == null) ? 0 : this.mutations.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MutationMetaData other = (MutationMetaData) obj; + if (this.mutations == null) { + if (other.mutations != null) { + return false; + } + } else if (!this.mutations.equals(other.mutations)) { + return false; + } + return true; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResult.java b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResult.java index 3e24afd36..169f4e5b9 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResult.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResult.java @@ -1,105 +1,105 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import java.util.Optional; -import org.pitest.mutationtest.engine.MutationDetails; - -public final class MutationResult { - - private final MutationDetails details; - private final MutationStatusTestPair status; - - public MutationResult(final MutationDetails md, - final MutationStatusTestPair status) { - this.details = md; - this.status = status; - } - - public MutationDetails getDetails() { - return this.details; - } - - public Optional getKillingTest() { - return this.status.getKillingTest(); - } - - public DetectionStatus getStatus() { - return this.status.getStatus(); - } - - public int getNumberOfTestsRun() { - return this.status.getNumberOfTestsRun(); - } - - public MutationStatusTestPair getStatusTestPair() { - return this.status; - } - - public String getStatusDescription() { - return getStatus().name(); - } - - public String getKillingTestDescription() { - return getKillingTest().orElse("none"); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.details == null) ? 0 : this.details.hashCode()); - result = (prime * result) - + ((this.status == null) ? 0 : this.status.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MutationResult other = (MutationResult) obj; - if (this.details == null) { - if (other.details != null) { - return false; - } - } else if (!this.details.equals(other.details)) { - return false; - } - if (this.status == null) { - if (other.status != null) { - return false; - } - } else if (!this.status.equals(other.status)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "MutationResult [details=" + this.details + ", status=" - + this.status + "]"; - } - +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import java.util.Optional; +import org.pitest.mutationtest.engine.MutationDetails; + +public final class MutationResult { + + private final MutationDetails details; + private final MutationStatusTestPair status; + + public MutationResult(final MutationDetails md, + final MutationStatusTestPair status) { + this.details = md; + this.status = status; + } + + public MutationDetails getDetails() { + return this.details; + } + + public Optional getKillingTest() { + return this.status.getKillingTest(); + } + + public DetectionStatus getStatus() { + return this.status.getStatus(); + } + + public int getNumberOfTestsRun() { + return this.status.getNumberOfTestsRun(); + } + + public MutationStatusTestPair getStatusTestPair() { + return this.status; + } + + public String getStatusDescription() { + return getStatus().name(); + } + + public String getKillingTestDescription() { + return getKillingTest().orElse("none"); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.details == null) ? 0 : this.details.hashCode()); + result = (prime * result) + + ((this.status == null) ? 0 : this.status.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MutationResult other = (MutationResult) obj; + if (this.details == null) { + if (other.details != null) { + return false; + } + } else if (!this.details.equals(other.details)) { + return false; + } + if (this.status == null) { + if (other.status != null) { + return false; + } + } else if (!this.status.equals(other.status)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "MutationResult [details=" + this.details + ", status=" + + this.status + "]"; + } + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResultListener.java b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResultListener.java index 7b60d6e18..6f10d4826 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResultListener.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResultListener.java @@ -1,11 +1,11 @@ -package org.pitest.mutationtest; - -public interface MutationResultListener { - - void runStart(); - - void handleMutationResult(ClassMutationResults results); - - void runEnd(); - -} +package org.pitest.mutationtest; + +public interface MutationResultListener { + + void runStart(); + + void handleMutationResult(ClassMutationResults results); + + void runEnd(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResultListenerFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResultListenerFactory.java index 4251c4364..4d068cbff 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResultListenerFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationResultListenerFactory.java @@ -1,28 +1,28 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest; - -import java.util.Properties; - -import org.pitest.plugin.ToolClasspathPlugin; - -public interface MutationResultListenerFactory extends ToolClasspathPlugin { - - MutationResultListener getListener(Properties props, ListenerArguments args); - - String name(); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest; + +import java.util.Properties; + +import org.pitest.plugin.ToolClasspathPlugin; + +public interface MutationResultListenerFactory extends ToolClasspathPlugin { + + MutationResultListener getListener(Properties props, ListenerArguments args); + + String name(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationStatusMap.java b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationStatusMap.java index 4dabebca8..46345d68d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/MutationStatusMap.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/MutationStatusMap.java @@ -1,105 +1,105 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import static org.pitest.functional.prelude.Prelude.putToMap; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.MutationDetails; - -public class MutationStatusMap { - - private final Map mutationMap = new HashMap<>(); - - public void setStatusForMutation(final MutationDetails mutation, - final DetectionStatus status) { - this.setStatusForMutations(Collections.singleton(mutation), status); - } - - public void setStatusForMutation(final MutationDetails mutation, - final MutationStatusTestPair status) { - this.mutationMap.put(mutation, status); - } - - public void setStatusForMutations( - final Collection mutations, final DetectionStatus status) { - FCollection.forEach(mutations, - putToMap(this.mutationMap, new MutationStatusTestPair(0, status))); - } - - public List createMutationResults() { - return FCollection.map(this.mutationMap.entrySet(), - detailsToMutationResults()); - - } - - public boolean hasUnrunMutations() { - return !getUnrunMutations().isEmpty(); - } - - public Collection getUnrunMutations() { - return this.mutationMap.entrySet().stream() - .filter(hasStatus(DetectionStatus.NOT_STARTED)) - .map(toMutationDetails()) - .collect(Collectors.toList()); - } - - public Collection getUnfinishedRuns() { - return this.mutationMap.entrySet().stream() - .filter(hasStatus(DetectionStatus.STARTED)) - .map(toMutationDetails()) - .collect(Collectors.toList()); - } - - public Set allMutations() { - return this.mutationMap.keySet(); - } - - private static Function, MutationResult> detailsToMutationResults() { - return a -> new MutationResult(a.getKey(), a.getValue()); - } - - private static Function, MutationDetails> toMutationDetails() { - return a -> a.getKey(); - } - - private static Predicate> hasStatus( - final DetectionStatus status) { - return a -> a.getValue().getStatus().equals(status); - } - - public void markUncoveredMutations() { - setStatusForMutations( - FCollection.filter(this.mutationMap.keySet(), hasNoCoverage()), - DetectionStatus.NO_COVERAGE); - - } - - private static Predicate hasNoCoverage() { - return a -> a.getTestsInOrder().isEmpty(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import static org.pitest.functional.prelude.Prelude.putToMap; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.MutationDetails; + +public class MutationStatusMap { + + private final Map mutationMap = new HashMap<>(); + + public void setStatusForMutation(final MutationDetails mutation, + final DetectionStatus status) { + this.setStatusForMutations(Collections.singleton(mutation), status); + } + + public void setStatusForMutation(final MutationDetails mutation, + final MutationStatusTestPair status) { + this.mutationMap.put(mutation, status); + } + + public void setStatusForMutations( + final Collection mutations, final DetectionStatus status) { + FCollection.forEach(mutations, + putToMap(this.mutationMap, new MutationStatusTestPair(0, status))); + } + + public List createMutationResults() { + return FCollection.map(this.mutationMap.entrySet(), + detailsToMutationResults()); + + } + + public boolean hasUnrunMutations() { + return !getUnrunMutations().isEmpty(); + } + + public Collection getUnrunMutations() { + return this.mutationMap.entrySet().stream() + .filter(hasStatus(DetectionStatus.NOT_STARTED)) + .map(toMutationDetails()) + .collect(Collectors.toList()); + } + + public Collection getUnfinishedRuns() { + return this.mutationMap.entrySet().stream() + .filter(hasStatus(DetectionStatus.STARTED)) + .map(toMutationDetails()) + .collect(Collectors.toList()); + } + + public Set allMutations() { + return this.mutationMap.keySet(); + } + + private static Function, MutationResult> detailsToMutationResults() { + return a -> new MutationResult(a.getKey(), a.getValue()); + } + + private static Function, MutationDetails> toMutationDetails() { + return a -> a.getKey(); + } + + private static Predicate> hasStatus( + final DetectionStatus status) { + return a -> a.getValue().getStatus().equals(status); + } + + public void markUncoveredMutations() { + setStatusForMutations( + FCollection.filter(this.mutationMap.keySet(), hasNoCoverage()), + DetectionStatus.NO_COVERAGE); + + } + + private static Predicate hasNoCoverage() { + return a -> a.getTestsInOrder().isEmpty(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/SourceLocator.java b/pitest-entry/src/main/java/org/pitest/mutationtest/SourceLocator.java index c185f9066..ccc74fb8d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/SourceLocator.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/SourceLocator.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import java.io.Reader; -import java.util.Collection; - -import java.util.Optional; - -public interface SourceLocator { - Optional locate(Collection classes, String fileName); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import java.io.Reader; +import java.util.Collection; + +import java.util.Optional; + +public interface SourceLocator { + Optional locate(Collection classes, String fileName); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/AnalysisPriorityComparator.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/AnalysisPriorityComparator.java index 15ab0ce74..44842a4a0 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/AnalysisPriorityComparator.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/AnalysisPriorityComparator.java @@ -1,24 +1,24 @@ -package org.pitest.mutationtest.build; - -import java.io.Serializable; -import java.util.Comparator; - -/** - * Comparator to prioritise the order of mutation analysis units. - * - * The ones with the most mutations are run first. This should make it less - * likely that a single thread remains running at the of a run because it has - * just picked up a large unit. - * - */ -class AnalysisPriorityComparator implements Comparator, -Serializable { - - private static final long serialVersionUID = 1L; - - @Override - public int compare(final MutationAnalysisUnit a, final MutationAnalysisUnit b) { - return b.priority() - a.priority(); - } - -} +package org.pitest.mutationtest.build; + +import java.io.Serializable; +import java.util.Comparator; + +/** + * Comparator to prioritise the order of mutation analysis units. + * + * The ones with the most mutations are run first. This should make it less + * likely that a single thread remains running at the of a run because it has + * just picked up a large unit. + * + */ +class AnalysisPriorityComparator implements Comparator, +Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(final MutationAnalysisUnit a, final MutationAnalysisUnit b) { + return b.priority() - a.priority(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/CompoundInterceptorFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/CompoundInterceptorFactory.java index 463b2c8bc..930ba5125 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/CompoundInterceptorFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/CompoundInterceptorFactory.java @@ -1,37 +1,37 @@ -package org.pitest.mutationtest.build; - -import java.util.Collection; -import java.util.List; -import java.util.function.Function; - -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.plugin.FeatureSelector; -import org.pitest.plugin.FeatureSetting; - -public class CompoundInterceptorFactory { - - private final FeatureSelector features; - - public CompoundInterceptorFactory(List features, - Collection filters) { - this.features = new FeatureSelector<>(features, filters); - } - - public MutationInterceptor createInterceptor( - ReportOptions data, - ClassByteArraySource source) { - final List interceptors = FCollection.map(this.features.getActiveFeatures(), - toInterceptor(this.features, data, source)); - return new CompoundMutationInterceptor(interceptors); - } - - - private static Function toInterceptor( - final FeatureSelector features, final ReportOptions data, final ClassByteArraySource source) { - - return a -> a.createInterceptor(new InterceptorParameters(features.getSettingForFeature(a.provides().name()), data, source)); - - } +package org.pitest.mutationtest.build; + +import java.util.Collection; +import java.util.List; +import java.util.function.Function; + +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.plugin.FeatureSelector; +import org.pitest.plugin.FeatureSetting; + +public class CompoundInterceptorFactory { + + private final FeatureSelector features; + + public CompoundInterceptorFactory(List features, + Collection filters) { + this.features = new FeatureSelector<>(features, filters); + } + + public MutationInterceptor createInterceptor( + ReportOptions data, + ClassByteArraySource source) { + final List interceptors = FCollection.map(this.features.getActiveFeatures(), + toInterceptor(this.features, data, source)); + return new CompoundMutationInterceptor(interceptors); + } + + + private static Function toInterceptor( + final FeatureSelector features, final ReportOptions data, final ClassByteArraySource source) { + + return a -> a.createInterceptor(new InterceptorParameters(features.getSettingForFeature(a.provides().name()), data, source)); + + } } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/CompoundMutationInterceptor.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/CompoundMutationInterceptor.java index 06938f6b6..1185ca6ea 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/CompoundMutationInterceptor.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/CompoundMutationInterceptor.java @@ -1,59 +1,59 @@ -package org.pitest.mutationtest.build; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -public class CompoundMutationInterceptor implements MutationInterceptor { - - private final List children = new ArrayList<>(); - - public CompoundMutationInterceptor(List interceptors) { - this.children.addAll(interceptors); - Collections.sort(this.children, sortByType()); - } - - public static MutationInterceptor nullInterceptor() { - return new CompoundMutationInterceptor(Collections.emptyList()); - } - - @Override - public void begin(ClassTree clazz) { - for (final MutationInterceptor each : this.children) { - each.begin(clazz); - } - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - Collection modified = mutations; - for (final MutationInterceptor each : this.children) { - modified = each.intercept(modified, m); - } - return modified; - } - - @Override - public void end() { - for (final MutationInterceptor each : this.children) { - each.end(); - } - } - - @Override - public InterceptorType type() { - return InterceptorType.OTHER; - } - - private static Comparator sortByType() { - return (o1, o2) -> o1.type().compareTo(o2.type()); - } - -} +package org.pitest.mutationtest.build; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +public class CompoundMutationInterceptor implements MutationInterceptor { + + private final List children = new ArrayList<>(); + + public CompoundMutationInterceptor(List interceptors) { + this.children.addAll(interceptors); + Collections.sort(this.children, sortByType()); + } + + public static MutationInterceptor nullInterceptor() { + return new CompoundMutationInterceptor(Collections.emptyList()); + } + + @Override + public void begin(ClassTree clazz) { + for (final MutationInterceptor each : this.children) { + each.begin(clazz); + } + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + Collection modified = mutations; + for (final MutationInterceptor each : this.children) { + modified = each.intercept(modified, m); + } + return modified; + } + + @Override + public void end() { + for (final MutationInterceptor each : this.children) { + each.end(); + } + } + + @Override + public InterceptorType type() { + return InterceptorType.OTHER; + } + + private static Comparator sortByType() { + return (o1, o2) -> o1.type().compareTo(o2.type()); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultGrouper.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultGrouper.java index db5b332db..b25656b75 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultGrouper.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultGrouper.java @@ -1,52 +1,52 @@ -package org.pitest.mutationtest.build; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - -import org.pitest.classinfo.ClassName; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.MutationDetails; - -public class DefaultGrouper implements MutationGrouper { - - private final int unitSize; - - public DefaultGrouper(final int unitSize) { - this.unitSize = unitSize; - } - - @Override - public List> groupMutations( - final Collection codeClasses, - final Collection mutations) { - final Map> bucketed = FCollection - .bucket(mutations, byClass()); - final List> chunked = new ArrayList<>(); - for (final Collection each : bucketed.values()) { - shrinkToMaximumUnitSize(chunked, each); - } - - return chunked; - } - - private void shrinkToMaximumUnitSize( - final List> chunked, - final Collection each) { - if (this.unitSize > 0) { - for (final List ms : FCollection.splitToLength( - this.unitSize, each)) { - chunked.add(ms); - } - } else { - chunked.add(new ArrayList<>(each)); - } - } - - private static Function byClass() { - return a -> a.getClassName(); - } - -} +package org.pitest.mutationtest.build; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import org.pitest.classinfo.ClassName; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.MutationDetails; + +public class DefaultGrouper implements MutationGrouper { + + private final int unitSize; + + public DefaultGrouper(final int unitSize) { + this.unitSize = unitSize; + } + + @Override + public List> groupMutations( + final Collection codeClasses, + final Collection mutations) { + final Map> bucketed = FCollection + .bucket(mutations, byClass()); + final List> chunked = new ArrayList<>(); + for (final Collection each : bucketed.values()) { + shrinkToMaximumUnitSize(chunked, each); + } + + return chunked; + } + + private void shrinkToMaximumUnitSize( + final List> chunked, + final Collection each) { + if (this.unitSize > 0) { + for (final List ms : FCollection.splitToLength( + this.unitSize, each)) { + chunked.add(ms); + } + } else { + chunked.add(new ArrayList<>(each)); + } + } + + private static Function byClass() { + return a -> a.getClassName(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultMutationGrouperFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultMutationGrouperFactory.java index 123c23ad8..43cb68813 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultMutationGrouperFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultMutationGrouperFactory.java @@ -1,20 +1,20 @@ -package org.pitest.mutationtest.build; - -import java.util.Properties; - -import org.pitest.classpath.CodeSource; - -public class DefaultMutationGrouperFactory implements MutationGrouperFactory { - - @Override - public String description() { - return "Default mutation grouping"; - } - - @Override - public MutationGrouper makeFactory(final Properties props, - final CodeSource codeSource, final int numberOfThreads, final int unitSize) { - return new DefaultGrouper(unitSize); - } - -} +package org.pitest.mutationtest.build; + +import java.util.Properties; + +import org.pitest.classpath.CodeSource; + +public class DefaultMutationGrouperFactory implements MutationGrouperFactory { + + @Override + public String description() { + return "Default mutation grouping"; + } + + @Override + public MutationGrouper makeFactory(final Properties props, + final CodeSource codeSource, final int numberOfThreads, final int unitSize) { + return new DefaultGrouper(unitSize); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultTestPrioritiser.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultTestPrioritiser.java index cccd10c3f..f4ccee1c9 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultTestPrioritiser.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultTestPrioritiser.java @@ -1,60 +1,60 @@ -package org.pitest.mutationtest.build; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.logging.Logger; - -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.coverage.TestInfo; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.util.Log; - -/** - * Assigns tests based on line coverage and order them by execution speed with a - * weighting towards tests whose names imply they are intended to test the - * mutated class - * - * @author henry - * - */ -public class DefaultTestPrioritiser implements TestPrioritiser { - - private static final Logger LOG = Log - .getLogger(); - - private static final int TIME_WEIGHTING_FOR_DIRECT_UNIT_TESTS = 1000; - - private final CoverageDatabase coverage; - - public DefaultTestPrioritiser(CoverageDatabase coverage) { - this.coverage = coverage; - } - - @Override - public List assignTests(MutationDetails mutation) { - return prioritizeTests(mutation.getClassName(), pickTests(mutation)); - } - - private Collection pickTests(MutationDetails mutation) { - if (!mutation.isInStaticInitializer()) { - return this.coverage.getTestsForClassLine(mutation.getClassLine()); - } else { - LOG.warning("Using untargetted tests"); - return this.coverage.getTestsForClass(mutation.getClassName()); - } - } - - private List prioritizeTests(ClassName clazz, - Collection testsForMutant) { - final List sortedTis = FCollection.map(testsForMutant, - Prelude.id(TestInfo.class)); - Collections.sort(sortedTis, new TestInfoPriorisationComparator(clazz, - TIME_WEIGHTING_FOR_DIRECT_UNIT_TESTS)); - return sortedTis; - } - -} +package org.pitest.mutationtest.build; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.logging.Logger; + +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.coverage.TestInfo; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.util.Log; + +/** + * Assigns tests based on line coverage and order them by execution speed with a + * weighting towards tests whose names imply they are intended to test the + * mutated class + * + * @author henry + * + */ +public class DefaultTestPrioritiser implements TestPrioritiser { + + private static final Logger LOG = Log + .getLogger(); + + private static final int TIME_WEIGHTING_FOR_DIRECT_UNIT_TESTS = 1000; + + private final CoverageDatabase coverage; + + public DefaultTestPrioritiser(CoverageDatabase coverage) { + this.coverage = coverage; + } + + @Override + public List assignTests(MutationDetails mutation) { + return prioritizeTests(mutation.getClassName(), pickTests(mutation)); + } + + private Collection pickTests(MutationDetails mutation) { + if (!mutation.isInStaticInitializer()) { + return this.coverage.getTestsForClassLine(mutation.getClassLine()); + } else { + LOG.warning("Using untargetted tests"); + return this.coverage.getTestsForClass(mutation.getClassName()); + } + } + + private List prioritizeTests(ClassName clazz, + Collection testsForMutant) { + final List sortedTis = FCollection.map(testsForMutant, + Prelude.id(TestInfo.class)); + Collections.sort(sortedTis, new TestInfoPriorisationComparator(clazz, + TIME_WEIGHTING_FOR_DIRECT_UNIT_TESTS)); + return sortedTis; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultTestPrioritiserFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultTestPrioritiserFactory.java index 1e49eb107..97c91d493 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultTestPrioritiserFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/DefaultTestPrioritiserFactory.java @@ -1,21 +1,21 @@ -package org.pitest.mutationtest.build; - -import java.util.Properties; - -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.CoverageDatabase; - -public class DefaultTestPrioritiserFactory implements TestPrioritiserFactory { - - @Override - public String description() { - return "Default test prioritiser"; - } - - @Override - public TestPrioritiser makeTestPrioritiser(final Properties props, - final CodeSource code, final CoverageDatabase coverage) { - return new DefaultTestPrioritiser(coverage); - } - -} +package org.pitest.mutationtest.build; + +import java.util.Properties; + +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.CoverageDatabase; + +public class DefaultTestPrioritiserFactory implements TestPrioritiserFactory { + + @Override + public String description() { + return "Default test prioritiser"; + } + + @Override + public TestPrioritiser makeTestPrioritiser(final Properties props, + final CodeSource code, final CoverageDatabase coverage) { + return new DefaultTestPrioritiser(coverage); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/InterceptorParameters.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/InterceptorParameters.java index a39a7b737..c4b213ad2 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/InterceptorParameters.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/InterceptorParameters.java @@ -1,61 +1,61 @@ -package org.pitest.mutationtest.build; - -import java.util.Collections; -import java.util.List; - -import org.pitest.classinfo.ClassByteArraySource; -import java.util.Optional; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.plugin.FeatureParameter; -import org.pitest.plugin.FeatureSetting; - -public final class InterceptorParameters { - - private final FeatureSetting conf; - private final ReportOptions data; - private final ClassByteArraySource source; - - - public InterceptorParameters(FeatureSetting conf, ReportOptions data, - ClassByteArraySource source) { - this.conf = conf; - this.data = data; - this.source = source; - } - - public ReportOptions data() { - return this.data; - } - - public Optional settings() { - return Optional.ofNullable(this.conf); - } - - - public ClassByteArraySource source() { - return this.source; - } - - public Optional getString(FeatureParameter limit) { - if (this.conf == null) { - return Optional.empty(); - } - return this.conf.getString(limit.name()); - } - - public List getList(FeatureParameter key) { - if (this.conf == null) { - return Collections.emptyList(); - } - return this.conf.getList(key.name()); - } - - public Optional getInteger(FeatureParameter key) { - final Optional val = getString(key); - if (val.isPresent()) { - return Optional.ofNullable(Integer.parseInt(val.get())); - } - return Optional.empty(); - } - -} +package org.pitest.mutationtest.build; + +import java.util.Collections; +import java.util.List; + +import org.pitest.classinfo.ClassByteArraySource; +import java.util.Optional; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.plugin.FeatureParameter; +import org.pitest.plugin.FeatureSetting; + +public final class InterceptorParameters { + + private final FeatureSetting conf; + private final ReportOptions data; + private final ClassByteArraySource source; + + + public InterceptorParameters(FeatureSetting conf, ReportOptions data, + ClassByteArraySource source) { + this.conf = conf; + this.data = data; + this.source = source; + } + + public ReportOptions data() { + return this.data; + } + + public Optional settings() { + return Optional.ofNullable(this.conf); + } + + + public ClassByteArraySource source() { + return this.source; + } + + public Optional getString(FeatureParameter limit) { + if (this.conf == null) { + return Optional.empty(); + } + return this.conf.getString(limit.name()); + } + + public List getList(FeatureParameter key) { + if (this.conf == null) { + return Collections.emptyList(); + } + return this.conf.getList(key.name()); + } + + public Optional getInteger(FeatureParameter key) { + final Optional val = getString(key); + if (val.isPresent()) { + return Optional.ofNullable(Integer.parseInt(val.get())); + } + return Optional.empty(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/InterceptorType.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/InterceptorType.java index 4611863ef..8bae761bf 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/InterceptorType.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/InterceptorType.java @@ -1,18 +1,18 @@ -package org.pitest.mutationtest.build; - -/** - * Used to group interceptors. Running order of groups - * is guaranteed (by order within group is not). - * - * The name indicates the intended typees of behaviour - but this is not enforced. - * - * OTHER - - * MODIFY - Modify mutants in a way that is functionally significant (e.g mark as poisoning JVM) - * FILTER - Remove mutants from processing - * MODIFY_COSMETIC - Modify mutants in way that will not affect processing (e.g update descriptions) - * REPORT - Output mutant in their final state - * - */ -public enum InterceptorType { - OTHER, MODIFY, FILTER, MODIFY_COSMETIC, REPORT -} +package org.pitest.mutationtest.build; + +/** + * Used to group interceptors. Running order of groups + * is guaranteed (by order within group is not). + * + * The name indicates the intended typees of behaviour - but this is not enforced. + * + * OTHER - + * MODIFY - Modify mutants in a way that is functionally significant (e.g mark as poisoning JVM) + * FILTER - Remove mutants from processing + * MODIFY_COSMETIC - Modify mutants in way that will not affect processing (e.g update descriptions) + * REPORT - Output mutant in their final state + * + */ +public enum InterceptorType { + OTHER, MODIFY, FILTER, MODIFY_COSMETIC, REPORT +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/KnownStatusMutationTestUnit.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/KnownStatusMutationTestUnit.java index 6fb624ca7..ff6012dda 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/KnownStatusMutationTestUnit.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/KnownStatusMutationTestUnit.java @@ -1,33 +1,33 @@ -package org.pitest.mutationtest.build; - -import java.util.List; -import java.util.logging.Logger; - -import org.pitest.mutationtest.MutationMetaData; -import org.pitest.mutationtest.MutationResult; -import org.pitest.util.Log; - -public class KnownStatusMutationTestUnit implements MutationAnalysisUnit { - - private static final Logger LOG = Log.getLogger(); - - private final List mutations; - - public KnownStatusMutationTestUnit(final List mutations) { - this.mutations = mutations; - } - - @Override - public MutationMetaData call() throws Exception { - LOG.fine("Using historic results for " + this.mutations.size() - + " mutations"); - return new MutationMetaData(this.mutations); - - } - - @Override - public int priority() { - return Integer.MAX_VALUE; - } - -} +package org.pitest.mutationtest.build; + +import java.util.List; +import java.util.logging.Logger; + +import org.pitest.mutationtest.MutationMetaData; +import org.pitest.mutationtest.MutationResult; +import org.pitest.util.Log; + +public class KnownStatusMutationTestUnit implements MutationAnalysisUnit { + + private static final Logger LOG = Log.getLogger(); + + private final List mutations; + + public KnownStatusMutationTestUnit(final List mutations) { + this.mutations = mutations; + } + + @Override + public MutationMetaData call() throws Exception { + LOG.fine("Using historic results for " + this.mutations.size() + + " mutations"); + return new MutationMetaData(this.mutations); + + } + + @Override + public int priority() { + return Integer.MAX_VALUE; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationAnalysisUnit.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationAnalysisUnit.java index 84ce45e9f..bc9ff87ef 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationAnalysisUnit.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationAnalysisUnit.java @@ -1,14 +1,14 @@ -package org.pitest.mutationtest.build; - -import java.util.concurrent.Callable; - -import org.pitest.mutationtest.MutationMetaData; - -/** - * A unit of mutation analysis - */ -public interface MutationAnalysisUnit extends Callable { - - int priority(); - -} +package org.pitest.mutationtest.build; + +import java.util.concurrent.Callable; + +import org.pitest.mutationtest.MutationMetaData; + +/** + * A unit of mutation analysis + */ +public interface MutationAnalysisUnit extends Callable { + + int priority(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationGrouper.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationGrouper.java index fc49c379e..60a3125ab 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationGrouper.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationGrouper.java @@ -1,14 +1,14 @@ -package org.pitest.mutationtest.build; - -import java.util.Collection; -import java.util.List; - -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.MutationDetails; - -public interface MutationGrouper { - - List> groupMutations(Collection codeClasses, - Collection mutations); - -} +package org.pitest.mutationtest.build; + +import java.util.Collection; +import java.util.List; + +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.MutationDetails; + +public interface MutationGrouper { + + List> groupMutations(Collection codeClasses, + Collection mutations); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationGrouperFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationGrouperFactory.java index 506917ef1..7bccf1204 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationGrouperFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationGrouperFactory.java @@ -1,12 +1,12 @@ -package org.pitest.mutationtest.build; - -import java.util.Properties; - -import org.pitest.classpath.CodeSource; -import org.pitest.plugin.ToolClasspathPlugin; - -public interface MutationGrouperFactory extends ToolClasspathPlugin { - - MutationGrouper makeFactory(Properties props, CodeSource codeSource, - int numberOfThreads, int unitSize); -} +package org.pitest.mutationtest.build; + +import java.util.Properties; + +import org.pitest.classpath.CodeSource; +import org.pitest.plugin.ToolClasspathPlugin; + +public interface MutationGrouperFactory extends ToolClasspathPlugin { + + MutationGrouper makeFactory(Properties props, CodeSource codeSource, + int numberOfThreads, int unitSize); +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationInterceptor.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationInterceptor.java index bbfe0bba7..e2b4632cf 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationInterceptor.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationInterceptor.java @@ -1,19 +1,19 @@ -package org.pitest.mutationtest.build; - -import java.util.Collection; - -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -public interface MutationInterceptor { - - InterceptorType type(); - - void begin(ClassTree clazz); - - Collection intercept(Collection mutations, Mutater m); - - void end(); - -} +package org.pitest.mutationtest.build; + +import java.util.Collection; + +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +public interface MutationInterceptor { + + InterceptorType type(); + + void begin(ClassTree clazz); + + Collection intercept(Collection mutations, Mutater m); + + void end(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationInterceptorFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationInterceptorFactory.java index 85ea6d4ee..6c15fb55d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationInterceptorFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationInterceptorFactory.java @@ -1,10 +1,10 @@ -package org.pitest.mutationtest.build; - -import org.pitest.plugin.ProvidesFeature; -import org.pitest.plugin.ToolClasspathPlugin; - -public interface MutationInterceptorFactory extends ToolClasspathPlugin, ProvidesFeature { - - MutationInterceptor createInterceptor(InterceptorParameters params); - -} +package org.pitest.mutationtest.build; + +import org.pitest.plugin.ProvidesFeature; +import org.pitest.plugin.ToolClasspathPlugin; + +public interface MutationInterceptorFactory extends ToolClasspathPlugin, ProvidesFeature { + + MutationInterceptor createInterceptor(InterceptorParameters params); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationSource.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationSource.java index 4bccdaec1..606f0795a 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationSource.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationSource.java @@ -1,86 +1,86 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.build; - -import java.util.Collection; -import java.util.List; -import java.util.logging.Logger; - -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.classinfo.CachingByteArraySource; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.TestInfo; -import org.pitest.mutationtest.MutationConfig; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.util.Log; - -public class MutationSource { - - private static final Logger LOG = Log.getLogger(); - - private final MutationConfig mutationConfig; - private final TestPrioritiser testPrioritiser; - private final ClassByteArraySource source; - private final MutationInterceptor interceptor; - - public MutationSource(final MutationConfig mutationConfig, - final TestPrioritiser testPrioritiser, - final ClassByteArraySource source, - final MutationInterceptor interceptor) { - this.mutationConfig = mutationConfig; - this.testPrioritiser = testPrioritiser; - this.source = new CachingByteArraySource(source, 200); - this.interceptor = interceptor; - } - - public Collection createMutations(final ClassName clazz) { - - final Mutater m = this.mutationConfig.createMutator(this.source); - - final Collection availableMutations = m - .findMutations(clazz); - - if (availableMutations.isEmpty()) { - return availableMutations; - } else { - final ClassTree tree = ClassTree - .fromBytes(this.source.getBytes(clazz.asJavaName()).get()); - - this.interceptor.begin(tree); - final Collection updatedMutations = this.interceptor - .intercept(availableMutations, m); - this.interceptor.end(); - - assignTestsToMutations(updatedMutations); - - return updatedMutations; - } - } - - private void assignTestsToMutations( - final Collection availableMutations) { - for (final MutationDetails mutation : availableMutations) { - final List testDetails = this.testPrioritiser - .assignTests(mutation); - if (testDetails.isEmpty()) { - LOG.fine("According to coverage no tests hit the mutation " + mutation); - } - mutation.addTestsInOrder(testDetails); - } - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.build; + +import java.util.Collection; +import java.util.List; +import java.util.logging.Logger; + +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.classinfo.CachingByteArraySource; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.TestInfo; +import org.pitest.mutationtest.MutationConfig; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.util.Log; + +public class MutationSource { + + private static final Logger LOG = Log.getLogger(); + + private final MutationConfig mutationConfig; + private final TestPrioritiser testPrioritiser; + private final ClassByteArraySource source; + private final MutationInterceptor interceptor; + + public MutationSource(final MutationConfig mutationConfig, + final TestPrioritiser testPrioritiser, + final ClassByteArraySource source, + final MutationInterceptor interceptor) { + this.mutationConfig = mutationConfig; + this.testPrioritiser = testPrioritiser; + this.source = new CachingByteArraySource(source, 200); + this.interceptor = interceptor; + } + + public Collection createMutations(final ClassName clazz) { + + final Mutater m = this.mutationConfig.createMutator(this.source); + + final Collection availableMutations = m + .findMutations(clazz); + + if (availableMutations.isEmpty()) { + return availableMutations; + } else { + final ClassTree tree = ClassTree + .fromBytes(this.source.getBytes(clazz.asJavaName()).get()); + + this.interceptor.begin(tree); + final Collection updatedMutations = this.interceptor + .intercept(availableMutations, m); + this.interceptor.end(); + + assignTestsToMutations(updatedMutations); + + return updatedMutations; + } + } + + private void assignTestsToMutations( + final Collection availableMutations) { + for (final MutationDetails mutation : availableMutations) { + final List testDetails = this.testPrioritiser + .assignTests(mutation); + if (testDetails.isEmpty()) { + LOG.fine("According to coverage no tests hit the mutation " + mutation); + } + mutation.addTestsInOrder(testDetails); + } + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationTestBuilder.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationTestBuilder.java index e341a084c..439edd390 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationTestBuilder.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/MutationTestBuilder.java @@ -1,125 +1,125 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.build; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.TestInfo; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationAnalyser; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.engine.MutationDetails; - -public class MutationTestBuilder { - - private final MutationSource mutationSource; - private final MutationAnalyser analyser; - private final WorkerFactory workerFactory; - private final MutationGrouper grouper; - - public MutationTestBuilder(final WorkerFactory workerFactory, - final MutationAnalyser analyser, final MutationSource mutationSource, - final MutationGrouper grouper) { - - this.mutationSource = mutationSource; - this.analyser = analyser; - this.workerFactory = workerFactory; - this.grouper = grouper; - } - - public List createMutationTestUnits( - final Collection codeClasses) { - final List tus = new ArrayList<>(); - - final List mutations = FCollection.flatMap(codeClasses, - classToMutations()); - - Collections.sort(mutations, comparator()); - - final Collection analysedMutations = this.analyser - .analyse(mutations); - - final Collection needAnalysis = analysedMutations.stream() - .filter(statusNotKnown()) - .map(resultToDetails()) - .collect(Collectors.toList()); - - final List analysed = FCollection.filter(analysedMutations, - Prelude.not(statusNotKnown())); - - if (!analysed.isEmpty()) { - tus.add(makePreAnalysedUnit(analysed)); - } - - if (!needAnalysis.isEmpty()) { - for (final Collection ms : this.grouper.groupMutations( - codeClasses, needAnalysis)) { - tus.add(makeUnanalysedUnit(ms)); - } - } - - Collections.sort(tus, new AnalysisPriorityComparator()); - return tus; - } - - private Comparator comparator() { - return (arg0, arg1) -> arg0.getId().compareTo(arg1.getId()); - } - - private Function> classToMutations() { - return a -> MutationTestBuilder.this.mutationSource.createMutations(a); - } - - private MutationAnalysisUnit makePreAnalysedUnit( - final List analysed) { - return new KnownStatusMutationTestUnit(analysed); - } - - private MutationAnalysisUnit makeUnanalysedUnit( - final Collection needAnalysis) { - final Set uniqueTestClasses = new HashSet<>(); - FCollection.flatMapTo(needAnalysis, mutationDetailsToTestClass(), - uniqueTestClasses); - - return new MutationTestUnit(needAnalysis, uniqueTestClasses, - this.workerFactory); - } - - private static Function resultToDetails() { - return a -> a.getDetails(); - } - - private static Predicate statusNotKnown() { - return a -> a.getStatus() == DetectionStatus.NOT_STARTED; - } - - private static Function> mutationDetailsToTestClass() { - return a -> FCollection.map(a.getTestsInOrder(), - TestInfo.toDefiningClassName()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.build; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.TestInfo; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationAnalyser; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.engine.MutationDetails; + +public class MutationTestBuilder { + + private final MutationSource mutationSource; + private final MutationAnalyser analyser; + private final WorkerFactory workerFactory; + private final MutationGrouper grouper; + + public MutationTestBuilder(final WorkerFactory workerFactory, + final MutationAnalyser analyser, final MutationSource mutationSource, + final MutationGrouper grouper) { + + this.mutationSource = mutationSource; + this.analyser = analyser; + this.workerFactory = workerFactory; + this.grouper = grouper; + } + + public List createMutationTestUnits( + final Collection codeClasses) { + final List tus = new ArrayList<>(); + + final List mutations = FCollection.flatMap(codeClasses, + classToMutations()); + + Collections.sort(mutations, comparator()); + + final Collection analysedMutations = this.analyser + .analyse(mutations); + + final Collection needAnalysis = analysedMutations.stream() + .filter(statusNotKnown()) + .map(resultToDetails()) + .collect(Collectors.toList()); + + final List analysed = FCollection.filter(analysedMutations, + Prelude.not(statusNotKnown())); + + if (!analysed.isEmpty()) { + tus.add(makePreAnalysedUnit(analysed)); + } + + if (!needAnalysis.isEmpty()) { + for (final Collection ms : this.grouper.groupMutations( + codeClasses, needAnalysis)) { + tus.add(makeUnanalysedUnit(ms)); + } + } + + Collections.sort(tus, new AnalysisPriorityComparator()); + return tus; + } + + private Comparator comparator() { + return (arg0, arg1) -> arg0.getId().compareTo(arg1.getId()); + } + + private Function> classToMutations() { + return a -> MutationTestBuilder.this.mutationSource.createMutations(a); + } + + private MutationAnalysisUnit makePreAnalysedUnit( + final List analysed) { + return new KnownStatusMutationTestUnit(analysed); + } + + private MutationAnalysisUnit makeUnanalysedUnit( + final Collection needAnalysis) { + final Set uniqueTestClasses = new HashSet<>(); + FCollection.flatMapTo(needAnalysis, mutationDetailsToTestClass(), + uniqueTestClasses); + + return new MutationTestUnit(needAnalysis, uniqueTestClasses, + this.workerFactory); + } + + private static Function resultToDetails() { + return a -> a.getDetails(); + } + + private static Predicate statusNotKnown() { + return a -> a.getStatus() == DetectionStatus.NOT_STARTED; + } + + private static Function> mutationDetailsToTestClass() { + return a -> FCollection.map(a.getTestsInOrder(), + TestInfo.toDefiningClassName()); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestInfoPriorisationComparator.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestInfoPriorisationComparator.java index 95539e6ef..a1afd33e9 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestInfoPriorisationComparator.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestInfoPriorisationComparator.java @@ -1,56 +1,56 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.build; - -import java.io.Serializable; -import java.util.Comparator; - -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.TestInfo; - -public class TestInfoPriorisationComparator implements Comparator, -Serializable { - - private static final long serialVersionUID = 1L; - - private final int distanceTimeWeighting; - private final ClassName targetClass; - - public TestInfoPriorisationComparator(final ClassName targetClass, - final int distanceTimeWeighting) { - this.targetClass = targetClass; - this.distanceTimeWeighting = distanceTimeWeighting; - } - - @Override - public int compare(final TestInfo arg0, final TestInfo arg1) { - final int t0 = arg0.getTime(); - final int t1 = arg1.getTime(); - return t0 - t1 - distanceWeighting(arg0, arg1); - } - - private int distanceWeighting(final TestInfo arg0, final TestInfo arg1) { - return weightFor(arg0) - weightFor(arg1); - } - - private int weightFor(final TestInfo ti) { - return weightForDirectHit(ti) - (ti.getNumberOfBlocksCovered() / 10); - } - - private int weightForDirectHit(final TestInfo arg0) { - return arg0.directlyHits(this.targetClass) ? this.distanceTimeWeighting : 0; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.build; + +import java.io.Serializable; +import java.util.Comparator; + +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.TestInfo; + +public class TestInfoPriorisationComparator implements Comparator, +Serializable { + + private static final long serialVersionUID = 1L; + + private final int distanceTimeWeighting; + private final ClassName targetClass; + + public TestInfoPriorisationComparator(final ClassName targetClass, + final int distanceTimeWeighting) { + this.targetClass = targetClass; + this.distanceTimeWeighting = distanceTimeWeighting; + } + + @Override + public int compare(final TestInfo arg0, final TestInfo arg1) { + final int t0 = arg0.getTime(); + final int t1 = arg1.getTime(); + return t0 - t1 - distanceWeighting(arg0, arg1); + } + + private int distanceWeighting(final TestInfo arg0, final TestInfo arg1) { + return weightFor(arg0) - weightFor(arg1); + } + + private int weightFor(final TestInfo ti) { + return weightForDirectHit(ti) - (ti.getNumberOfBlocksCovered() / 10); + } + + private int weightForDirectHit(final TestInfo arg0) { + return arg0.directlyHits(this.targetClass) ? this.distanceTimeWeighting : 0; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestPrioritiser.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestPrioritiser.java index 82cc0f84f..a30177252 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestPrioritiser.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestPrioritiser.java @@ -1,18 +1,18 @@ -package org.pitest.mutationtest.build; - -import java.util.List; - -import org.pitest.coverage.TestInfo; -import org.pitest.mutationtest.engine.MutationDetails; - -public interface TestPrioritiser { - - /** - * - * @param mutation - * Mutation to assign tests to - * @return List of tests to run against mutant in priority order - */ - List assignTests(MutationDetails mutation); - -} +package org.pitest.mutationtest.build; + +import java.util.List; + +import org.pitest.coverage.TestInfo; +import org.pitest.mutationtest.engine.MutationDetails; + +public interface TestPrioritiser { + + /** + * + * @param mutation + * Mutation to assign tests to + * @return List of tests to run against mutant in priority order + */ + List assignTests(MutationDetails mutation); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestPrioritiserFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestPrioritiserFactory.java index b97711bb1..920ae0e9f 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestPrioritiserFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/TestPrioritiserFactory.java @@ -1,14 +1,14 @@ -package org.pitest.mutationtest.build; - -import java.util.Properties; - -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.plugin.ToolClasspathPlugin; - -public interface TestPrioritiserFactory extends ToolClasspathPlugin { - - TestPrioritiser makeTestPrioritiser(Properties props, CodeSource code, - CoverageDatabase coverage); - -} +package org.pitest.mutationtest.build; + +import java.util.Properties; + +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.plugin.ToolClasspathPlugin; + +public interface TestPrioritiserFactory extends ToolClasspathPlugin { + + TestPrioritiser makeTestPrioritiser(Properties props, CodeSource code, + CoverageDatabase coverage); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/WorkerFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/WorkerFactory.java index d57f43376..8435864a9 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/WorkerFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/WorkerFactory.java @@ -1,75 +1,75 @@ -package org.pitest.mutationtest.build; - -import static org.pitest.functional.prelude.Prelude.printWith; - -import java.io.File; -import java.util.Collection; - -import org.pitest.classinfo.ClassName; -import org.pitest.functional.SideEffect1; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.EngineArguments; -import org.pitest.mutationtest.MutationConfig; -import org.pitest.mutationtest.TimeoutLengthStrategy; -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.execute.MinionArguments; -import org.pitest.mutationtest.execute.MutationTestProcess; -import org.pitest.process.ProcessArgs; -import org.pitest.util.Log; -import org.pitest.util.SocketFinder; - -public class WorkerFactory { - - private final String classPath; - private final File baseDir; - private final TestPluginArguments pitConfig; - private final TimeoutLengthStrategy timeoutStrategy; - private final boolean verbose; - private final MutationConfig config; - private final EngineArguments args; - - public WorkerFactory(final File baseDir, - final TestPluginArguments pitConfig, - final MutationConfig mutationConfig, - final EngineArguments args, - final TimeoutLengthStrategy timeoutStrategy, - final boolean verbose, - final String classPath) { - this.pitConfig = pitConfig; - this.timeoutStrategy = timeoutStrategy; - this.verbose = verbose; - this.classPath = classPath; - this.baseDir = baseDir; - this.config = mutationConfig; - this.args = args; - } - - public MutationTestProcess createWorker( - final Collection remainingMutations, - final Collection testClasses) { - final MinionArguments fileArgs = new MinionArguments(remainingMutations, - testClasses, this.config.getEngine().getName(), this.args, this.timeoutStrategy, - Log.isVerbose(), this.pitConfig); - - final ProcessArgs args = ProcessArgs.withClassPath(this.classPath) - .andLaunchOptions(this.config.getLaunchOptions()) - .andBaseDir(this.baseDir).andStdout(captureStdOutIfVerbose()) - .andStderr(printWith("stderr ")); - - final SocketFinder sf = new SocketFinder(); - final MutationTestProcess worker = new MutationTestProcess( - sf.getNextAvailableServerSocket(), args, fileArgs); - return worker; - } - - private SideEffect1 captureStdOutIfVerbose() { - if (this.verbose) { - return Prelude.printWith("stdout "); - } else { - return Prelude.noSideEffect(String.class); - } - - } - -} +package org.pitest.mutationtest.build; + +import static org.pitest.functional.prelude.Prelude.printWith; + +import java.io.File; +import java.util.Collection; + +import org.pitest.classinfo.ClassName; +import org.pitest.functional.SideEffect1; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.EngineArguments; +import org.pitest.mutationtest.MutationConfig; +import org.pitest.mutationtest.TimeoutLengthStrategy; +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.execute.MinionArguments; +import org.pitest.mutationtest.execute.MutationTestProcess; +import org.pitest.process.ProcessArgs; +import org.pitest.util.Log; +import org.pitest.util.SocketFinder; + +public class WorkerFactory { + + private final String classPath; + private final File baseDir; + private final TestPluginArguments pitConfig; + private final TimeoutLengthStrategy timeoutStrategy; + private final boolean verbose; + private final MutationConfig config; + private final EngineArguments args; + + public WorkerFactory(final File baseDir, + final TestPluginArguments pitConfig, + final MutationConfig mutationConfig, + final EngineArguments args, + final TimeoutLengthStrategy timeoutStrategy, + final boolean verbose, + final String classPath) { + this.pitConfig = pitConfig; + this.timeoutStrategy = timeoutStrategy; + this.verbose = verbose; + this.classPath = classPath; + this.baseDir = baseDir; + this.config = mutationConfig; + this.args = args; + } + + public MutationTestProcess createWorker( + final Collection remainingMutations, + final Collection testClasses) { + final MinionArguments fileArgs = new MinionArguments(remainingMutations, + testClasses, this.config.getEngine().getName(), this.args, this.timeoutStrategy, + Log.isVerbose(), this.pitConfig); + + final ProcessArgs args = ProcessArgs.withClassPath(this.classPath) + .andLaunchOptions(this.config.getLaunchOptions()) + .andBaseDir(this.baseDir).andStdout(captureStdOutIfVerbose()) + .andStderr(printWith("stderr ")); + + final SocketFinder sf = new SocketFinder(); + final MutationTestProcess worker = new MutationTestProcess( + sf.getNextAvailableServerSocket(), args, fileArgs); + return worker; + } + + private SideEffect1 captureStdOutIfVerbose() { + if (this.verbose) { + return Prelude.printWith("stdout "); + } else { + return Prelude.noSideEffect(String.class); + } + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptor.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptor.java index 9aa94a79b..f4aac35e6 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptor.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptor.java @@ -1,86 +1,86 @@ -package org.pitest.mutationtest.build.intercept.annotations; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.objectweb.asm.tree.AnnotationNode; -import org.pitest.bytecode.analysis.AnalysisFunctions; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -public class ExcludedAnnotationInterceptor implements MutationInterceptor { - - private final List configuredAnnotations; - - private boolean skipClass; - private Predicate annotatedMethodMatcher; - - - ExcludedAnnotationInterceptor(List configuredAnnotations) { - this.configuredAnnotations = configuredAnnotations; - } - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.skipClass = clazz.annotations().stream() - .filter(avoidedAnnotation()) - .findFirst().isPresent(); - if (!this.skipClass) { - final List> methods = clazz.methods().stream() - .filter(hasAvoidedAnnotation()) - .map(AnalysisFunctions.matchMutationsInMethod()) - .collect(Collectors.toList()); - this.annotatedMethodMatcher = Prelude.or(methods); - } - } - - private Predicate hasAvoidedAnnotation() { - return a -> a.annotations().stream() - .filter(avoidedAnnotation()) - .findFirst().isPresent(); - } - - private Predicate avoidedAnnotation() { - return a -> shouldAvoid(a.desc); - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - if (this.skipClass) { - return Collections.emptyList(); - } - - return FCollection.filter(mutations, Prelude.not(this.annotatedMethodMatcher)); - } - - @Override - public void end() { - - } - - boolean shouldAvoid(String desc) { - final String matchAgainst = desc.replace(";", ""); - for (final String each : this.configuredAnnotations) { - if (matchAgainst.endsWith(each)) { - return true; - } - } - return false; - } - -} +package org.pitest.mutationtest.build.intercept.annotations; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.objectweb.asm.tree.AnnotationNode; +import org.pitest.bytecode.analysis.AnalysisFunctions; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +public class ExcludedAnnotationInterceptor implements MutationInterceptor { + + private final List configuredAnnotations; + + private boolean skipClass; + private Predicate annotatedMethodMatcher; + + + ExcludedAnnotationInterceptor(List configuredAnnotations) { + this.configuredAnnotations = configuredAnnotations; + } + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.skipClass = clazz.annotations().stream() + .filter(avoidedAnnotation()) + .findFirst().isPresent(); + if (!this.skipClass) { + final List> methods = clazz.methods().stream() + .filter(hasAvoidedAnnotation()) + .map(AnalysisFunctions.matchMutationsInMethod()) + .collect(Collectors.toList()); + this.annotatedMethodMatcher = Prelude.or(methods); + } + } + + private Predicate hasAvoidedAnnotation() { + return a -> a.annotations().stream() + .filter(avoidedAnnotation()) + .findFirst().isPresent(); + } + + private Predicate avoidedAnnotation() { + return a -> shouldAvoid(a.desc); + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + if (this.skipClass) { + return Collections.emptyList(); + } + + return FCollection.filter(mutations, Prelude.not(this.annotatedMethodMatcher)); + } + + @Override + public void end() { + + } + + boolean shouldAvoid(String desc) { + final String matchAgainst = desc.replace(";", ""); + for (final String each : this.configuredAnnotations) { + if (matchAgainst.endsWith(each)) { + return true; + } + } + return false; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptorFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptorFactory.java index 18033a9ba..304a5b3c1 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptorFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptorFactory.java @@ -1,42 +1,42 @@ -package org.pitest.mutationtest.build.intercept.annotations; - -import java.util.Arrays; -import java.util.List; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; -import org.pitest.plugin.FeatureParameter; - -public class ExcludedAnnotationInterceptorFactory implements MutationInterceptorFactory { - - private static final FeatureParameter ARGUMENT = FeatureParameter.named("annotation") - .withDescription("Annotation to avoid (full package name not required)"); - - @Override - public String description() { - return "Excluded annotations plugin"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new ExcludedAnnotationInterceptor(determineAnnotations(params)); - } - - private List determineAnnotations(InterceptorParameters params) { - if (params.getList(ARGUMENT).isEmpty()) { - return Arrays.asList("Generated", "DoNotMutate", "CoverageIgnore"); - } - return params.getList(ARGUMENT); - } - - @Override - public Feature provides() { - return Feature.named("FANN") - .withOnByDefault(true) - .withDescription("Filters mutations in classes and methods with matching annotations of class or runtime retention") - .withParameter(ARGUMENT); - } - -} +package org.pitest.mutationtest.build.intercept.annotations; + +import java.util.Arrays; +import java.util.List; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; +import org.pitest.plugin.FeatureParameter; + +public class ExcludedAnnotationInterceptorFactory implements MutationInterceptorFactory { + + private static final FeatureParameter ARGUMENT = FeatureParameter.named("annotation") + .withDescription("Annotation to avoid (full package name not required)"); + + @Override + public String description() { + return "Excluded annotations plugin"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new ExcludedAnnotationInterceptor(determineAnnotations(params)); + } + + private List determineAnnotations(InterceptorParameters params) { + if (params.getList(ARGUMENT).isEmpty()) { + return Arrays.asList("Generated", "DoNotMutate", "CoverageIgnore"); + } + return params.getList(ARGUMENT); + } + + @Override + public Feature provides() { + return Feature.named("FANN") + .withOnByDefault(true) + .withDescription("Filters mutations in classes and methods with matching annotations of class or runtime retention") + .withParameter(ARGUMENT); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilter.java index cb7ec739b..c68ba3dbc 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilter.java @@ -1,127 +1,127 @@ -package org.pitest.mutationtest.build.intercept.equivalent; - -import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.debug; -import static org.pitest.bytecode.analysis.InstructionMatchers.isA; -import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; - -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.LineNumberNode; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.InstructionMatchers; -import org.pitest.bytecode.analysis.MethodMatchers; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.sequence.Match; -import org.pitest.sequence.QueryParams; -import org.pitest.sequence.QueryStart; -import org.pitest.sequence.SequenceMatcher; - -public class EqualsPerformanceShortcutFilter implements MutationInterceptor { - - private static final boolean DEBUG = false; - - private static final Match IGNORE = isA(LineNumberNode.class).or(isA(FrameNode.class)); - - // Looks fairly specifically for a conditional mutated to a unconditional - // rather than any always false condition - static final SequenceMatcher ALWAYS_FALSE = QueryStart - .any(AbstractInsnNode.class) - .then(opCode(Opcodes.ALOAD)) - .then(opCode(Opcodes.ALOAD)) - .then(opCode(Opcodes.POP2)) - .then(opCode(Opcodes.GOTO).and(debug("goto"))) - .zeroOrMore(QueryStart.match(anyInstruction())) - .compile(QueryParams.params(AbstractInsnNode.class) - .withIgnores(IGNORE) - .withDebug(DEBUG) - ); - - private ClassTree currentClass; - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - final List doNotTouch = FCollection.filter(mutations, inEqualsMethod().negate()); - if (doNotTouch.size() != mutations.size()) { - final List inEquals = FCollection.filter(mutations, inEqualsMethod()); - final List filtered = filter(inEquals, m); - doNotTouch.addAll(filtered); - } - return doNotTouch; - } - - private List filter( - List inEquals, Mutater m) { - final Location equalsMethod = inEquals.get(0).getId().getLocation(); - - final Optional maybeEquals = this.currentClass.methods().stream() - .filter(MethodMatchers.forLocation(equalsMethod)) - .findFirst(); - - return inEquals.stream() - .filter(isShortcutEquals(maybeEquals.get(), m).negate()) - .collect(Collectors.toList()); - } - - private Predicate isShortcutEquals(final MethodTree tree, final Mutater m) { - return a -> shortCutEquals(tree,a, m); - } - - private Boolean shortCutEquals(MethodTree tree, MutationDetails a, Mutater m) { - if (!mutatesAConditionalJump(tree, a.getInstructionIndex())) { - return false; - } - - final ClassTree mutant = ClassTree.fromBytes(m.getMutation(a.getId()).getBytes()); - final MethodTree mutantEquals = mutant.methods().stream() - .filter(MethodMatchers.forLocation(tree.asLocation())) - .findFirst() - .get(); - - return ALWAYS_FALSE.matches(mutantEquals.instructions()); - } - - private boolean mutatesAConditionalJump(MethodTree tree, int index) { - final AbstractInsnNode mutatedInsns = tree.instructions().get(index); - return InstructionMatchers.aConditionalJump().test(null, mutatedInsns); - } - - private Predicate inEqualsMethod() { - return a -> { - final Location loc = a.getId().getLocation(); - return loc.getMethodDesc().equals("(Ljava/lang/Object;)Z") - && loc.getMethodName().equals(MethodName.fromString("equals")); - }; - } - - @Override - public void end() { - - } - -} +package org.pitest.mutationtest.build.intercept.equivalent; + +import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.debug; +import static org.pitest.bytecode.analysis.InstructionMatchers.isA; +import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.InstructionMatchers; +import org.pitest.bytecode.analysis.MethodMatchers; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.sequence.Match; +import org.pitest.sequence.QueryParams; +import org.pitest.sequence.QueryStart; +import org.pitest.sequence.SequenceMatcher; + +public class EqualsPerformanceShortcutFilter implements MutationInterceptor { + + private static final boolean DEBUG = false; + + private static final Match IGNORE = isA(LineNumberNode.class).or(isA(FrameNode.class)); + + // Looks fairly specifically for a conditional mutated to a unconditional + // rather than any always false condition + static final SequenceMatcher ALWAYS_FALSE = QueryStart + .any(AbstractInsnNode.class) + .then(opCode(Opcodes.ALOAD)) + .then(opCode(Opcodes.ALOAD)) + .then(opCode(Opcodes.POP2)) + .then(opCode(Opcodes.GOTO).and(debug("goto"))) + .zeroOrMore(QueryStart.match(anyInstruction())) + .compile(QueryParams.params(AbstractInsnNode.class) + .withIgnores(IGNORE) + .withDebug(DEBUG) + ); + + private ClassTree currentClass; + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + final List doNotTouch = FCollection.filter(mutations, inEqualsMethod().negate()); + if (doNotTouch.size() != mutations.size()) { + final List inEquals = FCollection.filter(mutations, inEqualsMethod()); + final List filtered = filter(inEquals, m); + doNotTouch.addAll(filtered); + } + return doNotTouch; + } + + private List filter( + List inEquals, Mutater m) { + final Location equalsMethod = inEquals.get(0).getId().getLocation(); + + final Optional maybeEquals = this.currentClass.methods().stream() + .filter(MethodMatchers.forLocation(equalsMethod)) + .findFirst(); + + return inEquals.stream() + .filter(isShortcutEquals(maybeEquals.get(), m).negate()) + .collect(Collectors.toList()); + } + + private Predicate isShortcutEquals(final MethodTree tree, final Mutater m) { + return a -> shortCutEquals(tree,a, m); + } + + private Boolean shortCutEquals(MethodTree tree, MutationDetails a, Mutater m) { + if (!mutatesAConditionalJump(tree, a.getInstructionIndex())) { + return false; + } + + final ClassTree mutant = ClassTree.fromBytes(m.getMutation(a.getId()).getBytes()); + final MethodTree mutantEquals = mutant.methods().stream() + .filter(MethodMatchers.forLocation(tree.asLocation())) + .findFirst() + .get(); + + return ALWAYS_FALSE.matches(mutantEquals.instructions()); + } + + private boolean mutatesAConditionalJump(MethodTree tree, int index) { + final AbstractInsnNode mutatedInsns = tree.instructions().get(index); + return InstructionMatchers.aConditionalJump().test(null, mutatedInsns); + } + + private Predicate inEqualsMethod() { + return a -> { + final Location loc = a.getId().getLocation(); + return loc.getMethodDesc().equals("(Ljava/lang/Object;)Z") + && loc.getMethodName().equals(MethodName.fromString("equals")); + }; + } + + @Override + public void end() { + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilterFactory.java index f86e22ad9..bf4061ebf 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilterFactory.java @@ -1,27 +1,27 @@ -package org.pitest.mutationtest.build.intercept.equivalent; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class EqualsPerformanceShortcutFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Equals shortcut equivalent mutant filter"; - } - - @Override - public Feature provides() { - return Feature.named("FSEQUIVEQUALS") - .withOnByDefault(true) - .withDescription("Filters equivalent mutations that affect only performance in short cutting equals methods"); - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new EqualsPerformanceShortcutFilter(); - } - -} +package org.pitest.mutationtest.build.intercept.equivalent; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class EqualsPerformanceShortcutFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Equals shortcut equivalent mutant filter"; + } + + @Override + public Feature provides() { + return Feature.named("FSEQUIVEQUALS") + .withOnByDefault(true) + .withDescription("Filters equivalent mutations that affect only performance in short cutting equals methods"); + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new EqualsPerformanceShortcutFilter(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EquivalentReturnMutationFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EquivalentReturnMutationFilter.java index c74552060..8e59d1533 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EquivalentReturnMutationFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/equivalent/EquivalentReturnMutationFilter.java @@ -1,343 +1,343 @@ -package org.pitest.mutationtest.build.intercept.equivalent; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Predicate; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.LdcInsnNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodMatchers; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.CompoundMutationInterceptor; -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.mutators.BooleanFalseReturnValsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.BooleanTrueReturnValsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.EmptyObjectReturnValsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.NullReturnValsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.PrimitiveReturnsMutator; -import org.pitest.plugin.Feature; - -/** - * Tightly coupled to the PrimitiveReturnsMutator and EmptyObjectReturnValsMutator - * - removes trivially equivalent mutants generated by these. - * operator - * - */ -public class EquivalentReturnMutationFilter implements MutationInterceptorFactory { - - @Override - public String description() { - return "Trivial return vals equivalence filter"; - } - - @Override - public Feature provides() { - return Feature.named("FRETEQUIV") - .withOnByDefault(true) - .withDescription("Filters return vals mutants with bytecode equivalent to the unmutated class"); - - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new CompoundMutationInterceptor(Arrays.asList(new PrimitiveEquivalentFilter(), - new NullReturnsFilter(), - new EmptyReturnsFilter(), - new HardCodedTrueEquivalentFilter())) { - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - }; - } - -} - -class HardCodedTrueEquivalentFilter implements MutationInterceptor { - - private static final Set MUTATOR_IDS = new HashSet<>(); - private static final Set TRUE_CONSTANTS = new HashSet<>(); - static { - TRUE_CONSTANTS.add(Opcodes.ICONST_1); - - MUTATOR_IDS.add(BooleanTrueReturnValsMutator.BOOLEAN_TRUE_RETURN.getGloballyUniqueId()); - } - - private ClassTree currentClass; - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isEquivalent(m))); - } - - private Predicate isEquivalent(Mutater m) { - return new Predicate() { - @Override - public boolean test(MutationDetails a) { - if (!MUTATOR_IDS.contains(a.getMutator())) { - return false; - } - final int instruction = a.getInstructionIndex(); - final MethodTree method = HardCodedTrueEquivalentFilter.this.currentClass.methods().stream() - .filter(MethodMatchers.forLocation(a.getId().getLocation())) - .findFirst().get(); - return primitiveTrue(instruction, method) || boxedTrue(instruction, method); - } - - private boolean primitiveTrue(int instruction, MethodTree method) { - return method.instructions().get(instruction - 1).getOpcode() == Opcodes.ICONST_1; - } - - private boolean boxedTrue(int instruction, MethodTree method) { - return (method.instructions().get(instruction - 2).getOpcode() == Opcodes.ICONST_1) && isValueOfCall(instruction - 1, method); - } - - }; - - } - - @Override - public void end() { - this.currentClass = null; - } - - private boolean isValueOfCall(int instruction, MethodTree method) { - final AbstractInsnNode abstractInsnNode = method.instructions().get(instruction); - if (abstractInsnNode instanceof MethodInsnNode) { - return ((MethodInsnNode) abstractInsnNode).name.equals("valueOf"); - } - return false; - } - -} - - -class PrimitiveEquivalentFilter implements MutationInterceptor { - - private static final Set MUTATOR_IDS = new HashSet<>(); - private static final Set ZERO_CONSTANTS = new HashSet<>(); - static { - ZERO_CONSTANTS.add(Opcodes.ICONST_0); - ZERO_CONSTANTS.add(Opcodes.LCONST_0); - ZERO_CONSTANTS.add(Opcodes.FCONST_0); - ZERO_CONSTANTS.add(Opcodes.DCONST_0); - - MUTATOR_IDS.add(PrimitiveReturnsMutator.PRIMITIVE_RETURN_VALS_MUTATOR.getGloballyUniqueId()); - MUTATOR_IDS.add(BooleanFalseReturnValsMutator.BOOLEAN_FALSE_RETURN.getGloballyUniqueId()); - } - - private ClassTree currentClass; - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isEquivalent(m))); - } - - private Predicate isEquivalent(Mutater m) { - return a -> { - if (!MUTATOR_IDS.contains(a.getMutator())) { - return false; - } - final int intructionBeforeReturn = a.getInstructionIndex() - 1; - final MethodTree method = PrimitiveEquivalentFilter.this.currentClass.methods().stream() - .filter(MethodMatchers.forLocation(a.getId().getLocation())) - .findFirst() - .get(); - return ZERO_CONSTANTS.contains(method.instructions().get(intructionBeforeReturn).getOpcode()); - }; - } - - @Override - public void end() { - this.currentClass = null; - } - -} - -class EmptyReturnsFilter implements MutationInterceptor { - - private static final Set MUTATOR_IDS = new HashSet<>(); - - private static final Set ZERO_CONSTANTS = new HashSet<>(); - static { - ZERO_CONSTANTS.add(Opcodes.ICONST_0); - ZERO_CONSTANTS.add(Opcodes.LCONST_0); - ZERO_CONSTANTS.add(Opcodes.FCONST_0); - ZERO_CONSTANTS.add(Opcodes.DCONST_0); - - MUTATOR_IDS.add(EmptyObjectReturnValsMutator.EMPTY_RETURN_VALUES.getGloballyUniqueId()); - MUTATOR_IDS.add(BooleanFalseReturnValsMutator.BOOLEAN_FALSE_RETURN.getGloballyUniqueId()); - } - - private ClassTree currentClass; - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isEquivalent(m))); - } - - private Predicate isEquivalent(Mutater m) { - return new Predicate() { - @Override - public boolean test(MutationDetails a) { - if (!MUTATOR_IDS.contains(a.getMutator())) { - return false; - } - - final MethodTree method = EmptyReturnsFilter.this.currentClass.methods().stream() - .filter(MethodMatchers.forLocation(a.getId().getLocation())) - .findFirst() - .get(); - final int mutatedInstruction = a.getInstructionIndex(); - return returnsZeroValue(method, mutatedInstruction) - || returnsEmptyString(method, mutatedInstruction) - || returns(method, mutatedInstruction, "java/util/Optional","empty") - || returns(method, mutatedInstruction, "java/util/Collections","emptyList") - || returns(method, mutatedInstruction, "java/util/Collections","emptySet") - || returns(method, mutatedInstruction, "java/util/List","of") - || returns(method, mutatedInstruction, "java/util/Set","of"); - } - - private Boolean returnsZeroValue(MethodTree method, - int mutatedInstruction) { - return isValueOf(method.instructions().get(mutatedInstruction - 1)) - && ZERO_CONSTANTS.contains(method.instructions().get(mutatedInstruction - 2).getOpcode()); - } - - private boolean isValueOf(AbstractInsnNode abstractInsnNode) { - if (abstractInsnNode instanceof MethodInsnNode) { - return ((MethodInsnNode) abstractInsnNode).name.equals("valueOf"); - } - return false; - } - - private boolean returns(MethodTree method, int mutatedInstruction, String owner, String name) { - final AbstractInsnNode node = method.instructions().get(mutatedInstruction - 1); - if (node instanceof MethodInsnNode ) { - final MethodInsnNode call = (MethodInsnNode) node; - return call.owner.equals(owner) && call.name.equals(name) && takesNoArguments(call.desc); - } - return false; - } - - private boolean takesNoArguments(String desc) { - return Type.getArgumentTypes(desc).length == 0; - } - - private boolean returnsEmptyString(MethodTree method, - int mutatedInstruction) { - final AbstractInsnNode node = method.instructions().get(mutatedInstruction - 1); - if (node instanceof LdcInsnNode ) { - final LdcInsnNode ldc = (LdcInsnNode) node; - return "".equals(ldc.cst); - } - return false; - } - - }; - } - - @Override - public void end() { - this.currentClass = null; - } - -} - -class NullReturnsFilter implements MutationInterceptor { - - private static final String MUTATOR_ID = NullReturnValsMutator.NULL_RETURN_VALUES.getGloballyUniqueId(); - - private ClassTree currentClass; - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isEquivalent(m))); - } - - private Predicate isEquivalent(Mutater m) { - return new Predicate() { - @Override - public boolean test(MutationDetails a) { - if (!MUTATOR_ID.equals(a.getMutator())) { - return false; - } - - final MethodTree method = NullReturnsFilter.this.currentClass.methods().stream() - .filter(MethodMatchers.forLocation(a.getId().getLocation())) - .findFirst() - .get(); - final int mutatedInstruction = a.getInstructionIndex(); - return returnsNull(method, mutatedInstruction); - } - - private Boolean returnsNull(MethodTree method, - int mutatedInstruction) { - return method.instructions().get(mutatedInstruction - 1).getOpcode() == Opcodes.ACONST_NULL; - } - }; - } - - @Override - public void end() { - this.currentClass = null; - } - -} +package org.pitest.mutationtest.build.intercept.equivalent; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Predicate; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodMatchers; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.CompoundMutationInterceptor; +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.mutators.BooleanFalseReturnValsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.BooleanTrueReturnValsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.EmptyObjectReturnValsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.NullReturnValsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.PrimitiveReturnsMutator; +import org.pitest.plugin.Feature; + +/** + * Tightly coupled to the PrimitiveReturnsMutator and EmptyObjectReturnValsMutator + * - removes trivially equivalent mutants generated by these. + * operator + * + */ +public class EquivalentReturnMutationFilter implements MutationInterceptorFactory { + + @Override + public String description() { + return "Trivial return vals equivalence filter"; + } + + @Override + public Feature provides() { + return Feature.named("FRETEQUIV") + .withOnByDefault(true) + .withDescription("Filters return vals mutants with bytecode equivalent to the unmutated class"); + + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new CompoundMutationInterceptor(Arrays.asList(new PrimitiveEquivalentFilter(), + new NullReturnsFilter(), + new EmptyReturnsFilter(), + new HardCodedTrueEquivalentFilter())) { + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + }; + } + +} + +class HardCodedTrueEquivalentFilter implements MutationInterceptor { + + private static final Set MUTATOR_IDS = new HashSet<>(); + private static final Set TRUE_CONSTANTS = new HashSet<>(); + static { + TRUE_CONSTANTS.add(Opcodes.ICONST_1); + + MUTATOR_IDS.add(BooleanTrueReturnValsMutator.BOOLEAN_TRUE_RETURN.getGloballyUniqueId()); + } + + private ClassTree currentClass; + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isEquivalent(m))); + } + + private Predicate isEquivalent(Mutater m) { + return new Predicate() { + @Override + public boolean test(MutationDetails a) { + if (!MUTATOR_IDS.contains(a.getMutator())) { + return false; + } + final int instruction = a.getInstructionIndex(); + final MethodTree method = HardCodedTrueEquivalentFilter.this.currentClass.methods().stream() + .filter(MethodMatchers.forLocation(a.getId().getLocation())) + .findFirst().get(); + return primitiveTrue(instruction, method) || boxedTrue(instruction, method); + } + + private boolean primitiveTrue(int instruction, MethodTree method) { + return method.instructions().get(instruction - 1).getOpcode() == Opcodes.ICONST_1; + } + + private boolean boxedTrue(int instruction, MethodTree method) { + return (method.instructions().get(instruction - 2).getOpcode() == Opcodes.ICONST_1) && isValueOfCall(instruction - 1, method); + } + + }; + + } + + @Override + public void end() { + this.currentClass = null; + } + + private boolean isValueOfCall(int instruction, MethodTree method) { + final AbstractInsnNode abstractInsnNode = method.instructions().get(instruction); + if (abstractInsnNode instanceof MethodInsnNode) { + return ((MethodInsnNode) abstractInsnNode).name.equals("valueOf"); + } + return false; + } + +} + + +class PrimitiveEquivalentFilter implements MutationInterceptor { + + private static final Set MUTATOR_IDS = new HashSet<>(); + private static final Set ZERO_CONSTANTS = new HashSet<>(); + static { + ZERO_CONSTANTS.add(Opcodes.ICONST_0); + ZERO_CONSTANTS.add(Opcodes.LCONST_0); + ZERO_CONSTANTS.add(Opcodes.FCONST_0); + ZERO_CONSTANTS.add(Opcodes.DCONST_0); + + MUTATOR_IDS.add(PrimitiveReturnsMutator.PRIMITIVE_RETURN_VALS_MUTATOR.getGloballyUniqueId()); + MUTATOR_IDS.add(BooleanFalseReturnValsMutator.BOOLEAN_FALSE_RETURN.getGloballyUniqueId()); + } + + private ClassTree currentClass; + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isEquivalent(m))); + } + + private Predicate isEquivalent(Mutater m) { + return a -> { + if (!MUTATOR_IDS.contains(a.getMutator())) { + return false; + } + final int intructionBeforeReturn = a.getInstructionIndex() - 1; + final MethodTree method = PrimitiveEquivalentFilter.this.currentClass.methods().stream() + .filter(MethodMatchers.forLocation(a.getId().getLocation())) + .findFirst() + .get(); + return ZERO_CONSTANTS.contains(method.instructions().get(intructionBeforeReturn).getOpcode()); + }; + } + + @Override + public void end() { + this.currentClass = null; + } + +} + +class EmptyReturnsFilter implements MutationInterceptor { + + private static final Set MUTATOR_IDS = new HashSet<>(); + + private static final Set ZERO_CONSTANTS = new HashSet<>(); + static { + ZERO_CONSTANTS.add(Opcodes.ICONST_0); + ZERO_CONSTANTS.add(Opcodes.LCONST_0); + ZERO_CONSTANTS.add(Opcodes.FCONST_0); + ZERO_CONSTANTS.add(Opcodes.DCONST_0); + + MUTATOR_IDS.add(EmptyObjectReturnValsMutator.EMPTY_RETURN_VALUES.getGloballyUniqueId()); + MUTATOR_IDS.add(BooleanFalseReturnValsMutator.BOOLEAN_FALSE_RETURN.getGloballyUniqueId()); + } + + private ClassTree currentClass; + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isEquivalent(m))); + } + + private Predicate isEquivalent(Mutater m) { + return new Predicate() { + @Override + public boolean test(MutationDetails a) { + if (!MUTATOR_IDS.contains(a.getMutator())) { + return false; + } + + final MethodTree method = EmptyReturnsFilter.this.currentClass.methods().stream() + .filter(MethodMatchers.forLocation(a.getId().getLocation())) + .findFirst() + .get(); + final int mutatedInstruction = a.getInstructionIndex(); + return returnsZeroValue(method, mutatedInstruction) + || returnsEmptyString(method, mutatedInstruction) + || returns(method, mutatedInstruction, "java/util/Optional","empty") + || returns(method, mutatedInstruction, "java/util/Collections","emptyList") + || returns(method, mutatedInstruction, "java/util/Collections","emptySet") + || returns(method, mutatedInstruction, "java/util/List","of") + || returns(method, mutatedInstruction, "java/util/Set","of"); + } + + private Boolean returnsZeroValue(MethodTree method, + int mutatedInstruction) { + return isValueOf(method.instructions().get(mutatedInstruction - 1)) + && ZERO_CONSTANTS.contains(method.instructions().get(mutatedInstruction - 2).getOpcode()); + } + + private boolean isValueOf(AbstractInsnNode abstractInsnNode) { + if (abstractInsnNode instanceof MethodInsnNode) { + return ((MethodInsnNode) abstractInsnNode).name.equals("valueOf"); + } + return false; + } + + private boolean returns(MethodTree method, int mutatedInstruction, String owner, String name) { + final AbstractInsnNode node = method.instructions().get(mutatedInstruction - 1); + if (node instanceof MethodInsnNode ) { + final MethodInsnNode call = (MethodInsnNode) node; + return call.owner.equals(owner) && call.name.equals(name) && takesNoArguments(call.desc); + } + return false; + } + + private boolean takesNoArguments(String desc) { + return Type.getArgumentTypes(desc).length == 0; + } + + private boolean returnsEmptyString(MethodTree method, + int mutatedInstruction) { + final AbstractInsnNode node = method.instructions().get(mutatedInstruction - 1); + if (node instanceof LdcInsnNode ) { + final LdcInsnNode ldc = (LdcInsnNode) node; + return "".equals(ldc.cst); + } + return false; + } + + }; + } + + @Override + public void end() { + this.currentClass = null; + } + +} + +class NullReturnsFilter implements MutationInterceptor { + + private static final String MUTATOR_ID = NullReturnValsMutator.NULL_RETURN_VALUES.getGloballyUniqueId(); + + private ClassTree currentClass; + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isEquivalent(m))); + } + + private Predicate isEquivalent(Mutater m) { + return new Predicate() { + @Override + public boolean test(MutationDetails a) { + if (!MUTATOR_ID.equals(a.getMutator())) { + return false; + } + + final MethodTree method = NullReturnsFilter.this.currentClass.methods().stream() + .filter(MethodMatchers.forLocation(a.getId().getLocation())) + .findFirst() + .get(); + final int mutatedInstruction = a.getInstructionIndex(); + return returnsNull(method, mutatedInstruction); + } + + private Boolean returnsNull(MethodTree method, + int mutatedInstruction) { + return method.instructions().get(mutatedInstruction - 1).getOpcode() == Opcodes.ACONST_NULL; + } + }; + } + + @Override + public void end() { + this.currentClass = null; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachLoopFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachLoopFilter.java index ec518c307..671467737 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachLoopFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachLoopFilter.java @@ -1,208 +1,208 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJump; -import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJumpTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; -import static org.pitest.bytecode.analysis.InstructionMatchers.anIStore; -import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.debug; -import static org.pitest.bytecode.analysis.InstructionMatchers.gotoLabel; -import static org.pitest.bytecode.analysis.InstructionMatchers.incrementsVariable; -import static org.pitest.bytecode.analysis.InstructionMatchers.isA; -import static org.pitest.bytecode.analysis.InstructionMatchers.jumpsTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.labelNode; -import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallThatReturns; -import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; -import static org.pitest.bytecode.analysis.InstructionMatchers.recordTarget; - -import java.util.Collection; -import java.util.Iterator; -import java.util.function.Predicate; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.LineNumberNode; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodMatchers; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.classinfo.ClassName; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.sequence.Context; -import org.pitest.sequence.Match; -import org.pitest.sequence.QueryParams; -import org.pitest.sequence.QueryStart; -import org.pitest.sequence.SequenceMatcher; -import org.pitest.sequence.SequenceQuery; -import org.pitest.sequence.Slot; - -public class ForEachLoopFilter implements MutationInterceptor { - - private static final boolean DEBUG = false; - - private static final Match IGNORE = isA(LineNumberNode.class) - .or(isA(FrameNode.class) - ); - - private static final Slot MUTATED_INSTRUCTION = Slot.create(AbstractInsnNode.class); - private static final Slot FOUND = Slot.create(Boolean.class); - - - private static final SequenceMatcher ITERATOR_LOOP = QueryStart - .match(Match.never()) - .or(conditionalAtStart()) - .or(conditionalAtEnd()) - .or(arrayConditionalAtEnd()) - .or(arrayConditionalAtStart()) - .then(containMutation(FOUND)) - .compile(QueryParams.params(AbstractInsnNode.class) - .withIgnores(IGNORE) - .withDebug(DEBUG) - ); - - private ClassTree currentClass; - - - private static SequenceQuery conditionalAtEnd() { - final Slot loopStart = Slot.create(LabelNode.class); - final Slot loopEnd = Slot.create(LabelNode.class); - return QueryStart - .any(AbstractInsnNode.class) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(aMethodCallReturningAnIterator().and(mutationPoint())) - .then(opCode(Opcodes.ASTORE)) - .then(gotoLabel(loopEnd.write())) - .then(aLabelNode(loopStart.write())) - .then(opCode(Opcodes.ALOAD)) - .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "next").and(mutationPoint())) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(labelNode(loopEnd.read())) - .then(opCode(Opcodes.ALOAD)) - .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "hasNext").and(mutationPoint())) - .then(aConditionalJumpTo(loopStart).and(mutationPoint())) - .zeroOrMore(QueryStart.match(anyInstruction())); - } - - - private static SequenceQuery conditionalAtStart() { - final Slot loopStart = Slot.create(LabelNode.class); - final Slot loopEnd = Slot.create(LabelNode.class); - return QueryStart - .any(AbstractInsnNode.class) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(aMethodCallReturningAnIterator().and(mutationPoint())) - .then(opCode(Opcodes.ASTORE)) - .then(aLabelNode(loopStart.write())) - .then(opCode(Opcodes.ALOAD)) - .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "hasNext").and(mutationPoint())) - .then(aConditionalJump().and(jumpsTo(loopEnd.write())).and(mutationPoint())) - .then(opCode(Opcodes.ALOAD)) - .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "next").and(mutationPoint())) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(opCode(Opcodes.GOTO).and(jumpsTo(loopStart.read()))) - .then(labelNode(loopEnd.read())) - .zeroOrMore(QueryStart.match(anyInstruction())); - } - - - private static SequenceQuery arrayConditionalAtEnd() { - final Slot loopStart = Slot.create(LabelNode.class); - final Slot loopEnd = Slot.create(LabelNode.class); - final Slot counter = Slot.create(Integer.class); - return QueryStart - .any(AbstractInsnNode.class) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(opCode(Opcodes.ARRAYLENGTH).and(mutationPoint())) - .then(opCode(Opcodes.ISTORE)) - .then(opCode(Opcodes.ICONST_0).and(mutationPoint())) - .then(anIStore(counter.write()).and(debug("store"))) - .then(gotoLabel(loopEnd.write())) - .then(aLabelNode(loopStart.write())) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(incrementsVariable(counter.read()).and(mutationPoint())) - .then(labelNode(loopEnd.read())) - .then(opCode(Opcodes.ILOAD)) - .then(opCode(Opcodes.ILOAD)) - .then(aConditionalJumpTo(loopStart).and(mutationPoint())) - .zeroOrMore(QueryStart.match(anyInstruction())); - } - - private static SequenceQuery arrayConditionalAtStart() { - final Slot loopStart = Slot.create(LabelNode.class); - final Slot loopEnd = Slot.create(LabelNode.class); - final Slot counter = Slot.create(Integer.class); - return QueryStart - .any(AbstractInsnNode.class) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(opCode(Opcodes.ARRAYLENGTH).and(mutationPoint())) - .then(opCode(Opcodes.ISTORE)) - .then(opCode(Opcodes.ICONST_0).and(mutationPoint())) - .then(anIStore(counter.write()).and(debug("store"))) - .then(aLabelNode(loopStart.write())) - .then(opCode(Opcodes.ILOAD)) - .then(opCode(Opcodes.ILOAD)) - .then(aConditionalJump().and(jumpsTo(loopEnd.write())).and(mutationPoint())) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(incrementsVariable(counter.read()).and(mutationPoint())) - .then(opCode(Opcodes.GOTO).and(jumpsTo(loopStart.read()))) - .zeroOrMore(QueryStart.match(anyInstruction())); - } - - - private static Match aMethodCallReturningAnIterator() { - return methodCallThatReturns(ClassName.fromClass(Iterator.class)); - } - - private static Match mutationPoint() { - return recordTarget(MUTATED_INSTRUCTION.read(), FOUND.write()); - } - - - private static Match containMutation(final Slot found) { - return (c, t) -> c.retrieve(found.read()).isPresent(); - } - - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(mutatesIteratorLoopPlumbing())); - } - - private Predicate mutatesIteratorLoopPlumbing() { - return a -> { - final int instruction = a.getInstructionIndex(); - final MethodTree method = ForEachLoopFilter.this.currentClass.methods().stream() - .filter(MethodMatchers.forLocation(a.getId().getLocation())) - .findFirst() - .get(); - final AbstractInsnNode mutatedInstruction = method.instructions().get(instruction); - - final Context context = Context.start(method.instructions(), DEBUG); - context.store(MUTATED_INSTRUCTION.write(), mutatedInstruction); - return ITERATOR_LOOP.matches(method.instructions(), context); - }; - } - - @Override - public void end() { - this.currentClass = null; - } -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJump; +import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJumpTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; +import static org.pitest.bytecode.analysis.InstructionMatchers.anIStore; +import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.debug; +import static org.pitest.bytecode.analysis.InstructionMatchers.gotoLabel; +import static org.pitest.bytecode.analysis.InstructionMatchers.incrementsVariable; +import static org.pitest.bytecode.analysis.InstructionMatchers.isA; +import static org.pitest.bytecode.analysis.InstructionMatchers.jumpsTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.labelNode; +import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallThatReturns; +import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; +import static org.pitest.bytecode.analysis.InstructionMatchers.recordTarget; + +import java.util.Collection; +import java.util.Iterator; +import java.util.function.Predicate; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodMatchers; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.classinfo.ClassName; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.sequence.Context; +import org.pitest.sequence.Match; +import org.pitest.sequence.QueryParams; +import org.pitest.sequence.QueryStart; +import org.pitest.sequence.SequenceMatcher; +import org.pitest.sequence.SequenceQuery; +import org.pitest.sequence.Slot; + +public class ForEachLoopFilter implements MutationInterceptor { + + private static final boolean DEBUG = false; + + private static final Match IGNORE = isA(LineNumberNode.class) + .or(isA(FrameNode.class) + ); + + private static final Slot MUTATED_INSTRUCTION = Slot.create(AbstractInsnNode.class); + private static final Slot FOUND = Slot.create(Boolean.class); + + + private static final SequenceMatcher ITERATOR_LOOP = QueryStart + .match(Match.never()) + .or(conditionalAtStart()) + .or(conditionalAtEnd()) + .or(arrayConditionalAtEnd()) + .or(arrayConditionalAtStart()) + .then(containMutation(FOUND)) + .compile(QueryParams.params(AbstractInsnNode.class) + .withIgnores(IGNORE) + .withDebug(DEBUG) + ); + + private ClassTree currentClass; + + + private static SequenceQuery conditionalAtEnd() { + final Slot loopStart = Slot.create(LabelNode.class); + final Slot loopEnd = Slot.create(LabelNode.class); + return QueryStart + .any(AbstractInsnNode.class) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(aMethodCallReturningAnIterator().and(mutationPoint())) + .then(opCode(Opcodes.ASTORE)) + .then(gotoLabel(loopEnd.write())) + .then(aLabelNode(loopStart.write())) + .then(opCode(Opcodes.ALOAD)) + .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "next").and(mutationPoint())) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(labelNode(loopEnd.read())) + .then(opCode(Opcodes.ALOAD)) + .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "hasNext").and(mutationPoint())) + .then(aConditionalJumpTo(loopStart).and(mutationPoint())) + .zeroOrMore(QueryStart.match(anyInstruction())); + } + + + private static SequenceQuery conditionalAtStart() { + final Slot loopStart = Slot.create(LabelNode.class); + final Slot loopEnd = Slot.create(LabelNode.class); + return QueryStart + .any(AbstractInsnNode.class) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(aMethodCallReturningAnIterator().and(mutationPoint())) + .then(opCode(Opcodes.ASTORE)) + .then(aLabelNode(loopStart.write())) + .then(opCode(Opcodes.ALOAD)) + .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "hasNext").and(mutationPoint())) + .then(aConditionalJump().and(jumpsTo(loopEnd.write())).and(mutationPoint())) + .then(opCode(Opcodes.ALOAD)) + .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "next").and(mutationPoint())) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(opCode(Opcodes.GOTO).and(jumpsTo(loopStart.read()))) + .then(labelNode(loopEnd.read())) + .zeroOrMore(QueryStart.match(anyInstruction())); + } + + + private static SequenceQuery arrayConditionalAtEnd() { + final Slot loopStart = Slot.create(LabelNode.class); + final Slot loopEnd = Slot.create(LabelNode.class); + final Slot counter = Slot.create(Integer.class); + return QueryStart + .any(AbstractInsnNode.class) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(opCode(Opcodes.ARRAYLENGTH).and(mutationPoint())) + .then(opCode(Opcodes.ISTORE)) + .then(opCode(Opcodes.ICONST_0).and(mutationPoint())) + .then(anIStore(counter.write()).and(debug("store"))) + .then(gotoLabel(loopEnd.write())) + .then(aLabelNode(loopStart.write())) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(incrementsVariable(counter.read()).and(mutationPoint())) + .then(labelNode(loopEnd.read())) + .then(opCode(Opcodes.ILOAD)) + .then(opCode(Opcodes.ILOAD)) + .then(aConditionalJumpTo(loopStart).and(mutationPoint())) + .zeroOrMore(QueryStart.match(anyInstruction())); + } + + private static SequenceQuery arrayConditionalAtStart() { + final Slot loopStart = Slot.create(LabelNode.class); + final Slot loopEnd = Slot.create(LabelNode.class); + final Slot counter = Slot.create(Integer.class); + return QueryStart + .any(AbstractInsnNode.class) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(opCode(Opcodes.ARRAYLENGTH).and(mutationPoint())) + .then(opCode(Opcodes.ISTORE)) + .then(opCode(Opcodes.ICONST_0).and(mutationPoint())) + .then(anIStore(counter.write()).and(debug("store"))) + .then(aLabelNode(loopStart.write())) + .then(opCode(Opcodes.ILOAD)) + .then(opCode(Opcodes.ILOAD)) + .then(aConditionalJump().and(jumpsTo(loopEnd.write())).and(mutationPoint())) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(incrementsVariable(counter.read()).and(mutationPoint())) + .then(opCode(Opcodes.GOTO).and(jumpsTo(loopStart.read()))) + .zeroOrMore(QueryStart.match(anyInstruction())); + } + + + private static Match aMethodCallReturningAnIterator() { + return methodCallThatReturns(ClassName.fromClass(Iterator.class)); + } + + private static Match mutationPoint() { + return recordTarget(MUTATED_INSTRUCTION.read(), FOUND.write()); + } + + + private static Match containMutation(final Slot found) { + return (c, t) -> c.retrieve(found.read()).isPresent(); + } + + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(mutatesIteratorLoopPlumbing())); + } + + private Predicate mutatesIteratorLoopPlumbing() { + return a -> { + final int instruction = a.getInstructionIndex(); + final MethodTree method = ForEachLoopFilter.this.currentClass.methods().stream() + .filter(MethodMatchers.forLocation(a.getId().getLocation())) + .findFirst() + .get(); + final AbstractInsnNode mutatedInstruction = method.instructions().get(instruction); + + final Context context = Context.start(method.instructions(), DEBUG); + context.store(MUTATED_INSTRUCTION.write(), mutatedInstruction); + return ITERATOR_LOOP.matches(method.instructions(), context); + }; + } + + @Override + public void end() { + this.currentClass = null; + } +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachLoopFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachLoopFilterFactory.java index ebf73fd6f..8d52a9615 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachLoopFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachLoopFilterFactory.java @@ -1,27 +1,27 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class ForEachLoopFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "For each loop filter"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new ForEachLoopFilter(); - } - - @Override - public Feature provides() { - return Feature.named("FFEACH") - .withOnByDefault(true) - .withDescription("Filters mutations in compiler generated code that implements for each loops"); - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class ForEachLoopFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "For each loop filter"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new ForEachLoopFilter(); + } + + @Override + public Feature provides() { + return Feature.named("FFEACH") + .withOnByDefault(true) + .withDescription("Filters mutations in compiler generated code that implements for each loops"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilter.java index 252d61666..1951afa98 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilter.java @@ -1,93 +1,93 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.isA; -import static org.pitest.bytecode.analysis.InstructionMatchers.isInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; - -import java.util.Collection; -import java.util.function.Predicate; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.LineNumberNode; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodMatchers; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.classinfo.ClassName; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.sequence.Context; -import org.pitest.sequence.Match; -import org.pitest.sequence.QueryParams; -import org.pitest.sequence.QueryStart; -import org.pitest.sequence.SequenceMatcher; -import org.pitest.sequence.Slot; - -public class ImplicitNullCheckFilter implements MutationInterceptor { - - private static final boolean DEBUG = false; - - private static final Match IGNORE = isA(LineNumberNode.class).or(isA(FrameNode.class)); - - private static final Slot MUTATED_INSTRUCTION = Slot.create(AbstractInsnNode.class); - - static final SequenceMatcher GET_CLASS_NULL_CHECK = QueryStart - .any(AbstractInsnNode.class) - .then(methodCallTo(ClassName.fromClass(Object.class), "getClass").and(isInstruction(MUTATED_INSTRUCTION.read()))) - .then(opCode(Opcodes.POP)) // immediate discard - .then(isA(LabelNode.class).negate()) // use presence of a label to indicate this was a programmer call to getClass - .zeroOrMore(QueryStart.match(anyInstruction())) - .compile(QueryParams.params(AbstractInsnNode.class) - .withIgnores(IGNORE) - .withDebug(DEBUG) - ); - - - private ClassTree currentClass; - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isAnImplicitNullCheck())); - } - - private Predicate isAnImplicitNullCheck() { - return a -> { - final int instruction = a.getInstructionIndex(); - final MethodTree method = ImplicitNullCheckFilter.this.currentClass.methods().stream() - .filter(MethodMatchers.forLocation(a.getId().getLocation())) - .findFirst() - .get(); - - final AbstractInsnNode mutatedInstruction = method.instructions().get(instruction); - - final Context context = Context.start(method.instructions(), DEBUG); - context.store(MUTATED_INSTRUCTION.write(), mutatedInstruction); - return GET_CLASS_NULL_CHECK.matches(method.instructions(), context); - }; - } - - @Override - public void end() { - this.currentClass = null; - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.isA; +import static org.pitest.bytecode.analysis.InstructionMatchers.isInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; + +import java.util.Collection; +import java.util.function.Predicate; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodMatchers; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.classinfo.ClassName; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.sequence.Context; +import org.pitest.sequence.Match; +import org.pitest.sequence.QueryParams; +import org.pitest.sequence.QueryStart; +import org.pitest.sequence.SequenceMatcher; +import org.pitest.sequence.Slot; + +public class ImplicitNullCheckFilter implements MutationInterceptor { + + private static final boolean DEBUG = false; + + private static final Match IGNORE = isA(LineNumberNode.class).or(isA(FrameNode.class)); + + private static final Slot MUTATED_INSTRUCTION = Slot.create(AbstractInsnNode.class); + + static final SequenceMatcher GET_CLASS_NULL_CHECK = QueryStart + .any(AbstractInsnNode.class) + .then(methodCallTo(ClassName.fromClass(Object.class), "getClass").and(isInstruction(MUTATED_INSTRUCTION.read()))) + .then(opCode(Opcodes.POP)) // immediate discard + .then(isA(LabelNode.class).negate()) // use presence of a label to indicate this was a programmer call to getClass + .zeroOrMore(QueryStart.match(anyInstruction())) + .compile(QueryParams.params(AbstractInsnNode.class) + .withIgnores(IGNORE) + .withDebug(DEBUG) + ); + + + private ClassTree currentClass; + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isAnImplicitNullCheck())); + } + + private Predicate isAnImplicitNullCheck() { + return a -> { + final int instruction = a.getInstructionIndex(); + final MethodTree method = ImplicitNullCheckFilter.this.currentClass.methods().stream() + .filter(MethodMatchers.forLocation(a.getId().getLocation())) + .findFirst() + .get(); + + final AbstractInsnNode mutatedInstruction = method.instructions().get(instruction); + + final Context context = Context.start(method.instructions(), DEBUG); + context.store(MUTATED_INSTRUCTION.write(), mutatedInstruction); + return GET_CLASS_NULL_CHECK.matches(method.instructions(), context); + }; + } + + @Override + public void end() { + this.currentClass = null; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilterFactory.java index f71805785..b66f571f9 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilterFactory.java @@ -1,27 +1,27 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class ImplicitNullCheckFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Implicit null check filter"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new ImplicitNullCheckFilter(); - } - - @Override - public Feature provides() { - return Feature.named("FINULL") - .withOnByDefault(true) - .withDescription("Filters mutations in compiler generated code that checks for null by calling getClass"); - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class ImplicitNullCheckFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Implicit null check filter"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new ImplicitNullCheckFilter(); + } + + @Override + public Feature provides() { + return Feature.named("FINULL") + .withOnByDefault(true) + .withDescription("Filters mutations in compiler generated code that checks for null by calling getClass"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilter.java index f58fa513b..e0c47023d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilter.java @@ -1,146 +1,146 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.pitest.functional.FCollection.bucket; -import static org.pitest.functional.FCollection.map; -import static org.pitest.functional.FCollection.mapTo; -import static org.pitest.functional.prelude.Prelude.isEqualTo; -import static org.pitest.functional.prelude.Prelude.not; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.logging.Logger; - -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.util.Log; - -/** - * Detects mutations on same line, but within different code blocks. This - * pattern indicates code inlined for a finally block . . . or normal code that - * creates two blocks on the same line. - * - * Cannot be used with code that uses single line if statements - */ -public class InlinedFinallyBlockFilter implements MutationInterceptor { - - private static final Logger LOG = Log.getLogger(); - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - // no-opp - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - final List combined = new ArrayList<>( - mutations.size()); - final Map> mutatorLinebuckets = bucket( - mutations, toLineMutatorPair()); - - for (final Entry> each : mutatorLinebuckets - .entrySet()) { - if (each.getValue().size() > 1) { - checkForInlinedCode(combined, each); - } else { - combined.addAll(each.getValue()); - } - } - - /** FIXME tests rely on order of returned mutants **/ - Collections.sort(combined, compareLineNumbers()); - return combined; - } - - @Override - public void end() { - // no-opp - } - - private static Comparator compareLineNumbers() { - return (arg0, arg1) -> arg0.getLineNumber() - arg1.getLineNumber(); - } - - private void checkForInlinedCode(final Collection combined, - final Entry> each) { - - final List mutationsInHandlerBlock = FCollection - .filter(each.getValue(), isInFinallyHandler()); - if (!isPossibleToCorrectInlining(mutationsInHandlerBlock)) { - combined.addAll(each.getValue()); - return; - } - - final MutationDetails baseMutation = mutationsInHandlerBlock.get(0); - final int firstBlock = baseMutation.getBlock(); - - // check that we have at least on mutation in a different block - // to the base one (is this not implied by there being only 1 mutation in - // the handler ????) - final List ids = map(each.getValue(), mutationToBlock()); - if (ids.stream().filter(not(isEqualTo(firstBlock))).findFirst().isPresent()) { - combined.add(makeCombinedMutant(each.getValue())); - } else { - combined.addAll(each.getValue()); - } - } - - private boolean isPossibleToCorrectInlining( - final List mutationsInHandlerBlock) { - if (mutationsInHandlerBlock.size() > 1) { - LOG.warning("Found more than one mutation similar on same line in a finally block. Can't correct for inlining."); - return false; - } - - return !mutationsInHandlerBlock.isEmpty(); - } - - private static Predicate isInFinallyHandler() { - return a -> a.isInFinallyBlock(); - } - - private static MutationDetails makeCombinedMutant( - final Collection value) { - final MutationDetails first = value.iterator().next(); - final Set indexes = new HashSet<>(); - mapTo(value, mutationToIndex(), indexes); - - final MutationIdentifier id = new MutationIdentifier(first.getId() - .getLocation(), indexes, first.getId().getMutator()); - - return new MutationDetails(id, first.getFilename(), first.getDescription(), - first.getLineNumber(), first.getBlock()); - } - - private static Function mutationToIndex() { - return a -> a.getFirstIndex(); - } - - private static Function mutationToBlock() { - return a -> a.getBlock(); - } - - private static Function toLineMutatorPair() { - return a -> new LineMutatorPair(a.getLineNumber(), a.getMutator()); - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.pitest.functional.FCollection.bucket; +import static org.pitest.functional.FCollection.map; +import static org.pitest.functional.FCollection.mapTo; +import static org.pitest.functional.prelude.Prelude.isEqualTo; +import static org.pitest.functional.prelude.Prelude.not; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.logging.Logger; + +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.util.Log; + +/** + * Detects mutations on same line, but within different code blocks. This + * pattern indicates code inlined for a finally block . . . or normal code that + * creates two blocks on the same line. + * + * Cannot be used with code that uses single line if statements + */ +public class InlinedFinallyBlockFilter implements MutationInterceptor { + + private static final Logger LOG = Log.getLogger(); + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + // no-opp + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + final List combined = new ArrayList<>( + mutations.size()); + final Map> mutatorLinebuckets = bucket( + mutations, toLineMutatorPair()); + + for (final Entry> each : mutatorLinebuckets + .entrySet()) { + if (each.getValue().size() > 1) { + checkForInlinedCode(combined, each); + } else { + combined.addAll(each.getValue()); + } + } + + /** FIXME tests rely on order of returned mutants **/ + Collections.sort(combined, compareLineNumbers()); + return combined; + } + + @Override + public void end() { + // no-opp + } + + private static Comparator compareLineNumbers() { + return (arg0, arg1) -> arg0.getLineNumber() - arg1.getLineNumber(); + } + + private void checkForInlinedCode(final Collection combined, + final Entry> each) { + + final List mutationsInHandlerBlock = FCollection + .filter(each.getValue(), isInFinallyHandler()); + if (!isPossibleToCorrectInlining(mutationsInHandlerBlock)) { + combined.addAll(each.getValue()); + return; + } + + final MutationDetails baseMutation = mutationsInHandlerBlock.get(0); + final int firstBlock = baseMutation.getBlock(); + + // check that we have at least on mutation in a different block + // to the base one (is this not implied by there being only 1 mutation in + // the handler ????) + final List ids = map(each.getValue(), mutationToBlock()); + if (ids.stream().filter(not(isEqualTo(firstBlock))).findFirst().isPresent()) { + combined.add(makeCombinedMutant(each.getValue())); + } else { + combined.addAll(each.getValue()); + } + } + + private boolean isPossibleToCorrectInlining( + final List mutationsInHandlerBlock) { + if (mutationsInHandlerBlock.size() > 1) { + LOG.warning("Found more than one mutation similar on same line in a finally block. Can't correct for inlining."); + return false; + } + + return !mutationsInHandlerBlock.isEmpty(); + } + + private static Predicate isInFinallyHandler() { + return a -> a.isInFinallyBlock(); + } + + private static MutationDetails makeCombinedMutant( + final Collection value) { + final MutationDetails first = value.iterator().next(); + final Set indexes = new HashSet<>(); + mapTo(value, mutationToIndex(), indexes); + + final MutationIdentifier id = new MutationIdentifier(first.getId() + .getLocation(), indexes, first.getId().getMutator()); + + return new MutationDetails(id, first.getFilename(), first.getDescription(), + first.getLineNumber(), first.getBlock()); + } + + private static Function mutationToIndex() { + return a -> a.getFirstIndex(); + } + + private static Function mutationToBlock() { + return a -> a.getBlock(); + } + + private static Function toLineMutatorPair() { + return a -> new LineMutatorPair(a.getLineNumber(), a.getMutator()); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilterFactory.java index bf09c761d..0c866e377 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilterFactory.java @@ -1,32 +1,32 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import org.pitest.mutationtest.build.CompoundMutationInterceptor; -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class InlinedFinallyBlockFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Inlined finally block filter plugin"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - if (params.data().isDetectInlinedCode()) { - return new InlinedFinallyBlockFilter(); - } - return CompoundMutationInterceptor.nullInterceptor(); - } - - @Override - public Feature provides() { - return Feature.named("FFBLOCK") - .withOnByDefault(true) - .withDescription("Filters mutations in code duplicated by finally block inlining"); - } - - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import org.pitest.mutationtest.build.CompoundMutationInterceptor; +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class InlinedFinallyBlockFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Inlined finally block filter plugin"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + if (params.data().isDetectInlinedCode()) { + return new InlinedFinallyBlockFilter(); + } + return CompoundMutationInterceptor.nullInterceptor(); + } + + @Override + public Feature provides() { + return Feature.named("FFBLOCK") + .withOnByDefault(true) + .withDescription("Filters mutations in code duplicated by finally block inlining"); + } + + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/LineMutatorPair.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/LineMutatorPair.java index b17c3532a..9d49f20d7 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/LineMutatorPair.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/LineMutatorPair.java @@ -1,48 +1,48 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -public class LineMutatorPair { - - private final int lineNumber; - private final String mutator; - - public LineMutatorPair(final int lineNumber, final String mutator) { - this.lineNumber = lineNumber; - this.mutator = mutator; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + this.lineNumber; - result = (prime * result) - + ((this.mutator == null) ? 0 : this.mutator.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final LineMutatorPair other = (LineMutatorPair) obj; - if (this.lineNumber != other.lineNumber) { - return false; - } - if (this.mutator == null) { - if (other.mutator != null) { - return false; - } - } else if (!this.mutator.equals(other.mutator)) { - return false; - } - return true; - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +public class LineMutatorPair { + + private final int lineNumber; + private final String mutator; + + public LineMutatorPair(final int lineNumber, final String mutator) { + this.lineNumber = lineNumber; + this.mutator = mutator; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + this.lineNumber; + result = (prime * result) + + ((this.mutator == null) ? 0 : this.mutator.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final LineMutatorPair other = (LineMutatorPair) obj; + if (this.lineNumber != other.lineNumber) { + return false; + } + if (this.mutator == null) { + if (other.mutator != null) { + return false; + } + } else if (!this.mutator.equals(other.mutator)) { + return false; + } + return true; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilter.java index bfa980923..cf62f30d8 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilter.java @@ -1,53 +1,53 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Predicate; - -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -public class TryWithResourcesFilter implements MutationInterceptor { - - private Set lines; - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.lines = new HashSet<>(); - for (final MethodTree each : clazz.methods()) { - checkMehod(each,this.lines); - } - } - - private void checkMehod(MethodTree each, Set lines) { - each.rawNode().accept(new TryWithResourcesMethodVisitor(lines)); - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isOnMarkedLine())); - } - - private Predicate isOnMarkedLine() { - return a -> TryWithResourcesFilter.this.lines.contains(a.getClassLine().getLineNumber()); - } - - @Override - public void end() { - - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Predicate; + +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +public class TryWithResourcesFilter implements MutationInterceptor { + + private Set lines; + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.lines = new HashSet<>(); + for (final MethodTree each : clazz.methods()) { + checkMehod(each,this.lines); + } + } + + private void checkMehod(MethodTree each, Set lines) { + each.rawNode().accept(new TryWithResourcesMethodVisitor(lines)); + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isOnMarkedLine())); + } + + private Predicate isOnMarkedLine() { + return a -> TryWithResourcesFilter.this.lines.contains(a.getClassLine().getLineNumber()); + } + + @Override + public void end() { + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilterFactory.java index 421893978..a58f7ea9a 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilterFactory.java @@ -1,27 +1,27 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class TryWithResourcesFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Try with resources filter"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new TryWithResourcesFilter(); - } - - @Override - public Feature provides() { - return Feature.named("FTRYWR") - .withOnByDefault(true) - .withDescription("Filters mutations in code generated for try with resources statements"); - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class TryWithResourcesFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Try with resources filter"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new TryWithResourcesFilter(); + } + + @Override + public Feature provides() { + return Feature.named("FTRYWR") + .withOnByDefault(true) + .withDescription("Filters mutations in code generated for try with resources statements"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesMethodVisitor.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesMethodVisitor.java index 270710a59..94d7a1fea 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesMethodVisitor.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesMethodVisitor.java @@ -1,228 +1,228 @@ -/* - * Copyright 2014 Artem Khvastunov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.objectweb.asm.Opcodes.ALOAD; -import static org.objectweb.asm.Opcodes.ASTORE; -import static org.objectweb.asm.Opcodes.ATHROW; -import static org.objectweb.asm.Opcodes.GOTO; -import static org.objectweb.asm.Opcodes.IFNONNULL; -import static org.objectweb.asm.Opcodes.IFNULL; -import static org.objectweb.asm.Opcodes.IF_ACMPEQ; -import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; -import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -/** - * Example of code that was generated by 1.7 compiler for try-with-resources - * block: - * - *
- * 
- * } finally {
- *   if (closeable != null) { // IFNULL
- *     if (localThrowable2 != null) { // IFNULL
- *       try {
- *         closeable.close(); // INVOKEVIRTUAL or INVOKEINTERFACE
- *       } catch (Throwable x2) {
- *         localThrowable2.addSuppressed(x2); // INVOKEVIRTUAL
- *       }
- *     } else {
- *       closeable.close(); // INVOKEVIRTUAL or INVOKEINTERFACE
- *     }
- *   }
- * } // ATHROW
- * 
- * 
- * - * This class considers that only auto generated code may have such sequence - * without any line change. Such an approach make sense only for javac - * compiler. - *

- * Eclipse Java Compiler as well as aspectj - * have its own opinion how to compile try-with-resources block: - * - *

- * 
- * } finally {
- *   if (throwable1 == null) { // IFNONNULL
- *     throwable1 = throwable2;
- *   } else {
- *     if (throwable1 != throwable2) { // IF_ACMPEQ
- *       throwable1.addSuppressed(throwable2); // INVOKEVIRTUAL
- *     }
- *   }
- * } // ATHROW
- * 
- * 
- * - * @author Artem Khvastunov <contact@artspb.me> - */ -class TryWithResourcesMethodVisitor extends MethodVisitor { - - private static final List JAVAC_CLASS_INS_SEQUENCE = Arrays - .asList( - ASTORE, // store - // throwable - ALOAD, - IFNULL, // closeable - // != - // null - ALOAD, - IFNULL, // localThrowable2 - // != - // null - ALOAD, - INVOKEVIRTUAL, - GOTO, // closeable.close() - ASTORE, // Throwable - // x2 - ALOAD, - ALOAD, - INVOKEVIRTUAL, - GOTO, // localThrowable2.addSuppressed(x2) - ALOAD, - INVOKEVIRTUAL, // closeable.close() - ALOAD, - ATHROW); // throw - // throwable - - private static final List JAVAC_INTERFACE_INS_SEQUENCE = Arrays - .asList( - ASTORE, // store - // throwable - ALOAD, - IFNULL, // closeable - // != - // null - ALOAD, - IFNULL, // localThrowable2 - // != - // null - ALOAD, - INVOKEINTERFACE, - GOTO, // closeable.close() - ASTORE, // Throwable - // x2 - ALOAD, - ALOAD, - INVOKEVIRTUAL, - GOTO, // localThrowable2.addSuppressed(x2) - ALOAD, - INVOKEINTERFACE, // closeable.close() - ALOAD, - ATHROW); // throw - // throwable - - private static final List ECJ_INS_SEQUENCE = Arrays - .asList( - ASTORE, // store - // throwable2 - ALOAD, - IFNONNULL, // if - // (throwable1 - // == - // null) - ALOAD, - ASTORE, - GOTO, // throwable1 - // = - // throwable2; - ALOAD, - ALOAD, - IF_ACMPEQ, // if - // (throwable1 - // != - // throwable2) - // { - ALOAD, - ALOAD, - INVOKEVIRTUAL, // throwable1.addSuppressed(throwable2) - ALOAD, - ATHROW); // throw - // throwable1 - - private final Set lines; - - private final List opcodesStack = new ArrayList<>(); - private int currentLineNumber; - - /** - * @param context - * to store detected line numbers - */ - TryWithResourcesMethodVisitor(final Set lines) { - super(Opcodes.ASM6); - this.lines = lines; - } - - @Override - public void visitLineNumber(int line, Label start) { - prepareToStartTracking(); - this.currentLineNumber = line; - super.visitLineNumber(line, start); - } - - @Override - public void visitVarInsn(int opcode, int var) { - this.opcodesStack.add(opcode); - super.visitVarInsn(opcode, var); - } - - @Override - public void visitJumpInsn(int opcode, Label label) { - this.opcodesStack.add(opcode); - super.visitJumpInsn(opcode, label); - } - - @Override - public void visitMethodInsn(int opcode, String owner, String name, - String desc, boolean itf) { - this.opcodesStack.add(opcode); - super.visitMethodInsn(opcode, owner, name, desc, itf); - } - - @Override - public void visitInsn(int opcode) { - if (opcode == Opcodes.ATHROW) { - this.opcodesStack.add(opcode); - finishTracking(); - } - super.visitInsn(opcode); - } - - private void finishTracking() { - if (JAVAC_CLASS_INS_SEQUENCE.equals(this.opcodesStack) - || JAVAC_INTERFACE_INS_SEQUENCE.equals(this.opcodesStack) - || ECJ_INS_SEQUENCE.equals(this.opcodesStack)) { - this.lines.add(this.currentLineNumber); - } - prepareToStartTracking(); - } - - private void prepareToStartTracking() { - if (!this.opcodesStack.isEmpty()) { - this.opcodesStack.clear(); - } - } -} +/* + * Copyright 2014 Artem Khvastunov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ASTORE; +import static org.objectweb.asm.Opcodes.ATHROW; +import static org.objectweb.asm.Opcodes.GOTO; +import static org.objectweb.asm.Opcodes.IFNONNULL; +import static org.objectweb.asm.Opcodes.IFNULL; +import static org.objectweb.asm.Opcodes.IF_ACMPEQ; +import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; +import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Example of code that was generated by 1.7 compiler for try-with-resources + * block: + * + *
+ * 
+ * } finally {
+ *   if (closeable != null) { // IFNULL
+ *     if (localThrowable2 != null) { // IFNULL
+ *       try {
+ *         closeable.close(); // INVOKEVIRTUAL or INVOKEINTERFACE
+ *       } catch (Throwable x2) {
+ *         localThrowable2.addSuppressed(x2); // INVOKEVIRTUAL
+ *       }
+ *     } else {
+ *       closeable.close(); // INVOKEVIRTUAL or INVOKEINTERFACE
+ *     }
+ *   }
+ * } // ATHROW
+ * 
+ * 
+ * + * This class considers that only auto generated code may have such sequence + * without any line change. Such an approach make sense only for javac + * compiler. + *

+ * Eclipse Java Compiler as well as aspectj + * have its own opinion how to compile try-with-resources block: + * + *

+ * 
+ * } finally {
+ *   if (throwable1 == null) { // IFNONNULL
+ *     throwable1 = throwable2;
+ *   } else {
+ *     if (throwable1 != throwable2) { // IF_ACMPEQ
+ *       throwable1.addSuppressed(throwable2); // INVOKEVIRTUAL
+ *     }
+ *   }
+ * } // ATHROW
+ * 
+ * 
+ * + * @author Artem Khvastunov <contact@artspb.me> + */ +class TryWithResourcesMethodVisitor extends MethodVisitor { + + private static final List JAVAC_CLASS_INS_SEQUENCE = Arrays + .asList( + ASTORE, // store + // throwable + ALOAD, + IFNULL, // closeable + // != + // null + ALOAD, + IFNULL, // localThrowable2 + // != + // null + ALOAD, + INVOKEVIRTUAL, + GOTO, // closeable.close() + ASTORE, // Throwable + // x2 + ALOAD, + ALOAD, + INVOKEVIRTUAL, + GOTO, // localThrowable2.addSuppressed(x2) + ALOAD, + INVOKEVIRTUAL, // closeable.close() + ALOAD, + ATHROW); // throw + // throwable + + private static final List JAVAC_INTERFACE_INS_SEQUENCE = Arrays + .asList( + ASTORE, // store + // throwable + ALOAD, + IFNULL, // closeable + // != + // null + ALOAD, + IFNULL, // localThrowable2 + // != + // null + ALOAD, + INVOKEINTERFACE, + GOTO, // closeable.close() + ASTORE, // Throwable + // x2 + ALOAD, + ALOAD, + INVOKEVIRTUAL, + GOTO, // localThrowable2.addSuppressed(x2) + ALOAD, + INVOKEINTERFACE, // closeable.close() + ALOAD, + ATHROW); // throw + // throwable + + private static final List ECJ_INS_SEQUENCE = Arrays + .asList( + ASTORE, // store + // throwable2 + ALOAD, + IFNONNULL, // if + // (throwable1 + // == + // null) + ALOAD, + ASTORE, + GOTO, // throwable1 + // = + // throwable2; + ALOAD, + ALOAD, + IF_ACMPEQ, // if + // (throwable1 + // != + // throwable2) + // { + ALOAD, + ALOAD, + INVOKEVIRTUAL, // throwable1.addSuppressed(throwable2) + ALOAD, + ATHROW); // throw + // throwable1 + + private final Set lines; + + private final List opcodesStack = new ArrayList<>(); + private int currentLineNumber; + + /** + * @param context + * to store detected line numbers + */ + TryWithResourcesMethodVisitor(final Set lines) { + super(Opcodes.ASM6); + this.lines = lines; + } + + @Override + public void visitLineNumber(int line, Label start) { + prepareToStartTracking(); + this.currentLineNumber = line; + super.visitLineNumber(line, start); + } + + @Override + public void visitVarInsn(int opcode, int var) { + this.opcodesStack.add(opcode); + super.visitVarInsn(opcode, var); + } + + @Override + public void visitJumpInsn(int opcode, Label label) { + this.opcodesStack.add(opcode); + super.visitJumpInsn(opcode, label); + } + + @Override + public void visitMethodInsn(int opcode, String owner, String name, + String desc, boolean itf) { + this.opcodesStack.add(opcode); + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + + @Override + public void visitInsn(int opcode) { + if (opcode == Opcodes.ATHROW) { + this.opcodesStack.add(opcode); + finishTracking(); + } + super.visitInsn(opcode); + } + + private void finishTracking() { + if (JAVAC_CLASS_INS_SEQUENCE.equals(this.opcodesStack) + || JAVAC_INTERFACE_INS_SEQUENCE.equals(this.opcodesStack) + || ECJ_INS_SEQUENCE.equals(this.opcodesStack)) { + this.lines.add(this.currentLineNumber); + } + prepareToStartTracking(); + } + + private void prepareToStartTracking() { + if (!this.opcodesStack.isEmpty()) { + this.opcodesStack.clear(); + } + } +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilter.java index 37b06494c..0f14bb9c2 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilter.java @@ -1,53 +1,53 @@ -package org.pitest.mutationtest.build.intercept.kotlin; - -import java.util.Collection; -import java.util.function.Predicate; - -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -/** - * Quick dirty hack to filter out some of the junk mutations - * created for kotlin classes. These are mutations in autogenerated - * methods not created by the programmer, such as the copy method - * in data classes. - * - * For the amount assume that anything on line 0 of a kotlin class - * is autogenerated. This won't catch everything and will probably - * sometimes trigger when it shouldn't, but overall is a big - * improvement for very little effort. - * - */ -public class KotlinFilter implements MutationInterceptor { - - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isKotlinJunkMutation())); - } - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - // noop - } - - @Override - public void end() { - // noop - } - - private static Predicate isKotlinJunkMutation() { - return a -> a.getFilename().toLowerCase().endsWith(".kt") && (a.getLineNumber() == 0); - } -} +package org.pitest.mutationtest.build.intercept.kotlin; + +import java.util.Collection; +import java.util.function.Predicate; + +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +/** + * Quick dirty hack to filter out some of the junk mutations + * created for kotlin classes. These are mutations in autogenerated + * methods not created by the programmer, such as the copy method + * in data classes. + * + * For the amount assume that anything on line 0 of a kotlin class + * is autogenerated. This won't catch everything and will probably + * sometimes trigger when it shouldn't, but overall is a big + * improvement for very little effort. + * + */ +public class KotlinFilter implements MutationInterceptor { + + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isKotlinJunkMutation())); + } + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + // noop + } + + @Override + public void end() { + // noop + } + + private static Predicate isKotlinJunkMutation() { + return a -> a.getFilename().toLowerCase().endsWith(".kt") && (a.getLineNumber() == 0); + } +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterFactory.java index 401e66aef..eb087f3e6 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterFactory.java @@ -1,27 +1,27 @@ -package org.pitest.mutationtest.build.intercept.kotlin; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class KotlinFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Kotlin junk mutations filter"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new KotlinFilter(); - } - - @Override - public Feature provides() { - return Feature.named("FKOTLIN") - .withDescription("Filters out junk mutations in bytecode created by compiler for kotlin language features") - .withOnByDefault(true); - } - -} +package org.pitest.mutationtest.build.intercept.kotlin; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class KotlinFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Kotlin junk mutations filter"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new KotlinFilter(); + } + + @Override + public Feature provides() { + return Feature.named("FKOTLIN") + .withDescription("Filters out junk mutations in bytecode created by compiler for kotlin language features") + .withOnByDefault(true); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilter.java index b74abbf03..a91944a65 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilter.java @@ -1,97 +1,97 @@ -package org.pitest.mutationtest.build.intercept.logging; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -public class LoggingCallsFilter implements MutationInterceptor { - - private final Set loggingClasses = new HashSet<>(); - private Set lines; - - public LoggingCallsFilter(Collection loggingClasses) { - FCollection.mapTo(loggingClasses, correctFormat(), this.loggingClasses); - } - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.lines = new HashSet<>(); - for (final MethodTree each : clazz.methods()) { - findLoggingLines(each,this.lines); - } - } - - private void findLoggingLines(MethodTree each, Set lines) { - each.rawNode().accept(new LoggingLineScanner(lines, this.loggingClasses)); - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isOnLoggingLine())); - } - - private Predicate isOnLoggingLine() { - return a -> LoggingCallsFilter.this.lines.contains(a.getClassLine().getLineNumber()); - } - - @Override - public void end() { - this.lines = null; - } - - private static Function correctFormat() { - return a -> a.replace('.', '/'); - } - -} - -class LoggingLineScanner extends MethodVisitor { - - private final Set lines; - private final Set loggingClasses; - private int currentLineNumber; - - LoggingLineScanner(final Set lines, final Set loggingClasses) { - super(Opcodes.ASM6); - this.lines = lines; - this.loggingClasses = loggingClasses; - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, - final String name, final String desc, boolean itf) { - if (FCollection.contains(this.loggingClasses, matches(owner))) { - this.lines.add(this.currentLineNumber); - } - } - - private static Predicate matches(final String owner) { - return a -> owner.startsWith(a); - } - - @Override - public void visitLineNumber(final int line, final Label start) { - this.currentLineNumber = line; - } - -} +package org.pitest.mutationtest.build.intercept.logging; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +public class LoggingCallsFilter implements MutationInterceptor { + + private final Set loggingClasses = new HashSet<>(); + private Set lines; + + public LoggingCallsFilter(Collection loggingClasses) { + FCollection.mapTo(loggingClasses, correctFormat(), this.loggingClasses); + } + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.lines = new HashSet<>(); + for (final MethodTree each : clazz.methods()) { + findLoggingLines(each,this.lines); + } + } + + private void findLoggingLines(MethodTree each, Set lines) { + each.rawNode().accept(new LoggingLineScanner(lines, this.loggingClasses)); + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isOnLoggingLine())); + } + + private Predicate isOnLoggingLine() { + return a -> LoggingCallsFilter.this.lines.contains(a.getClassLine().getLineNumber()); + } + + @Override + public void end() { + this.lines = null; + } + + private static Function correctFormat() { + return a -> a.replace('.', '/'); + } + +} + +class LoggingLineScanner extends MethodVisitor { + + private final Set lines; + private final Set loggingClasses; + private int currentLineNumber; + + LoggingLineScanner(final Set lines, final Set loggingClasses) { + super(Opcodes.ASM6); + this.lines = lines; + this.loggingClasses = loggingClasses; + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, + final String name, final String desc, boolean itf) { + if (FCollection.contains(this.loggingClasses, matches(owner))) { + this.lines.add(this.currentLineNumber); + } + } + + private static Predicate matches(final String owner) { + return a -> owner.startsWith(a); + } + + @Override + public void visitLineNumber(final int line, final Label start) { + this.currentLineNumber = line; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilterFactory.java index 7ab046fb3..02121ad91 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilterFactory.java @@ -1,27 +1,27 @@ -package org.pitest.mutationtest.build.intercept.logging; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class LoggingCallsFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Logging calls filter"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new LoggingCallsFilter(params.data().getLoggingClasses()); - } - - @Override - public Feature provides() { - return Feature.named("FLOGCALL") - .withOnByDefault(true) - .withDescription("Filters mutations in code that makes calls to logging frameworks"); - } - -} +package org.pitest.mutationtest.build.intercept.logging; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class LoggingCallsFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Logging calls filter"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new LoggingCallsFilter(params.data().getLoggingClasses()); + } + + @Override + public Feature provides() { + return Feature.named("FLOGCALL") + .withOnByDefault(true) + .withDescription("Filters mutations in code that makes calls to logging frameworks"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilter.java index 8ec40dc05..9ead68321 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilter.java @@ -1,41 +1,41 @@ -package org.pitest.mutationtest.build.intercept.staticinitializers; - -import java.util.Collection; -import java.util.function.Predicate; - -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -class StaticInitializerFilter implements MutationInterceptor { - - @Override - public void begin(ClassTree clazz) { - // noop - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(isInStaticInitCode())); - } - - private Predicate isInStaticInitCode() { - return a -> a.isInStaticInitializer(); - } - - @Override - public void end() { - // noop - } - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - -} +package org.pitest.mutationtest.build.intercept.staticinitializers; + +import java.util.Collection; +import java.util.function.Predicate; + +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +class StaticInitializerFilter implements MutationInterceptor { + + @Override + public void begin(ClassTree clazz) { + // noop + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(isInStaticInitCode())); + } + + private Predicate isInStaticInitCode() { + return a -> a.isInStaticInitializer(); + } + + @Override + public void end() { + // noop + } + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilterFactory.java index a8886f91d..2e1d98773 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilterFactory.java @@ -1,27 +1,27 @@ -package org.pitest.mutationtest.build.intercept.staticinitializers; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class StaticInitializerFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Static initializer filter plugin"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new StaticInitializerFilter(); - } - - @Override - public Feature provides() { - return Feature.named("FSTATINIT") - .withOnByDefault(true) - .withDescription("Filters mutations in static initializers and code called only from them"); - } - -} +package org.pitest.mutationtest.build.intercept.staticinitializers; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class StaticInitializerFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Static initializer filter plugin"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new StaticInitializerFilter(); + } + + @Override + public Feature provides() { + return Feature.named("FSTATINIT") + .withOnByDefault(true) + .withDescription("Filters mutations in static initializers and code called only from them"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptor.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptor.java index 548ad6e7f..30826a09b 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptor.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptor.java @@ -1,153 +1,153 @@ -package org.pitest.mutationtest.build.intercept.staticinitializers; - -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.pitest.bytecode.analysis.AnalysisFunctions; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.classinfo.ClassName; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.PoisonStatus; - -/** - * Identifies and marks mutations in code that is active during class - * Initialisation. - * - * The analysis is simplistic and non-exhaustive. Code is considered to be - * for static initialisation if it is - * - * 1. In a static initializer (i.e ) - * 2. In a private static method called directly from - * - * TODO A better analysis would include private static methods called indirectly from - * and would exclude methods called from location other than . - * - */ -class StaticInitializerInterceptor implements MutationInterceptor { - - private static final MethodName CLINIT = MethodName.fromString(""); - - private Predicate isStaticInitCode; - - @Override - public void begin(ClassTree clazz) { - analyseClass(clazz); - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - if (this.isStaticInitCode != null) { - final List altered = - mutations.stream() - .filter(this.isStaticInitCode) - .map(setStaticInitializerFlag()) - .collect(Collectors.toList()); - - final List notAltered = - FCollection.filter(mutations, Prelude.not(this.isStaticInitCode)); - - notAltered.addAll(altered); - return notAltered; - } - return mutations; - } - - @Override - public void end() { - this.isStaticInitCode = null; - } - - private void analyseClass(ClassTree tree) { - final Optional clinit = tree.methods().stream().filter(nameEquals(CLINIT.name())).findFirst(); - - if (clinit.isPresent()) { - final List> selfCalls = - clinit.get().instructions().stream() - .flatMap(is(MethodInsnNode.class)) - .filter(calls(tree.name())) - .map(toPredicate()) - .collect(Collectors.toList()); - - final Predicate matchingCalls = Prelude.or(selfCalls); - - final Predicate initOnlyMethods = Prelude.or(tree.methods().stream() - .filter(isPrivateStatic()) - .filter(matchingCalls) - .map(AnalysisFunctions.matchMutationsInMethod()) - .collect(Collectors.toList()) - ); - - this.isStaticInitCode = Prelude.or(isInStaticInitializer(), initOnlyMethods); - } - } - - - private static Predicate isInStaticInitializer() { - return a -> a.getId().getLocation().getMethodName().equals(CLINIT); - } - - private static Predicate isPrivateStatic() { - return a -> ((a.rawNode().access & Opcodes.ACC_STATIC) != 0) - && ((a.rawNode().access & Opcodes.ACC_PRIVATE) != 0); - } - - - - private static Function> toPredicate() { - return a -> matchesCall(a); - } - - - private static Predicate matchesCall(final MethodInsnNode call) { - return a -> a.rawNode().name.equals(call.name) - && a.rawNode().desc.equals(call.desc); - } - - private Predicate calls(final ClassName self) { - return a -> a.owner.equals(self.asInternalName()); - } - - private Function> is(final Class clazz) { - return new Function>() { - @SuppressWarnings("unchecked") - @Override - public Stream apply(AbstractInsnNode a) { - if (a.getClass().isAssignableFrom(clazz)) { - return Stream.of((T)a); - } - return Stream.empty(); - } - }; - } - - private Predicate nameEquals(final String name) { - return a -> a.rawNode().name.equals(name); - } - - - private Function setStaticInitializerFlag() { - return a -> a.withPoisonStatus(PoisonStatus.IS_STATIC_INITIALIZER_CODE); - } - - @Override - public InterceptorType type() { - return InterceptorType.MODIFY; - } - -} +package org.pitest.mutationtest.build.intercept.staticinitializers; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.pitest.bytecode.analysis.AnalysisFunctions; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.classinfo.ClassName; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.PoisonStatus; + +/** + * Identifies and marks mutations in code that is active during class + * Initialisation. + * + * The analysis is simplistic and non-exhaustive. Code is considered to be + * for static initialisation if it is + * + * 1. In a static initializer (i.e ) + * 2. In a private static method called directly from + * + * TODO A better analysis would include private static methods called indirectly from + * and would exclude methods called from location other than . + * + */ +class StaticInitializerInterceptor implements MutationInterceptor { + + private static final MethodName CLINIT = MethodName.fromString(""); + + private Predicate isStaticInitCode; + + @Override + public void begin(ClassTree clazz) { + analyseClass(clazz); + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + if (this.isStaticInitCode != null) { + final List altered = + mutations.stream() + .filter(this.isStaticInitCode) + .map(setStaticInitializerFlag()) + .collect(Collectors.toList()); + + final List notAltered = + FCollection.filter(mutations, Prelude.not(this.isStaticInitCode)); + + notAltered.addAll(altered); + return notAltered; + } + return mutations; + } + + @Override + public void end() { + this.isStaticInitCode = null; + } + + private void analyseClass(ClassTree tree) { + final Optional clinit = tree.methods().stream().filter(nameEquals(CLINIT.name())).findFirst(); + + if (clinit.isPresent()) { + final List> selfCalls = + clinit.get().instructions().stream() + .flatMap(is(MethodInsnNode.class)) + .filter(calls(tree.name())) + .map(toPredicate()) + .collect(Collectors.toList()); + + final Predicate matchingCalls = Prelude.or(selfCalls); + + final Predicate initOnlyMethods = Prelude.or(tree.methods().stream() + .filter(isPrivateStatic()) + .filter(matchingCalls) + .map(AnalysisFunctions.matchMutationsInMethod()) + .collect(Collectors.toList()) + ); + + this.isStaticInitCode = Prelude.or(isInStaticInitializer(), initOnlyMethods); + } + } + + + private static Predicate isInStaticInitializer() { + return a -> a.getId().getLocation().getMethodName().equals(CLINIT); + } + + private static Predicate isPrivateStatic() { + return a -> ((a.rawNode().access & Opcodes.ACC_STATIC) != 0) + && ((a.rawNode().access & Opcodes.ACC_PRIVATE) != 0); + } + + + + private static Function> toPredicate() { + return a -> matchesCall(a); + } + + + private static Predicate matchesCall(final MethodInsnNode call) { + return a -> a.rawNode().name.equals(call.name) + && a.rawNode().desc.equals(call.desc); + } + + private Predicate calls(final ClassName self) { + return a -> a.owner.equals(self.asInternalName()); + } + + private Function> is(final Class clazz) { + return new Function>() { + @SuppressWarnings("unchecked") + @Override + public Stream apply(AbstractInsnNode a) { + if (a.getClass().isAssignableFrom(clazz)) { + return Stream.of((T)a); + } + return Stream.empty(); + } + }; + } + + private Predicate nameEquals(final String name) { + return a -> a.rawNode().name.equals(name); + } + + + private Function setStaticInitializerFlag() { + return a -> a.withPoisonStatus(PoisonStatus.IS_STATIC_INITIALIZER_CODE); + } + + @Override + public InterceptorType type() { + return InterceptorType.MODIFY; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptorFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptorFactory.java index afcaac29a..292bae6dd 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptorFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptorFactory.java @@ -1,26 +1,26 @@ -package org.pitest.mutationtest.build.intercept.staticinitializers; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class StaticInitializerInterceptorFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Static initializer code detector plugin"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new StaticInitializerInterceptor(); - } - - @Override - public Feature provides() { - return Feature.named("FSTATI") - .withOnByDefault(true) - .withDescription("Filters mutations in static initializers and code called only from them"); - } -} +package org.pitest.mutationtest.build.intercept.staticinitializers; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class StaticInitializerInterceptorFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Static initializer code detector plugin"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new StaticInitializerInterceptor(); + } + + @Override + public Feature provides() { + return Feature.named("FSTATI") + .withOnByDefault(true) + .withDescription("Filters mutations in static initializers and code called only from them"); + } +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCounterFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCounterFilter.java index f2bf2898d..6d42c05e4 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCounterFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCounterFilter.java @@ -1,173 +1,173 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJump; -import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJumpTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; -import static org.pitest.bytecode.analysis.InstructionMatchers.anILoadOf; -import static org.pitest.bytecode.analysis.InstructionMatchers.anIStore; -import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.debug; -import static org.pitest.bytecode.analysis.InstructionMatchers.gotoLabel; -import static org.pitest.bytecode.analysis.InstructionMatchers.incrementsVariable; -import static org.pitest.bytecode.analysis.InstructionMatchers.isA; -import static org.pitest.bytecode.analysis.InstructionMatchers.isInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.jumpsTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.labelNode; -import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; - -import java.util.Collection; -import java.util.function.Predicate; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.LineNumberNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodMatchers; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.sequence.Context; -import org.pitest.sequence.Match; -import org.pitest.sequence.QueryParams; -import org.pitest.sequence.QueryStart; -import org.pitest.sequence.SequenceMatcher; -import org.pitest.sequence.SequenceQuery; -import org.pitest.sequence.Slot; - -/** - * Removes mutants that affect for loop counters as these have - * a high chance of timing out. - */ -public class AvoidForLoopCounterFilter implements MutationInterceptor { - - private static final boolean DEBUG = false; - - // GETFIELDS are ignored so field access can be matched in the same way as local variables - private static final Match IGNORE = isA(LineNumberNode.class) - .or(isA(FrameNode.class) - .or(opCode(Opcodes.GETFIELD)) - ); - - private static final Slot MUTATED_INSTRUCTION = Slot.create(AbstractInsnNode.class); - - static final SequenceMatcher MUTATED_FOR_COUNTER = QueryStart - .match(Match.never()) - .or(conditionalAtEnd()) - .or(conditionalAtStart()) - .compile(QueryParams.params(AbstractInsnNode.class) - .withIgnores(IGNORE) - .withDebug(DEBUG) - ); - - - private ClassTree currentClass; - - - private static SequenceQuery conditionalAtEnd() { - final Slot counterVariable = Slot.create(Integer.class); - final Slot loopStart = Slot.create(LabelNode.class); - final Slot loopEnd = Slot.create(LabelNode.class); - return QueryStart - .any(AbstractInsnNode.class) - // .then(anIntegerConstant()) // skip this? - .then(anIStore(counterVariable.write()).and(debug("end_counter"))) - .then(isA(LabelNode.class)) - .then(gotoLabel(loopEnd.write())) - .then(aLabelNode(loopStart.write()).and(debug("loop start"))) - .zeroOrMore(anything()) - .then(targetInstruction(counterVariable).and(debug("target"))) - .then(labelNode(loopEnd.read()).and(debug("loop end"))) - .then(anILoadOf(counterVariable.read()).and(debug("read"))) - .zeroOrMore(anything()) - .then(loadsAnIntegerToCompareTo()) - .then(aConditionalJumpTo(loopStart).and(debug("jump"))) - .zeroOrMore(anything()); - } - - - private static SequenceQuery conditionalAtStart() { - final Slot counterVariable = Slot.create(Integer.class); - final Slot loopStart = Slot.create(LabelNode.class); - final Slot loopEnd = Slot.create(LabelNode.class); - return QueryStart - .any(AbstractInsnNode.class) - // .then(anIntegerConstant().and(debug("constant"))) // skip this? - .then(anIStore(counterVariable.write()).and(debug("store"))) - .then(aLabelNode(loopStart.write()).and(debug("label"))) - .then(anILoadOf(counterVariable.read()).and(debug("load"))) - .zeroOrMore(QueryStart.match(opCode(Opcodes.ALOAD))) // optionally put object on stack - .then(loadsAnIntegerToCompareTo().and(debug("push"))) - .then(jumpsTo(loopEnd.write()).and(aConditionalJump())) - .then(isA(LabelNode.class)) - .zeroOrMore(anything()) - .then(targetInstruction(counterVariable).and(debug("target"))) - .then(jumpsTo(loopStart.read()).and(debug("jump"))) - .then(labelNode(loopEnd.read())) - .zeroOrMore(anything()); - } - - private static Match loadsAnIntegerToCompareTo() { - return opCode(Opcodes.BIPUSH).or(integerMethodCall()).or(arrayLength()); - } - - - private static Match arrayLength() { - return opCode(Opcodes.ARRAYLENGTH); - } - - - private static SequenceQuery anything() { - return QueryStart.match(anyInstruction()); - } - - private static Match integerMethodCall() { - return isA(MethodInsnNode.class); - } - - private static Match targetInstruction(Slot counterVariable) { - return incrementsVariable(counterVariable.read()).and(isInstruction(MUTATED_INSTRUCTION.read())); - } - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - return FCollection.filter(mutations, Prelude.not(mutatesAForLoopCounter())); - } - - private Predicate mutatesAForLoopCounter() { - return a -> { - final int instruction = a.getInstructionIndex(); - final MethodTree method = AvoidForLoopCounterFilter.this.currentClass.methods().stream() - .filter(MethodMatchers.forLocation(a.getId().getLocation())) - .findFirst().get(); - final AbstractInsnNode mutatedInstruction = method.instructions().get(instruction); - - final Context context = Context.start(method.instructions(), DEBUG); - context.store(MUTATED_INSTRUCTION.write(), mutatedInstruction); - return MUTATED_FOR_COUNTER.matches(method.instructions(), context); - }; - } - - @Override - public void end() { - this.currentClass = null; - } - -} +package org.pitest.mutationtest.build.intercept.timeout; + +import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJump; +import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJumpTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; +import static org.pitest.bytecode.analysis.InstructionMatchers.anILoadOf; +import static org.pitest.bytecode.analysis.InstructionMatchers.anIStore; +import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.debug; +import static org.pitest.bytecode.analysis.InstructionMatchers.gotoLabel; +import static org.pitest.bytecode.analysis.InstructionMatchers.incrementsVariable; +import static org.pitest.bytecode.analysis.InstructionMatchers.isA; +import static org.pitest.bytecode.analysis.InstructionMatchers.isInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.jumpsTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.labelNode; +import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; + +import java.util.Collection; +import java.util.function.Predicate; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodMatchers; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.sequence.Context; +import org.pitest.sequence.Match; +import org.pitest.sequence.QueryParams; +import org.pitest.sequence.QueryStart; +import org.pitest.sequence.SequenceMatcher; +import org.pitest.sequence.SequenceQuery; +import org.pitest.sequence.Slot; + +/** + * Removes mutants that affect for loop counters as these have + * a high chance of timing out. + */ +public class AvoidForLoopCounterFilter implements MutationInterceptor { + + private static final boolean DEBUG = false; + + // GETFIELDS are ignored so field access can be matched in the same way as local variables + private static final Match IGNORE = isA(LineNumberNode.class) + .or(isA(FrameNode.class) + .or(opCode(Opcodes.GETFIELD)) + ); + + private static final Slot MUTATED_INSTRUCTION = Slot.create(AbstractInsnNode.class); + + static final SequenceMatcher MUTATED_FOR_COUNTER = QueryStart + .match(Match.never()) + .or(conditionalAtEnd()) + .or(conditionalAtStart()) + .compile(QueryParams.params(AbstractInsnNode.class) + .withIgnores(IGNORE) + .withDebug(DEBUG) + ); + + + private ClassTree currentClass; + + + private static SequenceQuery conditionalAtEnd() { + final Slot counterVariable = Slot.create(Integer.class); + final Slot loopStart = Slot.create(LabelNode.class); + final Slot loopEnd = Slot.create(LabelNode.class); + return QueryStart + .any(AbstractInsnNode.class) + // .then(anIntegerConstant()) // skip this? + .then(anIStore(counterVariable.write()).and(debug("end_counter"))) + .then(isA(LabelNode.class)) + .then(gotoLabel(loopEnd.write())) + .then(aLabelNode(loopStart.write()).and(debug("loop start"))) + .zeroOrMore(anything()) + .then(targetInstruction(counterVariable).and(debug("target"))) + .then(labelNode(loopEnd.read()).and(debug("loop end"))) + .then(anILoadOf(counterVariable.read()).and(debug("read"))) + .zeroOrMore(anything()) + .then(loadsAnIntegerToCompareTo()) + .then(aConditionalJumpTo(loopStart).and(debug("jump"))) + .zeroOrMore(anything()); + } + + + private static SequenceQuery conditionalAtStart() { + final Slot counterVariable = Slot.create(Integer.class); + final Slot loopStart = Slot.create(LabelNode.class); + final Slot loopEnd = Slot.create(LabelNode.class); + return QueryStart + .any(AbstractInsnNode.class) + // .then(anIntegerConstant().and(debug("constant"))) // skip this? + .then(anIStore(counterVariable.write()).and(debug("store"))) + .then(aLabelNode(loopStart.write()).and(debug("label"))) + .then(anILoadOf(counterVariable.read()).and(debug("load"))) + .zeroOrMore(QueryStart.match(opCode(Opcodes.ALOAD))) // optionally put object on stack + .then(loadsAnIntegerToCompareTo().and(debug("push"))) + .then(jumpsTo(loopEnd.write()).and(aConditionalJump())) + .then(isA(LabelNode.class)) + .zeroOrMore(anything()) + .then(targetInstruction(counterVariable).and(debug("target"))) + .then(jumpsTo(loopStart.read()).and(debug("jump"))) + .then(labelNode(loopEnd.read())) + .zeroOrMore(anything()); + } + + private static Match loadsAnIntegerToCompareTo() { + return opCode(Opcodes.BIPUSH).or(integerMethodCall()).or(arrayLength()); + } + + + private static Match arrayLength() { + return opCode(Opcodes.ARRAYLENGTH); + } + + + private static SequenceQuery anything() { + return QueryStart.match(anyInstruction()); + } + + private static Match integerMethodCall() { + return isA(MethodInsnNode.class); + } + + private static Match targetInstruction(Slot counterVariable) { + return incrementsVariable(counterVariable.read()).and(isInstruction(MUTATED_INSTRUCTION.read())); + } + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + return FCollection.filter(mutations, Prelude.not(mutatesAForLoopCounter())); + } + + private Predicate mutatesAForLoopCounter() { + return a -> { + final int instruction = a.getInstructionIndex(); + final MethodTree method = AvoidForLoopCounterFilter.this.currentClass.methods().stream() + .filter(MethodMatchers.forLocation(a.getId().getLocation())) + .findFirst().get(); + final AbstractInsnNode mutatedInstruction = method.instructions().get(instruction); + + final Context context = Context.start(method.instructions(), DEBUG); + context.store(MUTATED_INSTRUCTION.write(), mutatedInstruction); + return MUTATED_FOR_COUNTER.matches(method.instructions(), context); + }; + } + + @Override + public void end() { + this.currentClass = null; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCountersFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCountersFilterFactory.java index 0339c5947..2fe77271a 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCountersFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCountersFilterFactory.java @@ -1,26 +1,26 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class AvoidForLoopCountersFilterFactory implements MutationInterceptorFactory { - @Override - public String description() { - return "For loop counter filter"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new AvoidForLoopCounterFilter(); - } - - @Override - public Feature provides() { - return Feature.named("FFLOOP") - .withOnByDefault(true) - .withDescription("Filters any mutations to increments in for loops as they may cause timeouts"); - } - -} +package org.pitest.mutationtest.build.intercept.timeout; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class AvoidForLoopCountersFilterFactory implements MutationInterceptorFactory { + @Override + public String description() { + return "For loop counter filter"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new AvoidForLoopCounterFilter(); + } + + @Override + public Feature provides() { + return Feature.named("FFLOOP") + .withOnByDefault(true) + .withDescription("Filters any mutations to increments in for loops as they may cause timeouts"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilter.java index b7e327266..c995f9cd5 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilter.java @@ -1,113 +1,113 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJump; -import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; -import static org.pitest.bytecode.analysis.InstructionMatchers.anILoadOf; -import static org.pitest.bytecode.analysis.InstructionMatchers.anIStore; -import static org.pitest.bytecode.analysis.InstructionMatchers.anIStoreTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.anIntegerConstant; -import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.debug; -import static org.pitest.bytecode.analysis.InstructionMatchers.gotoLabel; -import static org.pitest.bytecode.analysis.InstructionMatchers.incrementsVariable; -import static org.pitest.bytecode.analysis.InstructionMatchers.isA; -import static org.pitest.bytecode.analysis.InstructionMatchers.jumpsTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.labelNode; -import static org.pitest.bytecode.analysis.InstructionMatchers.methodCall; -import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.LineNumberNode; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.sequence.Match; -import org.pitest.sequence.QueryParams; -import org.pitest.sequence.QueryStart; -import org.pitest.sequence.SequenceMatcher; -import org.pitest.sequence.SequenceQuery; -import org.pitest.sequence.Slot; - -/** - * Removes mutants that are likely to result in an infinite or long running - * for loop or while loop based on a counter. - */ -public class InfiniteForLoopFilter extends InfiniteLoopFilter { - - private static final boolean DEBUG = false; - - private static final Match IGNORE = isA(LineNumberNode.class).or(isA(FrameNode.class)); - - static final SequenceMatcher INFINITE_LOOP = QueryStart - .match(Match.never()) - .or(countingLoopWithoutWriteConditionalAtStart()) - .or(countingLoopWithoutWriteConditionAtEnd()) - .compile(QueryParams.params(AbstractInsnNode.class) - .withIgnores(IGNORE) - .withDebug(DEBUG) - ); - - @Override - SequenceMatcher infiniteLoopMatcher() { - return INFINITE_LOOP; - } - - @Override - boolean couldCauseInfiniteLoop(MethodTree method, MutationDetails each) { - final AbstractInsnNode instruction = method.instructions().get(each.getInstructionIndex()); - return instruction.getOpcode() == Opcodes.IINC; - } - - private static SequenceQuery countingLoopWithoutWriteConditionalAtStart() { - final Slot counterVariable = Slot.create(Integer.class); - final Slot loopStart = Slot.create(LabelNode.class); - return QueryStart - .any(AbstractInsnNode.class) - .then(anIntegerConstant().and(debug("constant"))) - .zeroOrMore(QueryStart.match(opCode(Opcodes.IADD))) // FIXME just one rather than many - .then(anIStore(counterVariable.write()).and(debug("counter"))) - .zeroOrMore(QueryStart.match(opCode(Opcodes.ILOAD) - .or(opCode(Opcodes.ALOAD) - .or(opCode(Opcodes.ISTORE)) - .or(methodCall())))) - .then(aLabelNode(loopStart.write()).and(debug("label"))) - .then(anILoadOf(counterVariable.read()).and(debug("load"))) - .zeroOrMore(doesNotBreakLoop(counterVariable)) - .zeroOrMore(QueryStart.match(opCode(Opcodes.ILOAD).or(opCode(Opcodes.ALOAD).or(methodCall())))) - .then(aConditionalJump().and(debug("jump"))) - .zeroOrMore(doesNotBreakLoop(counterVariable)) - .then(jumpsTo(loopStart.read())) - .zeroOrMore(QueryStart.match(anyInstruction())); - } - - private static SequenceQuery countingLoopWithoutWriteConditionAtEnd() { - final Slot counterVariable = Slot.create(Integer.class); - final Slot loopStart = Slot.create(LabelNode.class); - final Slot loopEnd = Slot.create(LabelNode.class); - - return QueryStart - .any(AbstractInsnNode.class) - .then(anIntegerConstant()) - .then(anIStore(counterVariable.write()).and(debug("counter"))) - .then(isA(LabelNode.class)) - .then(gotoLabel(loopEnd.write())) - .then(aLabelNode(loopStart.write()).and(debug("loop start"))) - .zeroOrMore(doesNotBreakLoop(counterVariable)) - .then(labelNode(loopEnd.read()).and(debug("loop end"))) - .then(anILoadOf(counterVariable.read()).and(debug("read"))) // is it really important that we read the counter? - .zeroOrMore(doesNotBreakLoop(counterVariable)) - .then(jumpsTo(loopStart.read()).and(debug("jump"))) - .zeroOrMore(QueryStart.match(anyInstruction())); - } - - private static SequenceQuery doesNotBreakLoop(Slot counterVariable) { - return QueryStart - .match(anIStoreTo(counterVariable.read()).and(debug("broken by store")) - .or(incrementsVariable(counterVariable.read())) - .negate()); - } - - -} +package org.pitest.mutationtest.build.intercept.timeout; + +import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJump; +import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; +import static org.pitest.bytecode.analysis.InstructionMatchers.anILoadOf; +import static org.pitest.bytecode.analysis.InstructionMatchers.anIStore; +import static org.pitest.bytecode.analysis.InstructionMatchers.anIStoreTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.anIntegerConstant; +import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.debug; +import static org.pitest.bytecode.analysis.InstructionMatchers.gotoLabel; +import static org.pitest.bytecode.analysis.InstructionMatchers.incrementsVariable; +import static org.pitest.bytecode.analysis.InstructionMatchers.isA; +import static org.pitest.bytecode.analysis.InstructionMatchers.jumpsTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.labelNode; +import static org.pitest.bytecode.analysis.InstructionMatchers.methodCall; +import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.sequence.Match; +import org.pitest.sequence.QueryParams; +import org.pitest.sequence.QueryStart; +import org.pitest.sequence.SequenceMatcher; +import org.pitest.sequence.SequenceQuery; +import org.pitest.sequence.Slot; + +/** + * Removes mutants that are likely to result in an infinite or long running + * for loop or while loop based on a counter. + */ +public class InfiniteForLoopFilter extends InfiniteLoopFilter { + + private static final boolean DEBUG = false; + + private static final Match IGNORE = isA(LineNumberNode.class).or(isA(FrameNode.class)); + + static final SequenceMatcher INFINITE_LOOP = QueryStart + .match(Match.never()) + .or(countingLoopWithoutWriteConditionalAtStart()) + .or(countingLoopWithoutWriteConditionAtEnd()) + .compile(QueryParams.params(AbstractInsnNode.class) + .withIgnores(IGNORE) + .withDebug(DEBUG) + ); + + @Override + SequenceMatcher infiniteLoopMatcher() { + return INFINITE_LOOP; + } + + @Override + boolean couldCauseInfiniteLoop(MethodTree method, MutationDetails each) { + final AbstractInsnNode instruction = method.instructions().get(each.getInstructionIndex()); + return instruction.getOpcode() == Opcodes.IINC; + } + + private static SequenceQuery countingLoopWithoutWriteConditionalAtStart() { + final Slot counterVariable = Slot.create(Integer.class); + final Slot loopStart = Slot.create(LabelNode.class); + return QueryStart + .any(AbstractInsnNode.class) + .then(anIntegerConstant().and(debug("constant"))) + .zeroOrMore(QueryStart.match(opCode(Opcodes.IADD))) // FIXME just one rather than many + .then(anIStore(counterVariable.write()).and(debug("counter"))) + .zeroOrMore(QueryStart.match(opCode(Opcodes.ILOAD) + .or(opCode(Opcodes.ALOAD) + .or(opCode(Opcodes.ISTORE)) + .or(methodCall())))) + .then(aLabelNode(loopStart.write()).and(debug("label"))) + .then(anILoadOf(counterVariable.read()).and(debug("load"))) + .zeroOrMore(doesNotBreakLoop(counterVariable)) + .zeroOrMore(QueryStart.match(opCode(Opcodes.ILOAD).or(opCode(Opcodes.ALOAD).or(methodCall())))) + .then(aConditionalJump().and(debug("jump"))) + .zeroOrMore(doesNotBreakLoop(counterVariable)) + .then(jumpsTo(loopStart.read())) + .zeroOrMore(QueryStart.match(anyInstruction())); + } + + private static SequenceQuery countingLoopWithoutWriteConditionAtEnd() { + final Slot counterVariable = Slot.create(Integer.class); + final Slot loopStart = Slot.create(LabelNode.class); + final Slot loopEnd = Slot.create(LabelNode.class); + + return QueryStart + .any(AbstractInsnNode.class) + .then(anIntegerConstant()) + .then(anIStore(counterVariable.write()).and(debug("counter"))) + .then(isA(LabelNode.class)) + .then(gotoLabel(loopEnd.write())) + .then(aLabelNode(loopStart.write()).and(debug("loop start"))) + .zeroOrMore(doesNotBreakLoop(counterVariable)) + .then(labelNode(loopEnd.read()).and(debug("loop end"))) + .then(anILoadOf(counterVariable.read()).and(debug("read"))) // is it really important that we read the counter? + .zeroOrMore(doesNotBreakLoop(counterVariable)) + .then(jumpsTo(loopStart.read()).and(debug("jump"))) + .zeroOrMore(QueryStart.match(anyInstruction())); + } + + private static SequenceQuery doesNotBreakLoop(Slot counterVariable) { + return QueryStart + .match(anIStoreTo(counterVariable.read()).and(debug("broken by store")) + .or(incrementsVariable(counterVariable.read())) + .negate()); + } + + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilterFactory.java index 443ef3639..a73c26adb 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilterFactory.java @@ -1,27 +1,27 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class InfiniteForLoopFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Infinite for loop filter"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new InfiniteForLoopFilter(); - } - - @Override - public Feature provides() { - return Feature.named("FINFINC") - .withOnByDefault(true) - .withDescription("Filters mutations to increments that may cause infinite loops"); - } - -} +package org.pitest.mutationtest.build.intercept.timeout; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class InfiniteForLoopFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Infinite for loop filter"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new InfiniteForLoopFilter(); + } + + @Override + public Feature provides() { + return Feature.named("FINFINC") + .withOnByDefault(true) + .withDescription("Filters mutations to increments that may cause infinite loops"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilter.java index 214e1eba5..cc80dc25d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilter.java @@ -1,94 +1,94 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import static org.pitest.bytecode.analysis.InstructionMatchers.aJump; -import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; -import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.jumpsTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallThatReturns; -import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; - -import java.util.Iterator; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.LabelNode; -import org.pitest.bytecode.analysis.InstructionMatchers; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.sequence.Match; -import org.pitest.sequence.QueryParams; -import org.pitest.sequence.QueryStart; -import org.pitest.sequence.SequenceMatcher; -import org.pitest.sequence.SequenceQuery; -import org.pitest.sequence.Slot; - -/** - * Removes mutants that remove the only call to next in an iterator loop - */ -public class InfiniteIteratorLoopFilter extends InfiniteLoopFilter { - - private static final boolean DEBUG = false; - - static final SequenceMatcher INFINITE_LOOP = QueryStart - .match(Match.never()) - .or(inifniteIteratorLoop()) - .or(infiniteIteratorLoopJavac()) - .compile(QueryParams.params(AbstractInsnNode.class) - .withIgnores(IGNORE) - .withDebug(DEBUG) - ); - - @Override - SequenceMatcher infiniteLoopMatcher() { - return INFINITE_LOOP; - } - - @Override - boolean couldCauseInfiniteLoop(MethodTree method, MutationDetails each) { - final AbstractInsnNode instruction = method.instructions().get(each.getInstructionIndex()); - return isIteratorNext(instruction); - } - - private static SequenceQuery doesNotBreakIteratorLoop() { - return QueryStart.match(methodCallTo(ClassName.fromClass(Iterator.class), "next").negate()); - } - - private boolean isIteratorNext(AbstractInsnNode instruction) { - return InstructionMatchers.methodCallTo(ClassName.fromClass(Iterator.class), "next").test(null, instruction); - } - - private static SequenceQuery inifniteIteratorLoop() { - final Slot loopStart = Slot.create(LabelNode.class); - - return QueryStart - .any(AbstractInsnNode.class) - .then(methodCallThatReturns(ClassName.fromString("java/util/Iterator"))) - .then(opCode(Opcodes.ASTORE)) - .zeroOrMore(QueryStart.match(anyInstruction())) - .then(aJump()) - .then(aLabelNode(loopStart.write())) - .oneOrMore(doesNotBreakIteratorLoop()) - .then(jumpsTo(loopStart.read())) - // can't currently deal with loops with conditionals that cause additional jumps back - .zeroOrMore(QueryStart.match(jumpsTo(loopStart.read()).negate())); - } - - private static SequenceQuery infiniteIteratorLoopJavac() { - final Slot loopStart = Slot.create(LabelNode.class); - - return QueryStart - .any(AbstractInsnNode.class) - .then(methodCallThatReturns(ClassName.fromString("java/util/Iterator"))) - .then(opCode(Opcodes.ASTORE)) - .then(aLabelNode(loopStart.write())) - .oneOrMore(doesNotBreakIteratorLoop()) - .then(jumpsTo(loopStart.read())) - // can't currently deal with loops with conditionals that cause additional jumps back - .zeroOrMore(QueryStart.match(jumpsTo(loopStart.read()).negate())); - } - - - -} +package org.pitest.mutationtest.build.intercept.timeout; + +import static org.pitest.bytecode.analysis.InstructionMatchers.aJump; +import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; +import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.jumpsTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallThatReturns; +import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; + +import java.util.Iterator; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.pitest.bytecode.analysis.InstructionMatchers; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.sequence.Match; +import org.pitest.sequence.QueryParams; +import org.pitest.sequence.QueryStart; +import org.pitest.sequence.SequenceMatcher; +import org.pitest.sequence.SequenceQuery; +import org.pitest.sequence.Slot; + +/** + * Removes mutants that remove the only call to next in an iterator loop + */ +public class InfiniteIteratorLoopFilter extends InfiniteLoopFilter { + + private static final boolean DEBUG = false; + + static final SequenceMatcher INFINITE_LOOP = QueryStart + .match(Match.never()) + .or(inifniteIteratorLoop()) + .or(infiniteIteratorLoopJavac()) + .compile(QueryParams.params(AbstractInsnNode.class) + .withIgnores(IGNORE) + .withDebug(DEBUG) + ); + + @Override + SequenceMatcher infiniteLoopMatcher() { + return INFINITE_LOOP; + } + + @Override + boolean couldCauseInfiniteLoop(MethodTree method, MutationDetails each) { + final AbstractInsnNode instruction = method.instructions().get(each.getInstructionIndex()); + return isIteratorNext(instruction); + } + + private static SequenceQuery doesNotBreakIteratorLoop() { + return QueryStart.match(methodCallTo(ClassName.fromClass(Iterator.class), "next").negate()); + } + + private boolean isIteratorNext(AbstractInsnNode instruction) { + return InstructionMatchers.methodCallTo(ClassName.fromClass(Iterator.class), "next").test(null, instruction); + } + + private static SequenceQuery inifniteIteratorLoop() { + final Slot loopStart = Slot.create(LabelNode.class); + + return QueryStart + .any(AbstractInsnNode.class) + .then(methodCallThatReturns(ClassName.fromString("java/util/Iterator"))) + .then(opCode(Opcodes.ASTORE)) + .zeroOrMore(QueryStart.match(anyInstruction())) + .then(aJump()) + .then(aLabelNode(loopStart.write())) + .oneOrMore(doesNotBreakIteratorLoop()) + .then(jumpsTo(loopStart.read())) + // can't currently deal with loops with conditionals that cause additional jumps back + .zeroOrMore(QueryStart.match(jumpsTo(loopStart.read()).negate())); + } + + private static SequenceQuery infiniteIteratorLoopJavac() { + final Slot loopStart = Slot.create(LabelNode.class); + + return QueryStart + .any(AbstractInsnNode.class) + .then(methodCallThatReturns(ClassName.fromString("java/util/Iterator"))) + .then(opCode(Opcodes.ASTORE)) + .then(aLabelNode(loopStart.write())) + .oneOrMore(doesNotBreakIteratorLoop()) + .then(jumpsTo(loopStart.read())) + // can't currently deal with loops with conditionals that cause additional jumps back + .zeroOrMore(QueryStart.match(jumpsTo(loopStart.read()).negate())); + } + + + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilterFactory.java index 484c89752..1bd0cfbf8 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilterFactory.java @@ -1,28 +1,28 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class InfiniteIteratorLoopFilterFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Long running iterator loop filter"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new InfiniteIteratorLoopFilter(); - } - - @Override - public Feature provides() { - return Feature.named("FINFIT") - .withOnByDefault(true) - .withDescription("Filters mutations that may cause infinite loops" - + " by removing calls to iterator.next"); - } - -} +package org.pitest.mutationtest.build.intercept.timeout; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class InfiniteIteratorLoopFilterFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Long running iterator loop filter"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new InfiniteIteratorLoopFilter(); + } + + @Override + public Feature provides() { + return Feature.named("FINFIT") + .withOnByDefault(true) + .withDescription("Filters mutations that may cause infinite loops" + + " by removing calls to iterator.next"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteLoopFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteLoopFilter.java index 16aacc3f2..5b6fc5674 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteLoopFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteLoopFilter.java @@ -1,104 +1,104 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import static org.pitest.bytecode.analysis.InstructionMatchers.isA; -import static org.pitest.bytecode.analysis.MethodMatchers.forLocation; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Function; - -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.LineNumberNode; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.sequence.Match; -import org.pitest.sequence.SequenceMatcher; - -public abstract class InfiniteLoopFilter implements MutationInterceptor { - - static final Match IGNORE = isA(LineNumberNode.class).or(isA(FrameNode.class)); - - private ClassTree currentClass; - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz; - } - - abstract SequenceMatcher infiniteLoopMatcher(); - abstract boolean couldCauseInfiniteLoop(MethodTree method, MutationDetails each); - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - final Map> buckets = FCollection.bucket(mutations, mutationToLocation()); - - final List willTimeout = new ArrayList<>(); - for (final Entry> each : buckets.entrySet() ) { - willTimeout.addAll(findTimeoutMutants(each.getKey(), each.getValue(), m)); - } - mutations.removeAll(willTimeout); - return mutations; - } - - private Collection findTimeoutMutants(Location location, - Collection mutations, Mutater m) { - - final MethodTree method = this.currentClass.methods().stream() - .filter(forLocation(location)) - .findFirst() - .get(); - - // give up if our matcher thinks loop is already infinite - if (infiniteLoopMatcher().matches(method.instructions())) { - return Collections.emptyList(); - } - - final List timeouts = new ArrayList<>(); - for ( final MutationDetails each : mutations ) { - // avoid cost of static analysis by first checking mutant is on - // on instruction that could affect looping - if (couldCauseInfiniteLoop(method, each) && isInfiniteLoop(each,m) ) { - timeouts.add(each); - } - } - return timeouts; - - } - - private boolean isInfiniteLoop(MutationDetails each, Mutater m) { - final ClassTree mutantClass = ClassTree.fromBytes(m.getMutation(each.getId()).getBytes()); - final Optional mutantMethod = mutantClass.methods().stream() - .filter(forLocation(each.getId().getLocation())) - .findFirst(); - return infiniteLoopMatcher().matches(mutantMethod.get().instructions()); - } - - private Function mutationToLocation() { - return a -> a.getId().getLocation(); - } - - @Override - public void end() { - this.currentClass = null; - } - -} - +package org.pitest.mutationtest.build.intercept.timeout; + +import static org.pitest.bytecode.analysis.InstructionMatchers.isA; +import static org.pitest.bytecode.analysis.MethodMatchers.forLocation; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Function; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.sequence.Match; +import org.pitest.sequence.SequenceMatcher; + +public abstract class InfiniteLoopFilter implements MutationInterceptor { + + static final Match IGNORE = isA(LineNumberNode.class).or(isA(FrameNode.class)); + + private ClassTree currentClass; + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz; + } + + abstract SequenceMatcher infiniteLoopMatcher(); + abstract boolean couldCauseInfiniteLoop(MethodTree method, MutationDetails each); + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + final Map> buckets = FCollection.bucket(mutations, mutationToLocation()); + + final List willTimeout = new ArrayList<>(); + for (final Entry> each : buckets.entrySet() ) { + willTimeout.addAll(findTimeoutMutants(each.getKey(), each.getValue(), m)); + } + mutations.removeAll(willTimeout); + return mutations; + } + + private Collection findTimeoutMutants(Location location, + Collection mutations, Mutater m) { + + final MethodTree method = this.currentClass.methods().stream() + .filter(forLocation(location)) + .findFirst() + .get(); + + // give up if our matcher thinks loop is already infinite + if (infiniteLoopMatcher().matches(method.instructions())) { + return Collections.emptyList(); + } + + final List timeouts = new ArrayList<>(); + for ( final MutationDetails each : mutations ) { + // avoid cost of static analysis by first checking mutant is on + // on instruction that could affect looping + if (couldCauseInfiniteLoop(method, each) && isInfiniteLoop(each,m) ) { + timeouts.add(each); + } + } + return timeouts; + + } + + private boolean isInfiniteLoop(MutationDetails each, Mutater m) { + final ClassTree mutantClass = ClassTree.fromBytes(m.getMutation(each.getId()).getBytes()); + final Optional mutantMethod = mutantClass.methods().stream() + .filter(forLocation(each.getId().getLocation())) + .findFirst(); + return infiniteLoopMatcher().matches(mutantMethod.get().instructions()); + } + + private Function mutationToLocation() { + return a -> a.getId().getLocation(); + } + + @Override + public void end() { + this.currentClass = null; + } + +} + diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/CompoundListenerFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/CompoundListenerFactory.java index dc17d11c7..d68b5812d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/CompoundListenerFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/CompoundListenerFactory.java @@ -1,56 +1,56 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import java.util.Properties; -import java.util.function.Function; - -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.ListenerArguments; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.MutationResultListenerFactory; - -public class CompoundListenerFactory implements MutationResultListenerFactory { - - private final Iterable children; - - public CompoundListenerFactory( - final Iterable children) { - this.children = children; - } - - @Override - public MutationResultListener getListener(final Properties props, - final ListenerArguments args) { - return new CompoundTestListener(FCollection.map(this.children, - factoryToListener(props, args))); - } - - private Function factoryToListener( - final Properties props, final ListenerArguments args) { - return a -> a.getListener(props, args); - } - - @Override - public String name() { - throw new UnsupportedOperationException(); - } - - @Override - public String description() { - throw new UnsupportedOperationException(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import java.util.Properties; +import java.util.function.Function; + +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.ListenerArguments; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.MutationResultListenerFactory; + +public class CompoundListenerFactory implements MutationResultListenerFactory { + + private final Iterable children; + + public CompoundListenerFactory( + final Iterable children) { + this.children = children; + } + + @Override + public MutationResultListener getListener(final Properties props, + final ListenerArguments args) { + return new CompoundTestListener(FCollection.map(this.children, + factoryToListener(props, args))); + } + + private Function factoryToListener( + final Properties props, final ListenerArguments args) { + return a -> a.getListener(props, args); + } + + @Override + public String name() { + throw new UnsupportedOperationException(); + } + + @Override + public String description() { + throw new UnsupportedOperationException(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/CompoundTestListener.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/CompoundTestListener.java index 1d85fa709..f3baedc16 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/CompoundTestListener.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/CompoundTestListener.java @@ -1,51 +1,51 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationResultListener; - -public class CompoundTestListener implements MutationResultListener { - - private final Iterable children; - - public CompoundTestListener(final Iterable children) { - this.children = children; - } - - @Override - public void runStart() { - for (final MutationResultListener each : this.children) { - each.runStart(); - } - - } - - @Override - public void handleMutationResult(final ClassMutationResults metaData) { - for (final MutationResultListener each : this.children) { - each.handleMutationResult(metaData); - } - } - - @Override - public void runEnd() { - for (final MutationResultListener each : this.children) { - each.runEnd(); - } - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationResultListener; + +public class CompoundTestListener implements MutationResultListener { + + private final Iterable children; + + public CompoundTestListener(final Iterable children) { + this.children = children; + } + + @Override + public void runStart() { + for (final MutationResultListener each : this.children) { + each.runStart(); + } + + } + + @Override + public void handleMutationResult(final ClassMutationResults metaData) { + for (final MutationResultListener each : this.children) { + each.handleMutationResult(metaData); + } + } + + @Override + public void runEnd() { + for (final MutationResultListener each : this.children) { + each.runEnd(); + } + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/ConfigOption.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/ConfigOption.java index 807556abc..8691d3151 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/ConfigOption.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/ConfigOption.java @@ -1,234 +1,234 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 ("the "License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import java.io.Serializable; - -import org.pitest.mutationtest.build.PercentAndConstantTimeoutStrategy; - -public enum ConfigOption { - - /** - * The test plugin to use - */ - TEST_PLUGIN("testPlugin"), - - /** - * The directory to write report sot - */ - REPORT_DIR("reportDir"), - /** - * Filter defining classes to mutate - */ - TARGET_CLASSES("targetClasses"), - - /** - * Directories to examine to find source files to annotate when generating - * report - */ - SOURCE_DIR("sourceDirs"), - /** - * Mutation operations to use - */ - MUTATIONS("mutators"), - /** - * Features to enable/disable - */ - FEATURES("features"), - /** - * Maximum number of hops from a mutable class to a test - */ - DEPENDENCY_DISTANCE("dependencyDistance", -1), - /** - * Arguments to launch child processes with - */ - CHILD_JVM("jvmArgs"), - - - /** - * Do/don't create timestamped folders for reports - */ - TIME_STAMPED_REPORTS("timestampedReports", true), - - /** - * Number of threads to use - */ - THREADS("threads", 1), - /** - * Multiple of normal runtime to allow before considering a mutation to have - * timed out - */ - TIMEOUT_FACTOR("timeoutFactor", - PercentAndConstantTimeoutStrategy.DEFAULT_FACTOR), - /** - * Consant addiotnal period of time to allow before considering a mutation to - * have timed out - */ - TIMEOUT_CONST("timeoutConst", - PercentAndConstantTimeoutStrategy.DEFAULT_CONSTANT), - /** - * Filter limiting tests to be considered - */ - TEST_FILTER("targetTests"), - /** - * List of classes no to mutate lines of calls that contain call to - */ - AVOID_CALLS("avoidCallsTo"), - /** - * Filter of methods not to be mutated - */ - EXCLUDED_METHOD("excludedMethods"), - /** - * Maximum number of mutations to allow per class - */ - MAX_MUTATIONS_PER_CLASS("maxMutationsPerClass", 0), - /** - * Flag to indicate if verbose logging should be enabled - */ - VERBOSE("verbose", false), - /** - * Filter defining classes to exclude from mutation - */ - EXCLUDED_CLASSES("excludedClasses"), - - /** - * Filter defining test classes to excludd - */ - EXCLUDED_TEST_CLASSES("excludedTestClasses"), - /** - * Formats in which to output results - */ - OUTPUT_FORMATS("outputFormats"), - - /** - * Classpath entries to analyse. Although classes on the launch classpath will - * also be analysed, this is the preferred place to specify the code to - * analyse - */ - CLASSPATH("classPath"), - /** - * Same as classPath above, but in a file. The file should contain paths to the jars - * to be added to the classpath. one path per line. - * This is usually only needed if you are running on windows and have a huge classpath - */ - CLASSPATH_FILE("classPathFile"), - /** - * Flag to indicate if an error should be thrown if no mutations found - */ - FAIL_WHEN_NOT_MUTATIONS("failWhenNoMutations", true), - /** - * Filter defining paths that should be treated as containing mutable code - */ - CODE_PATHS("mutableCodePaths"), - /** - * TestNG groups/JUnit categories to include - */ - INCLUDED_GROUPS("includedGroups"), - /** - * Test methods that should be included for challenging the mutants - */ - INCLUDED_TEST_METHODS("includedTestMethods"), - /** - * TestNG groupsJUnit categories to exclude - */ - EXCLUDED_GROUPS("excludedGroups"), - /** - * Maximum number of mutations to include within a single unit of analysis. - */ - MUTATION_UNIT_SIZE("mutationUnitSize", 0), - - /** - * Do/don't attempt to detect inlined code from finally blocks - */ - USE_INLINED_CODE_DETECTION("detectInlinedCode", true), - - /** - * Location to read history from for incremental analysis - */ - HISTORY_INPUT_LOCATION("historyInputLocation"), - - /** - * Location to write history to for incremental analysis - */ - HISTORY_OUTPUT_LOCATION("historyOutputLocation"), - - /** - * Mutation score below which to throw an error - */ - MUTATION_THRESHOLD("mutationThreshold", 0), - - /** - * Number of surviving mutants at which to throw an error - */ - MAX_SURVIVING("maxSurviving", -1), - - /** - * Line coverage score below which to throw an error - */ - COVERAGE_THRESHOLD("coverageThreshold", 0), - - /** - * Mutation engine to use - */ - MUTATION_ENGINE("mutationEngine", "gregor"), - - /** - * Dump per test line coverage to disk - */ - EXPORT_LINE_COVERAGE("exportLineCoverage", false), - - /** - * Include launch classpath in analysis - */ - INCLUDE_LAUNCH_CLASSPATH("includeLaunchClasspath", true), - - /** - * Path to executable with which to run tests - */ - JVM_PATH("jvmPath"), - - /** - * Custom properties for plugins - */ - PLUGIN_CONFIGURATION("pluginConfiguration"); - - private final String text; - private final Serializable defaultValue; - - ConfigOption(final String text) { - this(text, null); - } - - ConfigOption(final String text, final Serializable defaultValue) { - this.text = text; - this.defaultValue = defaultValue; - } - - public String getParamName() { - return this.text; - } - - @SuppressWarnings("unchecked") - public T getDefault(final Class type) { - // so much for type safety - return (T) this.defaultValue; - } - - @Override - public String toString() { - return this.text; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 ("the "License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import java.io.Serializable; + +import org.pitest.mutationtest.build.PercentAndConstantTimeoutStrategy; + +public enum ConfigOption { + + /** + * The test plugin to use + */ + TEST_PLUGIN("testPlugin"), + + /** + * The directory to write report sot + */ + REPORT_DIR("reportDir"), + /** + * Filter defining classes to mutate + */ + TARGET_CLASSES("targetClasses"), + + /** + * Directories to examine to find source files to annotate when generating + * report + */ + SOURCE_DIR("sourceDirs"), + /** + * Mutation operations to use + */ + MUTATIONS("mutators"), + /** + * Features to enable/disable + */ + FEATURES("features"), + /** + * Maximum number of hops from a mutable class to a test + */ + DEPENDENCY_DISTANCE("dependencyDistance", -1), + /** + * Arguments to launch child processes with + */ + CHILD_JVM("jvmArgs"), + + + /** + * Do/don't create timestamped folders for reports + */ + TIME_STAMPED_REPORTS("timestampedReports", true), + + /** + * Number of threads to use + */ + THREADS("threads", 1), + /** + * Multiple of normal runtime to allow before considering a mutation to have + * timed out + */ + TIMEOUT_FACTOR("timeoutFactor", + PercentAndConstantTimeoutStrategy.DEFAULT_FACTOR), + /** + * Consant addiotnal period of time to allow before considering a mutation to + * have timed out + */ + TIMEOUT_CONST("timeoutConst", + PercentAndConstantTimeoutStrategy.DEFAULT_CONSTANT), + /** + * Filter limiting tests to be considered + */ + TEST_FILTER("targetTests"), + /** + * List of classes no to mutate lines of calls that contain call to + */ + AVOID_CALLS("avoidCallsTo"), + /** + * Filter of methods not to be mutated + */ + EXCLUDED_METHOD("excludedMethods"), + /** + * Maximum number of mutations to allow per class + */ + MAX_MUTATIONS_PER_CLASS("maxMutationsPerClass", 0), + /** + * Flag to indicate if verbose logging should be enabled + */ + VERBOSE("verbose", false), + /** + * Filter defining classes to exclude from mutation + */ + EXCLUDED_CLASSES("excludedClasses"), + + /** + * Filter defining test classes to excludd + */ + EXCLUDED_TEST_CLASSES("excludedTestClasses"), + /** + * Formats in which to output results + */ + OUTPUT_FORMATS("outputFormats"), + + /** + * Classpath entries to analyse. Although classes on the launch classpath will + * also be analysed, this is the preferred place to specify the code to + * analyse + */ + CLASSPATH("classPath"), + /** + * Same as classPath above, but in a file. The file should contain paths to the jars + * to be added to the classpath. one path per line. + * This is usually only needed if you are running on windows and have a huge classpath + */ + CLASSPATH_FILE("classPathFile"), + /** + * Flag to indicate if an error should be thrown if no mutations found + */ + FAIL_WHEN_NOT_MUTATIONS("failWhenNoMutations", true), + /** + * Filter defining paths that should be treated as containing mutable code + */ + CODE_PATHS("mutableCodePaths"), + /** + * TestNG groups/JUnit categories to include + */ + INCLUDED_GROUPS("includedGroups"), + /** + * Test methods that should be included for challenging the mutants + */ + INCLUDED_TEST_METHODS("includedTestMethods"), + /** + * TestNG groupsJUnit categories to exclude + */ + EXCLUDED_GROUPS("excludedGroups"), + /** + * Maximum number of mutations to include within a single unit of analysis. + */ + MUTATION_UNIT_SIZE("mutationUnitSize", 0), + + /** + * Do/don't attempt to detect inlined code from finally blocks + */ + USE_INLINED_CODE_DETECTION("detectInlinedCode", true), + + /** + * Location to read history from for incremental analysis + */ + HISTORY_INPUT_LOCATION("historyInputLocation"), + + /** + * Location to write history to for incremental analysis + */ + HISTORY_OUTPUT_LOCATION("historyOutputLocation"), + + /** + * Mutation score below which to throw an error + */ + MUTATION_THRESHOLD("mutationThreshold", 0), + + /** + * Number of surviving mutants at which to throw an error + */ + MAX_SURVIVING("maxSurviving", -1), + + /** + * Line coverage score below which to throw an error + */ + COVERAGE_THRESHOLD("coverageThreshold", 0), + + /** + * Mutation engine to use + */ + MUTATION_ENGINE("mutationEngine", "gregor"), + + /** + * Dump per test line coverage to disk + */ + EXPORT_LINE_COVERAGE("exportLineCoverage", false), + + /** + * Include launch classpath in analysis + */ + INCLUDE_LAUNCH_CLASSPATH("includeLaunchClasspath", true), + + /** + * Path to executable with which to run tests + */ + JVM_PATH("jvmPath"), + + /** + * Custom properties for plugins + */ + PLUGIN_CONFIGURATION("pluginConfiguration"); + + private final String text; + private final Serializable defaultValue; + + ConfigOption(final String text) { + this(text, null); + } + + ConfigOption(final String text, final Serializable defaultValue) { + this.text = text; + this.defaultValue = defaultValue; + } + + public String getParamName() { + return this.text; + } + + @SuppressWarnings("unchecked") + public T getDefault(final Class type) { + // so much for type safety + return (T) this.defaultValue; + } + + @Override + public String toString() { + return this.text; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/DatedDirectoryReportDirCreationStrategy.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/DatedDirectoryReportDirCreationStrategy.java index 99abe10a6..d5d93763d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/DatedDirectoryReportDirCreationStrategy.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/DatedDirectoryReportDirCreationStrategy.java @@ -1,42 +1,42 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class DatedDirectoryReportDirCreationStrategy implements -ReportDirCreationStrategy { - - @Override - public File createReportDir(final String base) { - final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm"); - final String timeString = sdf.format(new Date()); - final File reportDir = new File(addPathSeparatorIfMissing(base) - + timeString); - reportDir.mkdirs(); - return reportDir; - } - - private String addPathSeparatorIfMissing(final String s) { - if (!s.endsWith(File.separator)) { - return s + File.separator; - } else { - return s; - } - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class DatedDirectoryReportDirCreationStrategy implements +ReportDirCreationStrategy { + + @Override + public File createReportDir(final String base) { + final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm"); + final String timeString = sdf.format(new Date()); + final File reportDir = new File(addPathSeparatorIfMissing(base) + + timeString); + reportDir.mkdirs(); + return reportDir; + } + + private String addPathSeparatorIfMissing(final String s) { + if (!s.endsWith(File.separator)) { + return s + File.separator; + } else { + return s; + } + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/DefaultCodePathPredicate.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/DefaultCodePathPredicate.java index 1a50e5752..7c7e54c66 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/DefaultCodePathPredicate.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/DefaultCodePathPredicate.java @@ -1,39 +1,39 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import java.util.function.Predicate; - -import org.pitest.classpath.ClassPathRoot; - -public class DefaultCodePathPredicate implements Predicate { - - @Override - public boolean test(final ClassPathRoot a) { - return a.cacheLocation().isPresent() - && !isATestPath(a.cacheLocation().get()) - && !isADependencyPath(a.cacheLocation().get()); - } - - private boolean isADependencyPath(final String path) { - final String lowerCasePath = path.toLowerCase(); - return lowerCasePath.endsWith(".jar") || lowerCasePath.endsWith(".zip"); - } - - private boolean isATestPath(final String path) { - return path.endsWith("test-classes") || path.endsWith("bin-test"); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import java.util.function.Predicate; + +import org.pitest.classpath.ClassPathRoot; + +public class DefaultCodePathPredicate implements Predicate { + + @Override + public boolean test(final ClassPathRoot a) { + return a.cacheLocation().isPresent() + && !isATestPath(a.cacheLocation().get()) + && !isADependencyPath(a.cacheLocation().get()); + } + + private boolean isADependencyPath(final String path) { + final String lowerCasePath = path.toLowerCase(); + return lowerCasePath.endsWith(".jar") || lowerCasePath.endsWith(".zip"); + } + + private boolean isATestPath(final String path) { + return path.endsWith("test-classes") || path.endsWith("bin-test"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/DefaultDependencyPathPredicate.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/DefaultDependencyPathPredicate.java index e8cd33690..1833d55e3 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/DefaultDependencyPathPredicate.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/DefaultDependencyPathPredicate.java @@ -1,38 +1,38 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import java.util.function.Predicate; - -import org.pitest.classpath.ClassPathRoot; - -public class DefaultDependencyPathPredicate implements Predicate { - - public DefaultDependencyPathPredicate() { - - } - - @Override - public boolean test(final ClassPathRoot a) { - return a.cacheLocation().isPresent() - && isADependencyPath(a.cacheLocation().get()); - } - - private boolean isADependencyPath(final String path) { - final String lowerCasePath = path.toLowerCase(); - return lowerCasePath.endsWith(".jar") || lowerCasePath.endsWith(".zip"); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import java.util.function.Predicate; + +import org.pitest.classpath.ClassPathRoot; + +public class DefaultDependencyPathPredicate implements Predicate { + + public DefaultDependencyPathPredicate() { + + } + + @Override + public boolean test(final ClassPathRoot a) { + return a.cacheLocation().isPresent() + && isADependencyPath(a.cacheLocation().get()); + } + + private boolean isADependencyPath(final String path) { + final String lowerCasePath = path.toLowerCase(); + return lowerCasePath.endsWith(".jar") || lowerCasePath.endsWith(".zip"); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/DirectoryResultOutputStrategy.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/DirectoryResultOutputStrategy.java index 3938415b3..4cecf0272 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/DirectoryResultOutputStrategy.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/DirectoryResultOutputStrategy.java @@ -1,54 +1,54 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; - -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.Unchecked; - -public class DirectoryResultOutputStrategy implements ResultOutputStrategy { - - private final File reportDir; - - public DirectoryResultOutputStrategy(final String baseDir, - final ReportDirCreationStrategy dirCreationStrategy) { - this.reportDir = dirCreationStrategy.createReportDir(baseDir); - } - - @Override - public Writer createWriterForFile(final String file) { - try { - final int fileSepIndex = file.lastIndexOf(File.separatorChar); - if (fileSepIndex > 0) { - final String directory = this.reportDir.getAbsolutePath() - + File.separatorChar + file.substring(0, fileSepIndex); - final File directoryFile = new File(directory); - if (!directoryFile.exists()) { - directoryFile.mkdirs(); - } - } - return new BufferedWriter(new FileWriter(this.reportDir.getAbsolutePath() - + File.separatorChar + file)); - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex); - } - } - +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; + +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.Unchecked; + +public class DirectoryResultOutputStrategy implements ResultOutputStrategy { + + private final File reportDir; + + public DirectoryResultOutputStrategy(final String baseDir, + final ReportDirCreationStrategy dirCreationStrategy) { + this.reportDir = dirCreationStrategy.createReportDir(baseDir); + } + + @Override + public Writer createWriterForFile(final String file) { + try { + final int fileSepIndex = file.lastIndexOf(File.separatorChar); + if (fileSepIndex > 0) { + final String directory = this.reportDir.getAbsolutePath() + + File.separatorChar + file.substring(0, fileSepIndex); + final File directoryFile = new File(directory); + if (!directoryFile.exists()) { + directoryFile.mkdirs(); + } + } + return new BufferedWriter(new FileWriter(this.reportDir.getAbsolutePath() + + File.separatorChar + file)); + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex); + } + } + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/PathNamePredicate.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/PathNamePredicate.java index 94a1ac26d..ee5c70f80 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/PathNamePredicate.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/PathNamePredicate.java @@ -1,44 +1,44 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import java.util.function.Predicate; - -import org.pitest.classpath.ClassPathRoot; - -public class PathNamePredicate implements Predicate { - - private final Predicate stringFilter; - - public PathNamePredicate(final Predicate stringFilter) { - this.stringFilter = stringFilter; - } - - @Override - public boolean test(final ClassPathRoot classPathRoot) { - return cacheLocationOptionExists(classPathRoot) - && cacheLocationMatchesFilter(classPathRoot); - } - - private Boolean cacheLocationMatchesFilter(final ClassPathRoot classPathRoot) { - final String cacheLocationValue = classPathRoot.cacheLocation().get(); - return this.stringFilter.test(cacheLocationValue); - } - - private boolean cacheLocationOptionExists(final ClassPathRoot a) { - return a.cacheLocation().isPresent(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import java.util.function.Predicate; + +import org.pitest.classpath.ClassPathRoot; + +public class PathNamePredicate implements Predicate { + + private final Predicate stringFilter; + + public PathNamePredicate(final Predicate stringFilter) { + this.stringFilter = stringFilter; + } + + @Override + public boolean test(final ClassPathRoot classPathRoot) { + return cacheLocationOptionExists(classPathRoot) + && cacheLocationMatchesFilter(classPathRoot); + } + + private Boolean cacheLocationMatchesFilter(final ClassPathRoot classPathRoot) { + final String cacheLocationValue = classPathRoot.cacheLocation().get(); + return this.stringFilter.test(cacheLocationValue); + } + + private boolean cacheLocationOptionExists(final ClassPathRoot a) { + return a.cacheLocation().isPresent(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/PluginServices.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/PluginServices.java index d91b65766..e20bc621a 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/PluginServices.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/PluginServices.java @@ -1,84 +1,84 @@ -package org.pitest.mutationtest.config; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.pitest.mutationtest.MutationEngineFactory; -import org.pitest.mutationtest.MutationResultListenerFactory; -import org.pitest.mutationtest.build.MutationGrouperFactory; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.mutationtest.build.TestPrioritiserFactory; -import org.pitest.plugin.ClientClasspathPlugin; -import org.pitest.plugin.ToolClasspathPlugin; -import org.pitest.testapi.TestPluginFactory; -import org.pitest.util.IsolationUtils; -import org.pitest.util.ServiceLoader; - -public class PluginServices { - - private final ClassLoader loader; - - public PluginServices(ClassLoader loader) { - this.loader = loader; - } - - public static PluginServices makeForContextLoader() { - return new PluginServices(IsolationUtils.getContextClassLoader()); - } - - /** - * Lists all plugin classes that must be present on the classpath of the - * controlling process only. - * - * @return list of plugins - */ - public Iterable findToolClasspathPlugins() { - final List l = new ArrayList<>(); - l.addAll(findListeners()); - l.addAll(findGroupers()); - l.addAll(findTestPrioritisers()); - l.addAll(findInterceptors()); - return l; - } - - /** - * Lists all plugin classes that must be present on the classpath of the code - * under test at runtime - */ - public Iterable findClientClasspathPlugins() { - final List l = new ArrayList<>(); - l.addAll(findMutationEngines()); - l.addAll(findTestFrameworkPlugins()); - l.addAll(nullPlugins()); - return l; - } - Collection findTestFrameworkPlugins() { - return ServiceLoader.load(TestPluginFactory.class, this.loader); - } - - Collection findGroupers() { - return ServiceLoader.load(MutationGrouperFactory.class, this.loader); - } - - Collection findListeners() { - return ServiceLoader.load(MutationResultListenerFactory.class, this.loader); - } - - Collection findMutationEngines() { - return ServiceLoader.load(MutationEngineFactory.class, this.loader); - } - - Collection findTestPrioritisers() { - return ServiceLoader.load(TestPrioritiserFactory.class, this.loader); - } - - private Collection nullPlugins() { - return ServiceLoader.load(ClientClasspathPlugin.class, this.loader); - } - - public Collection findInterceptors() { - return ServiceLoader.load(MutationInterceptorFactory.class, this.loader); - } - -} +package org.pitest.mutationtest.config; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.pitest.mutationtest.MutationEngineFactory; +import org.pitest.mutationtest.MutationResultListenerFactory; +import org.pitest.mutationtest.build.MutationGrouperFactory; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.mutationtest.build.TestPrioritiserFactory; +import org.pitest.plugin.ClientClasspathPlugin; +import org.pitest.plugin.ToolClasspathPlugin; +import org.pitest.testapi.TestPluginFactory; +import org.pitest.util.IsolationUtils; +import org.pitest.util.ServiceLoader; + +public class PluginServices { + + private final ClassLoader loader; + + public PluginServices(ClassLoader loader) { + this.loader = loader; + } + + public static PluginServices makeForContextLoader() { + return new PluginServices(IsolationUtils.getContextClassLoader()); + } + + /** + * Lists all plugin classes that must be present on the classpath of the + * controlling process only. + * + * @return list of plugins + */ + public Iterable findToolClasspathPlugins() { + final List l = new ArrayList<>(); + l.addAll(findListeners()); + l.addAll(findGroupers()); + l.addAll(findTestPrioritisers()); + l.addAll(findInterceptors()); + return l; + } + + /** + * Lists all plugin classes that must be present on the classpath of the code + * under test at runtime + */ + public Iterable findClientClasspathPlugins() { + final List l = new ArrayList<>(); + l.addAll(findMutationEngines()); + l.addAll(findTestFrameworkPlugins()); + l.addAll(nullPlugins()); + return l; + } + Collection findTestFrameworkPlugins() { + return ServiceLoader.load(TestPluginFactory.class, this.loader); + } + + Collection findGroupers() { + return ServiceLoader.load(MutationGrouperFactory.class, this.loader); + } + + Collection findListeners() { + return ServiceLoader.load(MutationResultListenerFactory.class, this.loader); + } + + Collection findMutationEngines() { + return ServiceLoader.load(MutationEngineFactory.class, this.loader); + } + + Collection findTestPrioritisers() { + return ServiceLoader.load(TestPrioritiserFactory.class, this.loader); + } + + private Collection nullPlugins() { + return ServiceLoader.load(ClientClasspathPlugin.class, this.loader); + } + + public Collection findInterceptors() { + return ServiceLoader.load(MutationInterceptorFactory.class, this.loader); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/ReportDirCreationStrategy.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/ReportDirCreationStrategy.java index 02bc3cd93..dddfe676f 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/ReportDirCreationStrategy.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/ReportDirCreationStrategy.java @@ -1,23 +1,23 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import java.io.File; - -public interface ReportDirCreationStrategy { - - File createReportDir(String base); - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import java.io.File; + +public interface ReportDirCreationStrategy { + + File createReportDir(String base); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/ReportOptions.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/ReportOptions.java index 69f6edf5d..e90b3754f 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/ReportOptions.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/ReportOptions.java @@ -1,620 +1,620 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import static org.pitest.functional.prelude.Prelude.not; -import static org.pitest.functional.prelude.Prelude.or; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Properties; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.pitest.classpath.ClassFilter; -import org.pitest.classpath.ClassPath; -import org.pitest.classpath.ClassPathRoot; -import org.pitest.classpath.PathFilter; -import org.pitest.classpath.ProjectClassPaths; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.functional.prelude.Prelude; -import org.pitest.help.Help; -import org.pitest.help.PitHelpError; -import org.pitest.mutationtest.build.PercentAndConstantTimeoutStrategy; -import org.pitest.mutationtest.incremental.FileWriterFactory; -import org.pitest.mutationtest.incremental.NullWriterFactory; -import org.pitest.mutationtest.incremental.WriterFactory; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.testapi.execute.Pitest; -import org.pitest.util.Glob; -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.Unchecked; - -// FIXME move all logic to SettingsFactory and turn into simple bean - -/** - * Big ball of user supplied options to configure various aspects of mutation - * testing. - * - */ -public class ReportOptions { - - public static final Collection LOGGING_CLASSES = Arrays - .asList( - "java.util.logging", - "org.apache.log4j", - "org.apache.logging.log4j", - "org.slf4j", - "org.apache.commons.logging"); - - private Collection targetClasses; - private Collection excludedMethods = Collections - .emptyList(); - - private Collection excludedClasses = Collections - .emptyList(); - - private Collection> excludedTestClasses = Collections - .emptyList(); - - private Collection codePaths; - - private String reportDir; - - private File historyInputLocation; - private File historyOutputLocation; - - private Collection sourceDirs; - private Collection classPathElements; - private Collection mutators; - private Collection features; - - private int dependencyAnalysisMaxDistance; - - private final List jvmArgs = new ArrayList<>(); - private int numberOfThreads = 0; - private float timeoutFactor = PercentAndConstantTimeoutStrategy.DEFAULT_FACTOR; - private long timeoutConstant = PercentAndConstantTimeoutStrategy.DEFAULT_CONSTANT; - - private Collection> targetTests; - - private Collection loggingClasses = new ArrayList<>(); - - private int maxMutationsPerClass; - - private boolean verbose = false; - private boolean failWhenNoMutations = false; - - private final Collection outputs = new LinkedHashSet<>(); - - private TestGroupConfig groupConfig; - - private int mutationUnitSize; - private boolean shouldCreateTimestampedReports = true; - private boolean detectInlinedCode = false; - private boolean exportLineCoverage = false; - private int mutationThreshold; - private int coverageThreshold; - - private String mutationEngine = "gregor"; - - private String javaExecutable; - - private boolean includeLaunchClasspath = true; - - private Properties properties; - - private int maxSurvivors; - - private Collection excludedRunners = new ArrayList<>(); - private Collection includedTestMethods = new ArrayList<>(); - - private String testPlugin = ""; - - public boolean isVerbose() { - return this.verbose; - } - - /** - * @return the reportDir - */ - public String getReportDir() { - return this.reportDir; - } - - /** - * @param reportDir - * the reportDir to set - */ - public void setReportDir(final String reportDir) { - this.reportDir = reportDir; - } - - /** - * @return the sourceDirs - */ - public Collection getSourceDirs() { - return this.sourceDirs; - } - - public Collection getClassPathElements() { - return this.classPathElements; - } - - public void setClassPathElements(final Collection classPathElements) { - this.classPathElements = classPathElements; - } - - /** - * @param sourceDirs - * the sourceDirs to set - */ - public void setSourceDirs(final Collection sourceDirs) { - this.sourceDirs = sourceDirs; - } - - /** - * @return the mutators - */ - public Collection getMutators() { - return this.mutators; - } - - /** - * @param mutators - * the mutators to set - */ - public void setMutators(final Collection mutators) { - this.mutators = mutators; - } - - - public Collection getFeatures() { - return this.features; - } - - public void setFeatures(Collection features) { - this.features = features; - } - - /** - * @return the dependencyAnalysisMaxDistance - */ - public int getDependencyAnalysisMaxDistance() { - return this.dependencyAnalysisMaxDistance; - } - - /** - * @param dependencyAnalysisMaxDistance - * the dependencyAnalysisMaxDistance to set - */ - public void setDependencyAnalysisMaxDistance( - final int dependencyAnalysisMaxDistance) { - this.dependencyAnalysisMaxDistance = dependencyAnalysisMaxDistance; - } - - public List getJvmArgs() { - return this.jvmArgs; - } - - public void addChildJVMArgs(final List args) { - this.jvmArgs.addAll(args); - } - - public ClassPath getClassPath() { - if (this.classPathElements != null) { - return createClassPathFromElements(); - } else { - return new ClassPath(); - } - } - - private ClassPath createClassPathFromElements() { - return new ClassPath( - FCollection.map(this.classPathElements, stringToFile())); - } - - private static Function stringToFile() { - return a -> new File(a); - } - - public Collection getTargetClasses() { - return this.targetClasses; - } - - - public Predicate getTargetClassesFilter() { - final Predicate filter = Prelude.and(or(Glob.toGlobPredicates(this.targetClasses)), - not(isBlackListed(Glob.toGlobPredicates(ReportOptions.this.excludedClasses)))); - checkNotTryingToMutateSelf(filter); - return filter; - } - - private void checkNotTryingToMutateSelf(final Predicate filter) { - if (filter.test(Pitest.class.getName())) { - throw new PitHelpError(Help.BAD_FILTER); - } - } - - public void setTargetClasses(final Collection targetClasses) { - this.targetClasses = targetClasses; - } - - public void setTargetTests( - final Collection> targetTestsPredicates) { - this.targetTests = targetTestsPredicates; - } - - public int getNumberOfThreads() { - return this.numberOfThreads; - } - - public void setNumberOfThreads(final int numberOfThreads) { - this.numberOfThreads = numberOfThreads; - } - - public float getTimeoutFactor() { - return this.timeoutFactor; - } - - public long getTimeoutConstant() { - return this.timeoutConstant; - } - - public void setTimeoutConstant(final long timeoutConstant) { - this.timeoutConstant = timeoutConstant; - } - - public void setTimeoutFactor(final float timeoutFactor) { - this.timeoutFactor = timeoutFactor; - } - - public Collection> getTargetTests() { - return this.targetTests; - } - - public Predicate getTargetTestsFilter() { - if ((this.targetTests == null) || this.targetTests.isEmpty()) { - // If target tests is not explicitly set we assume that the - // target classes predicate covers both classes and tests - return Prelude.and(or(Glob.toGlobPredicates(this.targetClasses)), - not(isBlackListed(ReportOptions.this.excludedTestClasses))); - } else { - return Prelude.and(or(this.targetTests), - not(isBlackListed(ReportOptions.this.excludedTestClasses))); - } - } - - private static Predicate isBlackListed( - final Collection> excludedClasses) { - return or(excludedClasses); - } - - public Collection getLoggingClasses() { - if (this.loggingClasses.isEmpty()) { - return LOGGING_CLASSES; - } else { - return this.loggingClasses; - } - } - - public void setLoggingClasses(final Collection loggingClasses) { - this.loggingClasses = loggingClasses; - } - - public Collection getExcludedMethods() { - return this.excludedMethods; - } - - public void setExcludedMethods( - final Collection excludedMethods) { - this.excludedMethods = excludedMethods; - } - - public void setVerbose(final boolean verbose) { - this.verbose = verbose; - } - - public void setExcludedClasses( - final Collection excludedClasses) { - this.excludedClasses = excludedClasses; - } - - public void setExcludedTestClasses( - final Collection> excludedClasses) { - this.excludedTestClasses = excludedClasses; - } - - - public void addOutputFormats(final Collection formats) { - this.outputs.addAll(formats); - } - - public Collection getOutputFormats() { - return this.outputs; - } - - public Collection getExcludedClasses() { - return this.excludedClasses; - } - - public Collection> getExcludedTestClasses() { - return this.excludedTestClasses; - } - - public boolean shouldFailWhenNoMutations() { - return this.failWhenNoMutations; - } - - public void setFailWhenNoMutations(final boolean failWhenNoMutations) { - this.failWhenNoMutations = failWhenNoMutations; - } - - public ProjectClassPaths getMutationClassPaths() { - - return new ProjectClassPaths(this.getClassPath(), createClassesFilter(), - createPathFilter()); - } - - public ClassFilter createClassesFilter() { - return new ClassFilter(this.getTargetTestsFilter(), - this.getTargetClassesFilter()); - } - - private PathFilter createPathFilter() { - return new PathFilter(createCodePathFilter(), - not(new DefaultDependencyPathPredicate())); - } - - private Predicate createCodePathFilter() { - if ((this.codePaths != null) && !this.codePaths.isEmpty()) { - return new PathNamePredicate(Prelude.or(Glob - .toGlobPredicates(this.codePaths))); - } else { - return new DefaultCodePathPredicate(); - } - } - - public Collection getCodePaths() { - return this.codePaths; - } - - public void setCodePaths(final Collection codePaths) { - this.codePaths = codePaths; - } - - public void setGroupConfig(final TestGroupConfig groupConfig) { - this.groupConfig = groupConfig; - } - - public TestGroupConfig getGroupConfig() { - return this.groupConfig; - } - - public int getMutationUnitSize() { - return this.mutationUnitSize; - } - - public void setMutationUnitSize(final int size) { - this.mutationUnitSize = size; - } - - public ResultOutputStrategy getReportDirectoryStrategy() { - return new DirectoryResultOutputStrategy(getReportDir(), - pickDirectoryStrategy()); - } - - public void setShouldCreateTimestampedReports( - final boolean shouldCreateTimestampedReports) { - this.shouldCreateTimestampedReports = shouldCreateTimestampedReports; - } - - private ReportDirCreationStrategy pickDirectoryStrategy() { - if (this.shouldCreateTimestampedReports) { - return new DatedDirectoryReportDirCreationStrategy(); - } else { - return new UndatedReportDirCreationStrategy(); - } - } - - public boolean shouldCreateTimeStampedReports() { - return this.shouldCreateTimestampedReports; - } - - public boolean isDetectInlinedCode() { - return this.detectInlinedCode; - } - - public void setDetectInlinedCode(final boolean b) { - this.detectInlinedCode = b; - } - - public WriterFactory createHistoryWriter() { - if (this.historyOutputLocation == null) { - return new NullWriterFactory(); - } - - return new FileWriterFactory(this.historyOutputLocation); - } - - public Optional createHistoryReader() { - if (this.historyInputLocation == null) { - return Optional.empty(); - } - - try { - if (this.historyInputLocation.exists() - && (this.historyInputLocation.length() > 0)) { - return Optional. ofNullable(new InputStreamReader(new FileInputStream( - this.historyInputLocation), "UTF-8")); - } - return Optional.empty(); - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex); - } - } - - public void setHistoryInputLocation(final File historyInputLocation) { - this.historyInputLocation = historyInputLocation; - } - - public void setHistoryOutputLocation(final File historyOutputLocation) { - this.historyOutputLocation = historyOutputLocation; - } - - public File getHistoryInputLocation() { - return this.historyInputLocation; - } - - public File getHistoryOutputLocation() { - return this.historyOutputLocation; - } - - public void setExportLineCoverage(final boolean value) { - this.exportLineCoverage = value; - } - - public boolean shouldExportLineCoverage() { - return this.exportLineCoverage; - } - - public int getMutationThreshold() { - return this.mutationThreshold; - } - - public void setMutationThreshold(final int value) { - this.mutationThreshold = value; - } - - public String getMutationEngine() { - return this.mutationEngine; - } - - public void setMutationEngine(final String mutationEngine) { - this.mutationEngine = mutationEngine; - } - - public int getCoverageThreshold() { - return this.coverageThreshold; - } - - public void setCoverageThreshold(final int coverageThreshold) { - this.coverageThreshold = coverageThreshold; - } - - public String getJavaExecutable() { - return this.javaExecutable; - } - - public void setJavaExecutable(final String javaExecutable) { - this.javaExecutable = javaExecutable; - } - - public void setIncludeLaunchClasspath(final boolean b) { - this.includeLaunchClasspath = b; - } - - public boolean isIncludeLaunchClasspath() { - return this.includeLaunchClasspath; - } - - public Properties getFreeFormProperties() { - return this.properties; - } - - public void setFreeFormProperties(Properties props) { - this.properties = props; - } - - public int getMaximumAllowedSurvivors() { - return this.maxSurvivors; - } - - public void setMaximumAllowedSurvivors(int maxSurvivors) { - this.maxSurvivors = maxSurvivors; - } - - public Collection getExcludedRunners() { - return this.excludedRunners; - } - - public Collection getIncludedTestMethods() { - return this.includedTestMethods; - } - - public void setExcludedRunners(Collection excludedRunners) { - this.excludedRunners = excludedRunners; - } - - public void setIncludedTestMethods(Collection includedTestMethods) { - this.includedTestMethods = includedTestMethods; - } - - /** - * Creates a serializable subset of data for use in child processes - */ - public TestPluginArguments createMinionSettings() { - return new TestPluginArguments(getTestPlugin(), this.getGroupConfig(), this.getExcludedRunners(), - this.getIncludedTestMethods()); - } - - public String getTestPlugin() { - return this.testPlugin; - } - - public void setTestPlugin(String testPlugin) { - this.testPlugin = testPlugin; - } - - @Override - public String toString() { - return "ReportOptions [targetClasses=" + this.targetClasses - + ", excludedMethods=" + this.excludedMethods + ", excludedClasses=" - + this.excludedClasses + ", excludedTestClasses=" + this.excludedTestClasses - + ", codePaths=" + this.codePaths + ", reportDir=" + this.reportDir - + ", historyInputLocation=" + this.historyInputLocation - + ", historyOutputLocation=" + this.historyOutputLocation + ", sourceDirs=" - + this.sourceDirs + ", classPathElements=" + this.classPathElements - + ", mutators=" + this.mutators + ", features=" + this.features - + ", dependencyAnalysisMaxDistance=" + this.dependencyAnalysisMaxDistance - + ", jvmArgs=" + this.jvmArgs + ", numberOfThreads=" + this.numberOfThreads - + ", timeoutFactor=" + this.timeoutFactor + ", timeoutConstant=" - + this.timeoutConstant + ", targetTests=" + this.targetTests + ", loggingClasses=" - + this.loggingClasses + ", maxMutationsPerClass=" + this.maxMutationsPerClass - + ", verbose=" + this.verbose + ", failWhenNoMutations=" - + this.failWhenNoMutations + ", outputs=" + this.outputs + ", groupConfig=" - + this.groupConfig + ", mutationUnitSize=" + this.mutationUnitSize - + ", shouldCreateTimestampedReports=" + this.shouldCreateTimestampedReports - + ", detectInlinedCode=" + this.detectInlinedCode + ", exportLineCoverage=" - + this.exportLineCoverage + ", mutationThreshold=" + this.mutationThreshold - + ", coverageThreshold=" + this.coverageThreshold + ", mutationEngine=" - + this.mutationEngine + ", javaExecutable=" + this.javaExecutable - + ", includeLaunchClasspath=" + this.includeLaunchClasspath + ", properties=" - + this.properties + ", maxSurvivors=" + this.maxSurvivors + ", excludedRunners=" - + this.excludedRunners + ", testPlugin=" + this.testPlugin + ", includedTestMethods=" - + this.includedTestMethods + "]"; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import static org.pitest.functional.prelude.Prelude.not; +import static org.pitest.functional.prelude.Prelude.or; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Properties; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.pitest.classpath.ClassFilter; +import org.pitest.classpath.ClassPath; +import org.pitest.classpath.ClassPathRoot; +import org.pitest.classpath.PathFilter; +import org.pitest.classpath.ProjectClassPaths; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.functional.prelude.Prelude; +import org.pitest.help.Help; +import org.pitest.help.PitHelpError; +import org.pitest.mutationtest.build.PercentAndConstantTimeoutStrategy; +import org.pitest.mutationtest.incremental.FileWriterFactory; +import org.pitest.mutationtest.incremental.NullWriterFactory; +import org.pitest.mutationtest.incremental.WriterFactory; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.testapi.execute.Pitest; +import org.pitest.util.Glob; +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.Unchecked; + +// FIXME move all logic to SettingsFactory and turn into simple bean + +/** + * Big ball of user supplied options to configure various aspects of mutation + * testing. + * + */ +public class ReportOptions { + + public static final Collection LOGGING_CLASSES = Arrays + .asList( + "java.util.logging", + "org.apache.log4j", + "org.apache.logging.log4j", + "org.slf4j", + "org.apache.commons.logging"); + + private Collection targetClasses; + private Collection excludedMethods = Collections + .emptyList(); + + private Collection excludedClasses = Collections + .emptyList(); + + private Collection> excludedTestClasses = Collections + .emptyList(); + + private Collection codePaths; + + private String reportDir; + + private File historyInputLocation; + private File historyOutputLocation; + + private Collection sourceDirs; + private Collection classPathElements; + private Collection mutators; + private Collection features; + + private int dependencyAnalysisMaxDistance; + + private final List jvmArgs = new ArrayList<>(); + private int numberOfThreads = 0; + private float timeoutFactor = PercentAndConstantTimeoutStrategy.DEFAULT_FACTOR; + private long timeoutConstant = PercentAndConstantTimeoutStrategy.DEFAULT_CONSTANT; + + private Collection> targetTests; + + private Collection loggingClasses = new ArrayList<>(); + + private int maxMutationsPerClass; + + private boolean verbose = false; + private boolean failWhenNoMutations = false; + + private final Collection outputs = new LinkedHashSet<>(); + + private TestGroupConfig groupConfig; + + private int mutationUnitSize; + private boolean shouldCreateTimestampedReports = true; + private boolean detectInlinedCode = false; + private boolean exportLineCoverage = false; + private int mutationThreshold; + private int coverageThreshold; + + private String mutationEngine = "gregor"; + + private String javaExecutable; + + private boolean includeLaunchClasspath = true; + + private Properties properties; + + private int maxSurvivors; + + private Collection excludedRunners = new ArrayList<>(); + private Collection includedTestMethods = new ArrayList<>(); + + private String testPlugin = ""; + + public boolean isVerbose() { + return this.verbose; + } + + /** + * @return the reportDir + */ + public String getReportDir() { + return this.reportDir; + } + + /** + * @param reportDir + * the reportDir to set + */ + public void setReportDir(final String reportDir) { + this.reportDir = reportDir; + } + + /** + * @return the sourceDirs + */ + public Collection getSourceDirs() { + return this.sourceDirs; + } + + public Collection getClassPathElements() { + return this.classPathElements; + } + + public void setClassPathElements(final Collection classPathElements) { + this.classPathElements = classPathElements; + } + + /** + * @param sourceDirs + * the sourceDirs to set + */ + public void setSourceDirs(final Collection sourceDirs) { + this.sourceDirs = sourceDirs; + } + + /** + * @return the mutators + */ + public Collection getMutators() { + return this.mutators; + } + + /** + * @param mutators + * the mutators to set + */ + public void setMutators(final Collection mutators) { + this.mutators = mutators; + } + + + public Collection getFeatures() { + return this.features; + } + + public void setFeatures(Collection features) { + this.features = features; + } + + /** + * @return the dependencyAnalysisMaxDistance + */ + public int getDependencyAnalysisMaxDistance() { + return this.dependencyAnalysisMaxDistance; + } + + /** + * @param dependencyAnalysisMaxDistance + * the dependencyAnalysisMaxDistance to set + */ + public void setDependencyAnalysisMaxDistance( + final int dependencyAnalysisMaxDistance) { + this.dependencyAnalysisMaxDistance = dependencyAnalysisMaxDistance; + } + + public List getJvmArgs() { + return this.jvmArgs; + } + + public void addChildJVMArgs(final List args) { + this.jvmArgs.addAll(args); + } + + public ClassPath getClassPath() { + if (this.classPathElements != null) { + return createClassPathFromElements(); + } else { + return new ClassPath(); + } + } + + private ClassPath createClassPathFromElements() { + return new ClassPath( + FCollection.map(this.classPathElements, stringToFile())); + } + + private static Function stringToFile() { + return a -> new File(a); + } + + public Collection getTargetClasses() { + return this.targetClasses; + } + + + public Predicate getTargetClassesFilter() { + final Predicate filter = Prelude.and(or(Glob.toGlobPredicates(this.targetClasses)), + not(isBlackListed(Glob.toGlobPredicates(ReportOptions.this.excludedClasses)))); + checkNotTryingToMutateSelf(filter); + return filter; + } + + private void checkNotTryingToMutateSelf(final Predicate filter) { + if (filter.test(Pitest.class.getName())) { + throw new PitHelpError(Help.BAD_FILTER); + } + } + + public void setTargetClasses(final Collection targetClasses) { + this.targetClasses = targetClasses; + } + + public void setTargetTests( + final Collection> targetTestsPredicates) { + this.targetTests = targetTestsPredicates; + } + + public int getNumberOfThreads() { + return this.numberOfThreads; + } + + public void setNumberOfThreads(final int numberOfThreads) { + this.numberOfThreads = numberOfThreads; + } + + public float getTimeoutFactor() { + return this.timeoutFactor; + } + + public long getTimeoutConstant() { + return this.timeoutConstant; + } + + public void setTimeoutConstant(final long timeoutConstant) { + this.timeoutConstant = timeoutConstant; + } + + public void setTimeoutFactor(final float timeoutFactor) { + this.timeoutFactor = timeoutFactor; + } + + public Collection> getTargetTests() { + return this.targetTests; + } + + public Predicate getTargetTestsFilter() { + if ((this.targetTests == null) || this.targetTests.isEmpty()) { + // If target tests is not explicitly set we assume that the + // target classes predicate covers both classes and tests + return Prelude.and(or(Glob.toGlobPredicates(this.targetClasses)), + not(isBlackListed(ReportOptions.this.excludedTestClasses))); + } else { + return Prelude.and(or(this.targetTests), + not(isBlackListed(ReportOptions.this.excludedTestClasses))); + } + } + + private static Predicate isBlackListed( + final Collection> excludedClasses) { + return or(excludedClasses); + } + + public Collection getLoggingClasses() { + if (this.loggingClasses.isEmpty()) { + return LOGGING_CLASSES; + } else { + return this.loggingClasses; + } + } + + public void setLoggingClasses(final Collection loggingClasses) { + this.loggingClasses = loggingClasses; + } + + public Collection getExcludedMethods() { + return this.excludedMethods; + } + + public void setExcludedMethods( + final Collection excludedMethods) { + this.excludedMethods = excludedMethods; + } + + public void setVerbose(final boolean verbose) { + this.verbose = verbose; + } + + public void setExcludedClasses( + final Collection excludedClasses) { + this.excludedClasses = excludedClasses; + } + + public void setExcludedTestClasses( + final Collection> excludedClasses) { + this.excludedTestClasses = excludedClasses; + } + + + public void addOutputFormats(final Collection formats) { + this.outputs.addAll(formats); + } + + public Collection getOutputFormats() { + return this.outputs; + } + + public Collection getExcludedClasses() { + return this.excludedClasses; + } + + public Collection> getExcludedTestClasses() { + return this.excludedTestClasses; + } + + public boolean shouldFailWhenNoMutations() { + return this.failWhenNoMutations; + } + + public void setFailWhenNoMutations(final boolean failWhenNoMutations) { + this.failWhenNoMutations = failWhenNoMutations; + } + + public ProjectClassPaths getMutationClassPaths() { + + return new ProjectClassPaths(this.getClassPath(), createClassesFilter(), + createPathFilter()); + } + + public ClassFilter createClassesFilter() { + return new ClassFilter(this.getTargetTestsFilter(), + this.getTargetClassesFilter()); + } + + private PathFilter createPathFilter() { + return new PathFilter(createCodePathFilter(), + not(new DefaultDependencyPathPredicate())); + } + + private Predicate createCodePathFilter() { + if ((this.codePaths != null) && !this.codePaths.isEmpty()) { + return new PathNamePredicate(Prelude.or(Glob + .toGlobPredicates(this.codePaths))); + } else { + return new DefaultCodePathPredicate(); + } + } + + public Collection getCodePaths() { + return this.codePaths; + } + + public void setCodePaths(final Collection codePaths) { + this.codePaths = codePaths; + } + + public void setGroupConfig(final TestGroupConfig groupConfig) { + this.groupConfig = groupConfig; + } + + public TestGroupConfig getGroupConfig() { + return this.groupConfig; + } + + public int getMutationUnitSize() { + return this.mutationUnitSize; + } + + public void setMutationUnitSize(final int size) { + this.mutationUnitSize = size; + } + + public ResultOutputStrategy getReportDirectoryStrategy() { + return new DirectoryResultOutputStrategy(getReportDir(), + pickDirectoryStrategy()); + } + + public void setShouldCreateTimestampedReports( + final boolean shouldCreateTimestampedReports) { + this.shouldCreateTimestampedReports = shouldCreateTimestampedReports; + } + + private ReportDirCreationStrategy pickDirectoryStrategy() { + if (this.shouldCreateTimestampedReports) { + return new DatedDirectoryReportDirCreationStrategy(); + } else { + return new UndatedReportDirCreationStrategy(); + } + } + + public boolean shouldCreateTimeStampedReports() { + return this.shouldCreateTimestampedReports; + } + + public boolean isDetectInlinedCode() { + return this.detectInlinedCode; + } + + public void setDetectInlinedCode(final boolean b) { + this.detectInlinedCode = b; + } + + public WriterFactory createHistoryWriter() { + if (this.historyOutputLocation == null) { + return new NullWriterFactory(); + } + + return new FileWriterFactory(this.historyOutputLocation); + } + + public Optional createHistoryReader() { + if (this.historyInputLocation == null) { + return Optional.empty(); + } + + try { + if (this.historyInputLocation.exists() + && (this.historyInputLocation.length() > 0)) { + return Optional. ofNullable(new InputStreamReader(new FileInputStream( + this.historyInputLocation), "UTF-8")); + } + return Optional.empty(); + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex); + } + } + + public void setHistoryInputLocation(final File historyInputLocation) { + this.historyInputLocation = historyInputLocation; + } + + public void setHistoryOutputLocation(final File historyOutputLocation) { + this.historyOutputLocation = historyOutputLocation; + } + + public File getHistoryInputLocation() { + return this.historyInputLocation; + } + + public File getHistoryOutputLocation() { + return this.historyOutputLocation; + } + + public void setExportLineCoverage(final boolean value) { + this.exportLineCoverage = value; + } + + public boolean shouldExportLineCoverage() { + return this.exportLineCoverage; + } + + public int getMutationThreshold() { + return this.mutationThreshold; + } + + public void setMutationThreshold(final int value) { + this.mutationThreshold = value; + } + + public String getMutationEngine() { + return this.mutationEngine; + } + + public void setMutationEngine(final String mutationEngine) { + this.mutationEngine = mutationEngine; + } + + public int getCoverageThreshold() { + return this.coverageThreshold; + } + + public void setCoverageThreshold(final int coverageThreshold) { + this.coverageThreshold = coverageThreshold; + } + + public String getJavaExecutable() { + return this.javaExecutable; + } + + public void setJavaExecutable(final String javaExecutable) { + this.javaExecutable = javaExecutable; + } + + public void setIncludeLaunchClasspath(final boolean b) { + this.includeLaunchClasspath = b; + } + + public boolean isIncludeLaunchClasspath() { + return this.includeLaunchClasspath; + } + + public Properties getFreeFormProperties() { + return this.properties; + } + + public void setFreeFormProperties(Properties props) { + this.properties = props; + } + + public int getMaximumAllowedSurvivors() { + return this.maxSurvivors; + } + + public void setMaximumAllowedSurvivors(int maxSurvivors) { + this.maxSurvivors = maxSurvivors; + } + + public Collection getExcludedRunners() { + return this.excludedRunners; + } + + public Collection getIncludedTestMethods() { + return this.includedTestMethods; + } + + public void setExcludedRunners(Collection excludedRunners) { + this.excludedRunners = excludedRunners; + } + + public void setIncludedTestMethods(Collection includedTestMethods) { + this.includedTestMethods = includedTestMethods; + } + + /** + * Creates a serializable subset of data for use in child processes + */ + public TestPluginArguments createMinionSettings() { + return new TestPluginArguments(getTestPlugin(), this.getGroupConfig(), this.getExcludedRunners(), + this.getIncludedTestMethods()); + } + + public String getTestPlugin() { + return this.testPlugin; + } + + public void setTestPlugin(String testPlugin) { + this.testPlugin = testPlugin; + } + + @Override + public String toString() { + return "ReportOptions [targetClasses=" + this.targetClasses + + ", excludedMethods=" + this.excludedMethods + ", excludedClasses=" + + this.excludedClasses + ", excludedTestClasses=" + this.excludedTestClasses + + ", codePaths=" + this.codePaths + ", reportDir=" + this.reportDir + + ", historyInputLocation=" + this.historyInputLocation + + ", historyOutputLocation=" + this.historyOutputLocation + ", sourceDirs=" + + this.sourceDirs + ", classPathElements=" + this.classPathElements + + ", mutators=" + this.mutators + ", features=" + this.features + + ", dependencyAnalysisMaxDistance=" + this.dependencyAnalysisMaxDistance + + ", jvmArgs=" + this.jvmArgs + ", numberOfThreads=" + this.numberOfThreads + + ", timeoutFactor=" + this.timeoutFactor + ", timeoutConstant=" + + this.timeoutConstant + ", targetTests=" + this.targetTests + ", loggingClasses=" + + this.loggingClasses + ", maxMutationsPerClass=" + this.maxMutationsPerClass + + ", verbose=" + this.verbose + ", failWhenNoMutations=" + + this.failWhenNoMutations + ", outputs=" + this.outputs + ", groupConfig=" + + this.groupConfig + ", mutationUnitSize=" + this.mutationUnitSize + + ", shouldCreateTimestampedReports=" + this.shouldCreateTimestampedReports + + ", detectInlinedCode=" + this.detectInlinedCode + ", exportLineCoverage=" + + this.exportLineCoverage + ", mutationThreshold=" + this.mutationThreshold + + ", coverageThreshold=" + this.coverageThreshold + ", mutationEngine=" + + this.mutationEngine + ", javaExecutable=" + this.javaExecutable + + ", includeLaunchClasspath=" + this.includeLaunchClasspath + ", properties=" + + this.properties + ", maxSurvivors=" + this.maxSurvivors + ", excludedRunners=" + + this.excludedRunners + ", testPlugin=" + this.testPlugin + ", includedTestMethods=" + + this.includedTestMethods + "]"; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/SettingsFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/SettingsFactory.java index ef2244791..b0b01073b 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/SettingsFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/SettingsFactory.java @@ -1,166 +1,166 @@ -package org.pitest.mutationtest.config; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.pitest.coverage.CoverageExporter; -import org.pitest.coverage.execute.CoverageOptions; -import org.pitest.coverage.export.DefaultCoverageExporter; -import org.pitest.coverage.export.NullCoverageExporter; -import org.pitest.functional.FCollection; -import org.pitest.functional.SideEffect1; -import org.pitest.mutationtest.MutationEngineFactory; -import org.pitest.mutationtest.MutationResultListenerFactory; -import org.pitest.mutationtest.build.CompoundInterceptorFactory; -import org.pitest.mutationtest.build.DefaultMutationGrouperFactory; -import org.pitest.mutationtest.build.DefaultTestPrioritiserFactory; -import org.pitest.mutationtest.build.MutationGrouperFactory; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.mutationtest.build.TestPrioritiserFactory; -import org.pitest.plugin.Feature; -import org.pitest.plugin.FeatureParser; -import org.pitest.plugin.FeatureSelector; -import org.pitest.plugin.FeatureSetting; -import org.pitest.plugin.ProvidesFeature; -import org.pitest.process.DefaultJavaExecutableLocator; -import org.pitest.process.JavaExecutableLocator; -import org.pitest.process.KnownLocationJavaExecutableLocator; -import org.pitest.util.PitError; -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.StringUtil; - -public class SettingsFactory { - - private final ReportOptions options; - private final PluginServices plugins; - - public SettingsFactory(final ReportOptions options, - final PluginServices plugins) { - this.options = options; - this.plugins = plugins; - } - - public ResultOutputStrategy getOutputStrategy() { - return this.options.getReportDirectoryStrategy(); - } - - public CoverageExporter createCoverageExporter() { - if (this.options.shouldExportLineCoverage()) { - return new DefaultCoverageExporter(getOutputStrategy()); - } else { - return new NullCoverageExporter(); - } - } - - public MutationEngineFactory createEngine() { - for (final MutationEngineFactory each : this.plugins.findMutationEngines()) { - if (each.name().equals(this.options.getMutationEngine())) { - return each; - } - } - throw new PitError("Could not load requested engine " - + this.options.getMutationEngine()); - } - - public MutationResultListenerFactory createListener() { - return new CompoundListenerFactory(findListeners()); - } - - public JavaExecutableLocator getJavaExecutable() { - if (this.options.getJavaExecutable() != null) { - return new KnownLocationJavaExecutableLocator( - this.options.getJavaExecutable()); - } - return new DefaultJavaExecutableLocator(); - } - - public MutationGrouperFactory getMutationGrouper() { - final Collection groupers = this.plugins - .findGroupers(); - return firstOrDefault(groupers, new DefaultMutationGrouperFactory()); - } - - public void describeFeatures(SideEffect1 enabled, SideEffect1 disabled) { - final FeatureParser parser = new FeatureParser(); - final Collection available = new ArrayList<>(this.plugins.findInterceptors()); - final List settings = parser.parseFeatures(this.options.getFeatures()); - final FeatureSelector selector = new FeatureSelector<>(settings, available); - - final HashSet enabledFeatures = new HashSet<>(); - FCollection.mapTo(selector.getActiveFeatures(), toFeature(), enabledFeatures); - - FCollection.forEach(enabledFeatures, enabled); - - final HashSet disabledFeatures = new HashSet<>(); - FCollection.mapTo(available, toFeature(), disabledFeatures); - disabledFeatures.removeAll(enabledFeatures); - - FCollection.forEach(disabledFeatures, disabled); - } - - - public TestPrioritiserFactory getTestPrioritiser() { - final Collection testPickers = this.plugins - .findTestPrioritisers(); - return firstOrDefault(testPickers, new DefaultTestPrioritiserFactory()); - } - - public CoverageOptions createCoverageOptions() { - return new CoverageOptions( - this.options.getTargetClasses(), this.options.getExcludedClasses(), - this.options.createMinionSettings(), this.options.isVerbose(), - this.options.getDependencyAnalysisMaxDistance()); - } - - public CompoundInterceptorFactory getInterceptor() { - final Collection interceptors = this.plugins - .findInterceptors(); - final FeatureParser parser = new FeatureParser(); - return new CompoundInterceptorFactory(parser.parseFeatures(this.options.getFeatures()), new ArrayList<>(interceptors)); - } - - private static Predicate nameMatches( - final Iterable outputFormats) { - return a -> FCollection.contains(outputFormats, equalsIgnoreCase(a.name())); - } - - private Iterable findListeners() { - final Iterable listeners = this.plugins - .findListeners(); - final Collection matches = FCollection - .filter(listeners, nameMatches(this.options.getOutputFormats())); - if (matches.size() < this.options.getOutputFormats().size()) { - throw new PitError("Unknown listener requested in " - + StringUtil.join(this.options.getOutputFormats(), ",")); - } - return matches; - } - - private static Predicate equalsIgnoreCase(final String other) { - return a -> a.equalsIgnoreCase(other); - } - - private static T firstOrDefault(final Collection found, - final T defaultInstance) { - if (found.isEmpty()) { - return defaultInstance; - } - if (found.size() > 1) { - throw new PitError( - "Multiple implementations of plugin detected on classpath"); - } - return found.iterator().next(); - } - - - - private static Function toFeature() { - return a -> a.provides(); - } - - -} +package org.pitest.mutationtest.config; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.pitest.coverage.CoverageExporter; +import org.pitest.coverage.execute.CoverageOptions; +import org.pitest.coverage.export.DefaultCoverageExporter; +import org.pitest.coverage.export.NullCoverageExporter; +import org.pitest.functional.FCollection; +import org.pitest.functional.SideEffect1; +import org.pitest.mutationtest.MutationEngineFactory; +import org.pitest.mutationtest.MutationResultListenerFactory; +import org.pitest.mutationtest.build.CompoundInterceptorFactory; +import org.pitest.mutationtest.build.DefaultMutationGrouperFactory; +import org.pitest.mutationtest.build.DefaultTestPrioritiserFactory; +import org.pitest.mutationtest.build.MutationGrouperFactory; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.mutationtest.build.TestPrioritiserFactory; +import org.pitest.plugin.Feature; +import org.pitest.plugin.FeatureParser; +import org.pitest.plugin.FeatureSelector; +import org.pitest.plugin.FeatureSetting; +import org.pitest.plugin.ProvidesFeature; +import org.pitest.process.DefaultJavaExecutableLocator; +import org.pitest.process.JavaExecutableLocator; +import org.pitest.process.KnownLocationJavaExecutableLocator; +import org.pitest.util.PitError; +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.StringUtil; + +public class SettingsFactory { + + private final ReportOptions options; + private final PluginServices plugins; + + public SettingsFactory(final ReportOptions options, + final PluginServices plugins) { + this.options = options; + this.plugins = plugins; + } + + public ResultOutputStrategy getOutputStrategy() { + return this.options.getReportDirectoryStrategy(); + } + + public CoverageExporter createCoverageExporter() { + if (this.options.shouldExportLineCoverage()) { + return new DefaultCoverageExporter(getOutputStrategy()); + } else { + return new NullCoverageExporter(); + } + } + + public MutationEngineFactory createEngine() { + for (final MutationEngineFactory each : this.plugins.findMutationEngines()) { + if (each.name().equals(this.options.getMutationEngine())) { + return each; + } + } + throw new PitError("Could not load requested engine " + + this.options.getMutationEngine()); + } + + public MutationResultListenerFactory createListener() { + return new CompoundListenerFactory(findListeners()); + } + + public JavaExecutableLocator getJavaExecutable() { + if (this.options.getJavaExecutable() != null) { + return new KnownLocationJavaExecutableLocator( + this.options.getJavaExecutable()); + } + return new DefaultJavaExecutableLocator(); + } + + public MutationGrouperFactory getMutationGrouper() { + final Collection groupers = this.plugins + .findGroupers(); + return firstOrDefault(groupers, new DefaultMutationGrouperFactory()); + } + + public void describeFeatures(SideEffect1 enabled, SideEffect1 disabled) { + final FeatureParser parser = new FeatureParser(); + final Collection available = new ArrayList<>(this.plugins.findInterceptors()); + final List settings = parser.parseFeatures(this.options.getFeatures()); + final FeatureSelector selector = new FeatureSelector<>(settings, available); + + final HashSet enabledFeatures = new HashSet<>(); + FCollection.mapTo(selector.getActiveFeatures(), toFeature(), enabledFeatures); + + FCollection.forEach(enabledFeatures, enabled); + + final HashSet disabledFeatures = new HashSet<>(); + FCollection.mapTo(available, toFeature(), disabledFeatures); + disabledFeatures.removeAll(enabledFeatures); + + FCollection.forEach(disabledFeatures, disabled); + } + + + public TestPrioritiserFactory getTestPrioritiser() { + final Collection testPickers = this.plugins + .findTestPrioritisers(); + return firstOrDefault(testPickers, new DefaultTestPrioritiserFactory()); + } + + public CoverageOptions createCoverageOptions() { + return new CoverageOptions( + this.options.getTargetClasses(), this.options.getExcludedClasses(), + this.options.createMinionSettings(), this.options.isVerbose(), + this.options.getDependencyAnalysisMaxDistance()); + } + + public CompoundInterceptorFactory getInterceptor() { + final Collection interceptors = this.plugins + .findInterceptors(); + final FeatureParser parser = new FeatureParser(); + return new CompoundInterceptorFactory(parser.parseFeatures(this.options.getFeatures()), new ArrayList<>(interceptors)); + } + + private static Predicate nameMatches( + final Iterable outputFormats) { + return a -> FCollection.contains(outputFormats, equalsIgnoreCase(a.name())); + } + + private Iterable findListeners() { + final Iterable listeners = this.plugins + .findListeners(); + final Collection matches = FCollection + .filter(listeners, nameMatches(this.options.getOutputFormats())); + if (matches.size() < this.options.getOutputFormats().size()) { + throw new PitError("Unknown listener requested in " + + StringUtil.join(this.options.getOutputFormats(), ",")); + } + return matches; + } + + private static Predicate equalsIgnoreCase(final String other) { + return a -> a.equalsIgnoreCase(other); + } + + private static T firstOrDefault(final Collection found, + final T defaultInstance) { + if (found.isEmpty()) { + return defaultInstance; + } + if (found.size() > 1) { + throw new PitError( + "Multiple implementations of plugin detected on classpath"); + } + return found.iterator().next(); + } + + + + private static Function toFeature() { + return a -> a.provides(); + } + + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/config/UndatedReportDirCreationStrategy.java b/pitest-entry/src/main/java/org/pitest/mutationtest/config/UndatedReportDirCreationStrategy.java index 92b9b40cd..5fdac8b7d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/config/UndatedReportDirCreationStrategy.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/config/UndatedReportDirCreationStrategy.java @@ -1,15 +1,15 @@ -package org.pitest.mutationtest.config; - -import java.io.File; - -public class UndatedReportDirCreationStrategy implements -ReportDirCreationStrategy { - - @Override - public File createReportDir(final String base) { - final File reportDir = new File(base); - reportDir.mkdirs(); - return reportDir; - } - -} +package org.pitest.mutationtest.config; + +import java.io.File; + +public class UndatedReportDirCreationStrategy implements +ReportDirCreationStrategy { + + @Override + public File createReportDir(final String base) { + final File reportDir = new File(base); + reportDir.mkdirs(); + return reportDir; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationAnalysisExecutor.java b/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationAnalysisExecutor.java index 6a3ef7526..f75757a38 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationAnalysisExecutor.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationAnalysisExecutor.java @@ -1,86 +1,86 @@ -package org.pitest.mutationtest.execute; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; - -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationMetaData; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.build.MutationAnalysisUnit; -import org.pitest.util.Log; -import org.pitest.util.Unchecked; - -public class MutationAnalysisExecutor { - - private static final Logger LOG = Log.getLogger(); - - private final List listeners; - private final ThreadPoolExecutor executor; - - public MutationAnalysisExecutor(int numberOfThreads, - List listeners) { - this.listeners = listeners; - this.executor = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, - 10, TimeUnit.SECONDS, new LinkedBlockingQueue(), - Executors.defaultThreadFactory()); - } - - // entry point for mutation testing - public void run(final List testUnits) { - - LOG.fine("Running " + testUnits.size() + " units"); - - signalRunStartToAllListeners(); - - final List> results = new ArrayList<>( - testUnits.size()); - - for (final MutationAnalysisUnit unit : testUnits) { - results.add(this.executor.submit(unit)); - } - - this.executor.shutdown(); - - try { - processResult(results); - } catch (final InterruptedException e) { - throw Unchecked.translateCheckedException(e); - } catch (final ExecutionException e) { - throw Unchecked.translateCheckedException(e); - } - - signalRunEndToAllListeners(); - - } - - private void processResult(List> results) - throws InterruptedException, ExecutionException { - for (final Future f : results) { - final MutationMetaData r = f.get(); - for (final MutationResultListener l : this.listeners) { - for (final ClassMutationResults cr : r.toClassResults()) { - l.handleMutationResult(cr); - } - } - } - } - - private void signalRunStartToAllListeners() { - FCollection.forEach(this.listeners, - a -> a.runStart()); - } - - private void signalRunEndToAllListeners() { - FCollection.forEach(this.listeners, - a -> a.runEnd()); - } - -} +package org.pitest.mutationtest.execute; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; + +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationMetaData; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.build.MutationAnalysisUnit; +import org.pitest.util.Log; +import org.pitest.util.Unchecked; + +public class MutationAnalysisExecutor { + + private static final Logger LOG = Log.getLogger(); + + private final List listeners; + private final ThreadPoolExecutor executor; + + public MutationAnalysisExecutor(int numberOfThreads, + List listeners) { + this.listeners = listeners; + this.executor = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, + 10, TimeUnit.SECONDS, new LinkedBlockingQueue(), + Executors.defaultThreadFactory()); + } + + // entry point for mutation testing + public void run(final List testUnits) { + + LOG.fine("Running " + testUnits.size() + " units"); + + signalRunStartToAllListeners(); + + final List> results = new ArrayList<>( + testUnits.size()); + + for (final MutationAnalysisUnit unit : testUnits) { + results.add(this.executor.submit(unit)); + } + + this.executor.shutdown(); + + try { + processResult(results); + } catch (final InterruptedException e) { + throw Unchecked.translateCheckedException(e); + } catch (final ExecutionException e) { + throw Unchecked.translateCheckedException(e); + } + + signalRunEndToAllListeners(); + + } + + private void processResult(List> results) + throws InterruptedException, ExecutionException { + for (final Future f : results) { + final MutationMetaData r = f.get(); + for (final MutationResultListener l : this.listeners) { + for (final ClassMutationResults cr : r.toClassResults()) { + l.handleMutationResult(cr); + } + } + } + } + + private void signalRunStartToAllListeners() { + FCollection.forEach(this.listeners, + a -> a.runStart()); + } + + private void signalRunEndToAllListeners() { + FCollection.forEach(this.listeners, + a -> a.runEnd()); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationTestCommunicationThread.java b/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationTestCommunicationThread.java index c54816a4e..c62e0bee9 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationTestCommunicationThread.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationTestCommunicationThread.java @@ -1,99 +1,99 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.execute; - -import java.net.ServerSocket; -import java.util.Map; -import java.util.logging.Logger; - -import org.pitest.functional.SideEffect1; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.util.CommunicationThread; -import org.pitest.util.Id; -import org.pitest.util.Log; -import org.pitest.util.ReceiveStrategy; -import org.pitest.util.SafeDataInputStream; -import org.pitest.util.SafeDataOutputStream; - -public class MutationTestCommunicationThread extends CommunicationThread { - - private static final Logger LOG = Log.getLogger(); - - private static class SendData implements SideEffect1 { - private final MinionArguments arguments; - - SendData(final MinionArguments arguments) { - this.arguments = arguments; - } - - @Override - public void apply(final SafeDataOutputStream dos) { - dos.write(this.arguments); - dos.flush(); - } - } - - private static class Receive implements ReceiveStrategy { - - private final Map idMap; - - Receive(final Map idMap) { - this.idMap = idMap; - } - - @Override - public void apply(final byte control, final SafeDataInputStream is) { - switch (control) { - case Id.DESCRIBE: - handleDescribe(is); - break; - case Id.REPORT: - handleReport(is); - break; - } - } - - private void handleReport(final SafeDataInputStream is) { - final MutationIdentifier mutation = is.read(MutationIdentifier.class); - final MutationStatusTestPair value = is - .read(MutationStatusTestPair.class); - this.idMap.put(mutation, value); - LOG.fine(mutation + " " + value); - } - - private void handleDescribe(final SafeDataInputStream is) { - final MutationIdentifier mutation = is.read(MutationIdentifier.class); - this.idMap.put(mutation, new MutationStatusTestPair(1, - DetectionStatus.STARTED)); - } - - } - - private final Map idMap; - - public MutationTestCommunicationThread(final ServerSocket socket, - final MinionArguments arguments, - final Map idMap) { - super(socket, new SendData(arguments), new Receive(idMap)); - this.idMap = idMap; - } - - public MutationStatusTestPair getStatus(final MutationIdentifier id) { - return this.idMap.get(id); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.execute; + +import java.net.ServerSocket; +import java.util.Map; +import java.util.logging.Logger; + +import org.pitest.functional.SideEffect1; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.util.CommunicationThread; +import org.pitest.util.Id; +import org.pitest.util.Log; +import org.pitest.util.ReceiveStrategy; +import org.pitest.util.SafeDataInputStream; +import org.pitest.util.SafeDataOutputStream; + +public class MutationTestCommunicationThread extends CommunicationThread { + + private static final Logger LOG = Log.getLogger(); + + private static class SendData implements SideEffect1 { + private final MinionArguments arguments; + + SendData(final MinionArguments arguments) { + this.arguments = arguments; + } + + @Override + public void apply(final SafeDataOutputStream dos) { + dos.write(this.arguments); + dos.flush(); + } + } + + private static class Receive implements ReceiveStrategy { + + private final Map idMap; + + Receive(final Map idMap) { + this.idMap = idMap; + } + + @Override + public void apply(final byte control, final SafeDataInputStream is) { + switch (control) { + case Id.DESCRIBE: + handleDescribe(is); + break; + case Id.REPORT: + handleReport(is); + break; + } + } + + private void handleReport(final SafeDataInputStream is) { + final MutationIdentifier mutation = is.read(MutationIdentifier.class); + final MutationStatusTestPair value = is + .read(MutationStatusTestPair.class); + this.idMap.put(mutation, value); + LOG.fine(mutation + " " + value); + } + + private void handleDescribe(final SafeDataInputStream is) { + final MutationIdentifier mutation = is.read(MutationIdentifier.class); + this.idMap.put(mutation, new MutationStatusTestPair(1, + DetectionStatus.STARTED)); + } + + } + + private final Map idMap; + + public MutationTestCommunicationThread(final ServerSocket socket, + final MinionArguments arguments, + final Map idMap) { + super(socket, new SendData(arguments), new Receive(idMap)); + this.idMap = idMap; + } + + public MutationStatusTestPair getStatus(final MutationIdentifier id) { + return this.idMap.get(id); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationTestProcess.java b/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationTestProcess.java index f4f047753..012cf8d9c 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationTestProcess.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/execute/MutationTestProcess.java @@ -1,54 +1,54 @@ -package org.pitest.mutationtest.execute; - -import java.io.IOException; -import java.net.ServerSocket; -import java.util.HashMap; - -import org.pitest.mutationtest.MutationStatusMap; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.process.ProcessArgs; -import org.pitest.process.WrappingProcess; -import org.pitest.util.ExitCode; - -public class MutationTestProcess { - - private final WrappingProcess process; - private final MutationTestCommunicationThread thread; - - public MutationTestProcess(final ServerSocket socket, - final ProcessArgs processArgs, final MinionArguments arguments) { - this.process = new WrappingProcess(socket.getLocalPort(), processArgs, - MutationTestMinion.class); - this.thread = new MutationTestCommunicationThread(socket, arguments, - new HashMap()); - - } - - public void start() throws IOException, InterruptedException { - this.thread.start(); - this.process.start(); - } - - public void results(final MutationStatusMap allmutations) throws IOException { - - for (final MutationDetails each : allmutations.allMutations()) { - final MutationStatusTestPair status = this.thread.getStatus(each.getId()); - if (status != null) { - allmutations.setStatusForMutation(each, status); - } - } - - } - - public ExitCode waitToDie() { - try { - return this.thread.waitToFinish(); - } finally { - this.process.destroy(); - } - - } - -} +package org.pitest.mutationtest.execute; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.HashMap; + +import org.pitest.mutationtest.MutationStatusMap; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.process.ProcessArgs; +import org.pitest.process.WrappingProcess; +import org.pitest.util.ExitCode; + +public class MutationTestProcess { + + private final WrappingProcess process; + private final MutationTestCommunicationThread thread; + + public MutationTestProcess(final ServerSocket socket, + final ProcessArgs processArgs, final MinionArguments arguments) { + this.process = new WrappingProcess(socket.getLocalPort(), processArgs, + MutationTestMinion.class); + this.thread = new MutationTestCommunicationThread(socket, arguments, + new HashMap()); + + } + + public void start() throws IOException, InterruptedException { + this.thread.start(); + this.process.start(); + } + + public void results(final MutationStatusMap allmutations) throws IOException { + + for (final MutationDetails each : allmutations.allMutations()) { + final MutationStatusTestPair status = this.thread.getStatus(each.getId()); + if (status != null) { + allmutations.setStatusForMutation(each, status); + } + } + + } + + public ExitCode waitToDie() { + try { + return this.thread.waitToFinish(); + } finally { + this.process.destroy(); + } + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/filter/LimitNumberOfMutationPerClassFilter.java b/pitest-entry/src/main/java/org/pitest/mutationtest/filter/LimitNumberOfMutationPerClassFilter.java index b01cde943..4612d8323 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/filter/LimitNumberOfMutationPerClassFilter.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/filter/LimitNumberOfMutationPerClassFilter.java @@ -1,80 +1,80 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.filter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -public class LimitNumberOfMutationPerClassFilter implements MutationInterceptor { - - private final int maxMutationsPerClass; - - public LimitNumberOfMutationPerClassFilter(final int max) { - this.maxMutationsPerClass = max; - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - if (mutations.size() <= this.maxMutationsPerClass) { - return mutations; - } else { - return createEvenlyDistributedSampling(mutations); - } - } - - private Collection createEvenlyDistributedSampling( - final Collection mutations) { - final Collection filtered = new ArrayList<>( - this.maxMutationsPerClass); - final int step = (mutations.size() / this.maxMutationsPerClass); - final Iterator it = mutations.iterator(); - while (it.hasNext()) { - int i = 0; - MutationDetails value = null; - while (it.hasNext() && (i != step)) { - value = it.next(); - i++; - } - if (filtered.size() != this.maxMutationsPerClass) { - filtered.add(value); - } - } - - return filtered; - } - - @Override - public InterceptorType type() { - return InterceptorType.FILTER; - } - - @Override - public void begin(ClassTree clazz) { - // noop - } - - @Override - public void end() { - // noop - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.filter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +public class LimitNumberOfMutationPerClassFilter implements MutationInterceptor { + + private final int maxMutationsPerClass; + + public LimitNumberOfMutationPerClassFilter(final int max) { + this.maxMutationsPerClass = max; + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + if (mutations.size() <= this.maxMutationsPerClass) { + return mutations; + } else { + return createEvenlyDistributedSampling(mutations); + } + } + + private Collection createEvenlyDistributedSampling( + final Collection mutations) { + final Collection filtered = new ArrayList<>( + this.maxMutationsPerClass); + final int step = (mutations.size() / this.maxMutationsPerClass); + final Iterator it = mutations.iterator(); + while (it.hasNext()) { + int i = 0; + MutationDetails value = null; + while (it.hasNext() && (i != step)) { + value = it.next(); + i++; + } + if (filtered.size() != this.maxMutationsPerClass) { + filtered.add(value); + } + } + + return filtered; + } + + @Override + public InterceptorType type() { + return InterceptorType.FILTER; + } + + @Override + public void begin(ClassTree clazz) { + // noop + } + + @Override + public void end() { + // noop + } +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/filter/LimitNumberOfMutationsPerClassFilterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/filter/LimitNumberOfMutationsPerClassFilterFactory.java index b33a4c354..6d9b69859 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/filter/LimitNumberOfMutationsPerClassFilterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/filter/LimitNumberOfMutationsPerClassFilterFactory.java @@ -1,36 +1,36 @@ -package org.pitest.mutationtest.filter; - -import java.util.Optional; -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; -import org.pitest.plugin.FeatureParameter; - -public class LimitNumberOfMutationsPerClassFilterFactory implements MutationInterceptorFactory { - - private final FeatureParameter limit = FeatureParameter.named("limit") - .withDescription("Integer value for maximum mutations to create per class"); - - @Override - public String description() { - return "Max mutations per class limit"; - } - - @Override - public Feature provides() { - return Feature.named("CLASSLIMIT") - .withDescription("Limits the maximum number of mutations per class") - .withParameter(this.limit); - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - final Optional max = params.getInteger(this.limit); - if (!max.isPresent()) { - throw new IllegalArgumentException("Max mutation per class filter requires a limit parameter"); - } - return new LimitNumberOfMutationPerClassFilter(max.get()); - } - -} +package org.pitest.mutationtest.filter; + +import java.util.Optional; +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; +import org.pitest.plugin.FeatureParameter; + +public class LimitNumberOfMutationsPerClassFilterFactory implements MutationInterceptorFactory { + + private final FeatureParameter limit = FeatureParameter.named("limit") + .withDescription("Integer value for maximum mutations to create per class"); + + @Override + public String description() { + return "Max mutations per class limit"; + } + + @Override + public Feature provides() { + return Feature.named("CLASSLIMIT") + .withDescription("Limits the maximum number of mutations per class") + .withParameter(this.limit); + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + final Optional max = params.getInteger(this.limit); + if (!max.isPresent()) { + throw new IllegalArgumentException("Max mutation per class filter requires a limit parameter"); + } + return new LimitNumberOfMutationPerClassFilter(max.get()); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/CodeHistory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/CodeHistory.java index af75cb5f7..a4773f419 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/CodeHistory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/CodeHistory.java @@ -1,18 +1,18 @@ -package org.pitest.mutationtest.incremental; - -import java.math.BigInteger; - -import org.pitest.classinfo.ClassName; -import java.util.Optional; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public interface CodeHistory { - - Optional getPreviousResult(MutationIdentifier id); - - boolean hasClassChanged(ClassName className); - - boolean hasCoverageChanged(ClassName className, BigInteger currentCoverage); - -} +package org.pitest.mutationtest.incremental; + +import java.math.BigInteger; + +import org.pitest.classinfo.ClassName; +import java.util.Optional; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationIdentifier; + +public interface CodeHistory { + + Optional getPreviousResult(MutationIdentifier id); + + boolean hasClassChanged(ClassName className); + + boolean hasCoverageChanged(ClassName className, BigInteger currentCoverage); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/DefaultCodeHistory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/DefaultCodeHistory.java index 2790683c0..4b9761209 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/DefaultCodeHistory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/DefaultCodeHistory.java @@ -1,61 +1,61 @@ -package org.pitest.mutationtest.incremental; - -import java.math.BigInteger; -import java.util.Map; - -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassInfoSource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.CodeSource; -import java.util.Optional; -import org.pitest.mutationtest.ClassHistory; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public class DefaultCodeHistory implements CodeHistory { - - private final ClassInfoSource code; - private final Map previousResults; - private final Map previousClassPath; - - public DefaultCodeHistory(final CodeSource code, - final HistoryStore historyStore) { - this(code, historyStore.getHistoricResults(), historyStore - .getHistoricClassPath()); - } - - public DefaultCodeHistory(final ClassInfoSource code, - final Map previousResults, - final Map previousClassPath) { - this.code = code; - this.previousResults = previousResults; - this.previousClassPath = previousClassPath; - } - - @Override - public Optional getPreviousResult( - final MutationIdentifier id) { - return Optional.ofNullable(this.previousResults.get(id)); - } - - @Override - public boolean hasClassChanged(final ClassName className) { - final ClassHistory historic = this.previousClassPath.get(className); - if (historic == null) { - return true; - } - - final Optional current = this.code.fetchClass(className); - return !current.get().getHierarchicalId().equals(historic.getId()); - - } - - @Override - public boolean hasCoverageChanged(final ClassName className, - final BigInteger currentCoverage) { - return !this.previousClassPath.get(className).getCoverageId() - .equals(currentCoverage.toString(16)); - } - -} +package org.pitest.mutationtest.incremental; + +import java.math.BigInteger; +import java.util.Map; + +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassInfoSource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.CodeSource; +import java.util.Optional; +import org.pitest.mutationtest.ClassHistory; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationIdentifier; + +public class DefaultCodeHistory implements CodeHistory { + + private final ClassInfoSource code; + private final Map previousResults; + private final Map previousClassPath; + + public DefaultCodeHistory(final CodeSource code, + final HistoryStore historyStore) { + this(code, historyStore.getHistoricResults(), historyStore + .getHistoricClassPath()); + } + + public DefaultCodeHistory(final ClassInfoSource code, + final Map previousResults, + final Map previousClassPath) { + this.code = code; + this.previousResults = previousResults; + this.previousClassPath = previousClassPath; + } + + @Override + public Optional getPreviousResult( + final MutationIdentifier id) { + return Optional.ofNullable(this.previousResults.get(id)); + } + + @Override + public boolean hasClassChanged(final ClassName className) { + final ClassHistory historic = this.previousClassPath.get(className); + if (historic == null) { + return true; + } + + final Optional current = this.code.fetchClass(className); + return !current.get().getHierarchicalId().equals(historic.getId()); + + } + + @Override + public boolean hasCoverageChanged(final ClassName className, + final BigInteger currentCoverage) { + return !this.previousClassPath.get(className).getCoverageId() + .equals(currentCoverage.toString(16)); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/FileWriterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/FileWriterFactory.java index a978b0b71..87e3deb29 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/FileWriterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/FileWriterFactory.java @@ -1,43 +1,43 @@ -package org.pitest.mutationtest.incremental; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; - -import org.pitest.util.Unchecked; - -public class FileWriterFactory implements WriterFactory { - - private final File file; - private PrintWriter writer; - - public FileWriterFactory(final File file) { - this.file = file; - } - - @Override - public PrintWriter create() { - this.file.getParentFile().mkdirs(); - try { - if (this.writer == null) { - this.writer = new PrintWriter(new OutputStreamWriter( - new FileOutputStream(this.file), "UTF-8")); - } - - return this.writer; - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - - @Override - public void close() { - if (this.writer != null) { - this.writer.close(); - } - - } - -} +package org.pitest.mutationtest.incremental; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; + +import org.pitest.util.Unchecked; + +public class FileWriterFactory implements WriterFactory { + + private final File file; + private PrintWriter writer; + + public FileWriterFactory(final File file) { + this.file = file; + } + + @Override + public PrintWriter create() { + this.file.getParentFile().mkdirs(); + try { + if (this.writer == null) { + this.writer = new PrintWriter(new OutputStreamWriter( + new FileOutputStream(this.file), "UTF-8")); + } + + return this.writer; + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + + @Override + public void close() { + if (this.writer != null) { + this.writer.close(); + } + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/HistoryListener.java b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/HistoryListener.java index c14790658..b4989c648 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/HistoryListener.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/HistoryListener.java @@ -1,34 +1,34 @@ -package org.pitest.mutationtest.incremental; - -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationResultListener; - -public class HistoryListener implements MutationResultListener { - - private final HistoryStore historyStore; - - public HistoryListener(final HistoryStore historyStore) { - this.historyStore = historyStore; - } - - @Override - public void runStart() { - - } - - @Override - public void handleMutationResult(final ClassMutationResults metaData) { - for (final MutationResult each : metaData.getMutations()) { - this.historyStore.recordResult(each); - } - - } - - @Override - public void runEnd() { - - } - -} +package org.pitest.mutationtest.incremental; + +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationResultListener; + +public class HistoryListener implements MutationResultListener { + + private final HistoryStore historyStore; + + public HistoryListener(final HistoryStore historyStore) { + this.historyStore = historyStore; + } + + @Override + public void runStart() { + + } + + @Override + public void handleMutationResult(final ClassMutationResults metaData) { + for (final MutationResult each : metaData.getMutations()) { + this.historyStore.recordResult(each); + } + + } + + @Override + public void runEnd() { + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/IncrementalAnalyser.java b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/IncrementalAnalyser.java index 58590e60e..85fa47f31 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/IncrementalAnalyser.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/IncrementalAnalyser.java @@ -1,151 +1,151 @@ -package org.pitest.mutationtest.incremental; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.logging.Logger; -import java.util.stream.Collectors; - -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.coverage.TestInfo; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationAnalyser; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.util.Log; - -public class IncrementalAnalyser implements MutationAnalyser { - - private static final Logger LOG = Log.getLogger(); - - private final CodeHistory history; - private final CoverageDatabase coverage; - private final Map preAnalysed = createStatusMap(); - - public IncrementalAnalyser(final CodeHistory history, - final CoverageDatabase coverage) { - this.history = history; - this.coverage = coverage; - } - - private static Map createStatusMap() { - final EnumMap map = new EnumMap<>(DetectionStatus.class); - for (final DetectionStatus each : DetectionStatus.values()) { - map.put(each, 0L); - } - return map; - } - - @Override - public Collection analyse( - final Collection mutation) { - - final List mrs = new ArrayList<>( - mutation.size()); - for (final MutationDetails each : mutation) { - final Optional maybeResult = this.history - .getPreviousResult(each.getId()); - if (!maybeResult.isPresent()) { - mrs.add(analyseFromScratch(each)); - } else { - mrs.add(analyseFromHistory(each, maybeResult.get())); - } - } - - logTotals(); - - return mrs; - - } - - private void logTotals() { - for (final Entry each : this.preAnalysed.entrySet()) { - if (each.getValue() != 0) { - LOG.fine("Incremental analysis set " + each.getValue() - + " mutations to a status of " + each.getKey()); - } - } - - } - - private MutationResult analyseFromHistory(final MutationDetails each, - final MutationStatusTestPair mutationStatusTestPair) { - - final ClassName clazz = each.getClassName(); - - if (this.history.hasClassChanged(clazz)) { - return analyseFromScratch(each); - } - - if (mutationStatusTestPair.getStatus() == DetectionStatus.TIMED_OUT) { - return makeResult(each, DetectionStatus.TIMED_OUT); - } - - if ((mutationStatusTestPair.getStatus() == DetectionStatus.KILLED) - && killingTestHasNotChanged(each, mutationStatusTestPair)) { - return makeResult(each, DetectionStatus.KILLED, mutationStatusTestPair - .getKillingTest().get()); - } - - if ((mutationStatusTestPair.getStatus() == DetectionStatus.SURVIVED) - && !this.history.hasCoverageChanged(clazz, - this.coverage.getCoverageIdForClass(clazz))) { - return makeResult(each, DetectionStatus.SURVIVED); - } - - return analyseFromScratch(each); - } - - private boolean killingTestHasNotChanged(final MutationDetails each, - final MutationStatusTestPair mutationStatusTestPair) { - final Collection allTests = this.coverage.getTestsForClass(each - .getClassName()); - - final List testClasses = allTests.stream() - .filter(testIsCalled(mutationStatusTestPair.getKillingTest().get())) - .map(TestInfo.toDefiningClassName()) - .collect(Collectors.toList()); - - if (testClasses.isEmpty()) { - return false; - } - - return !this.history.hasClassChanged(testClasses.get(0)); - - } - - private static Predicate testIsCalled(final String testName) { - return a -> a.getName().equals(testName); - } - - private MutationResult analyseFromScratch(final MutationDetails mutation) { - return makeResult(mutation, DetectionStatus.NOT_STARTED); - } - - private MutationResult makeResult(final MutationDetails each, - final DetectionStatus status) { - return makeResult(each, status, null); - } - - private MutationResult makeResult(final MutationDetails each, - final DetectionStatus status, final String killingTest) { - updatePreanalysedTotal(status); - return new MutationResult(each, new MutationStatusTestPair(0, status, - killingTest)); - } - - private void updatePreanalysedTotal(final DetectionStatus status) { - if (status != DetectionStatus.NOT_STARTED) { - final long count = this.preAnalysed.get(status); - this.preAnalysed.put(status, count + 1); - } - } - -} +package org.pitest.mutationtest.incremental; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.coverage.TestInfo; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationAnalyser; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.util.Log; + +public class IncrementalAnalyser implements MutationAnalyser { + + private static final Logger LOG = Log.getLogger(); + + private final CodeHistory history; + private final CoverageDatabase coverage; + private final Map preAnalysed = createStatusMap(); + + public IncrementalAnalyser(final CodeHistory history, + final CoverageDatabase coverage) { + this.history = history; + this.coverage = coverage; + } + + private static Map createStatusMap() { + final EnumMap map = new EnumMap<>(DetectionStatus.class); + for (final DetectionStatus each : DetectionStatus.values()) { + map.put(each, 0L); + } + return map; + } + + @Override + public Collection analyse( + final Collection mutation) { + + final List mrs = new ArrayList<>( + mutation.size()); + for (final MutationDetails each : mutation) { + final Optional maybeResult = this.history + .getPreviousResult(each.getId()); + if (!maybeResult.isPresent()) { + mrs.add(analyseFromScratch(each)); + } else { + mrs.add(analyseFromHistory(each, maybeResult.get())); + } + } + + logTotals(); + + return mrs; + + } + + private void logTotals() { + for (final Entry each : this.preAnalysed.entrySet()) { + if (each.getValue() != 0) { + LOG.fine("Incremental analysis set " + each.getValue() + + " mutations to a status of " + each.getKey()); + } + } + + } + + private MutationResult analyseFromHistory(final MutationDetails each, + final MutationStatusTestPair mutationStatusTestPair) { + + final ClassName clazz = each.getClassName(); + + if (this.history.hasClassChanged(clazz)) { + return analyseFromScratch(each); + } + + if (mutationStatusTestPair.getStatus() == DetectionStatus.TIMED_OUT) { + return makeResult(each, DetectionStatus.TIMED_OUT); + } + + if ((mutationStatusTestPair.getStatus() == DetectionStatus.KILLED) + && killingTestHasNotChanged(each, mutationStatusTestPair)) { + return makeResult(each, DetectionStatus.KILLED, mutationStatusTestPair + .getKillingTest().get()); + } + + if ((mutationStatusTestPair.getStatus() == DetectionStatus.SURVIVED) + && !this.history.hasCoverageChanged(clazz, + this.coverage.getCoverageIdForClass(clazz))) { + return makeResult(each, DetectionStatus.SURVIVED); + } + + return analyseFromScratch(each); + } + + private boolean killingTestHasNotChanged(final MutationDetails each, + final MutationStatusTestPair mutationStatusTestPair) { + final Collection allTests = this.coverage.getTestsForClass(each + .getClassName()); + + final List testClasses = allTests.stream() + .filter(testIsCalled(mutationStatusTestPair.getKillingTest().get())) + .map(TestInfo.toDefiningClassName()) + .collect(Collectors.toList()); + + if (testClasses.isEmpty()) { + return false; + } + + return !this.history.hasClassChanged(testClasses.get(0)); + + } + + private static Predicate testIsCalled(final String testName) { + return a -> a.getName().equals(testName); + } + + private MutationResult analyseFromScratch(final MutationDetails mutation) { + return makeResult(mutation, DetectionStatus.NOT_STARTED); + } + + private MutationResult makeResult(final MutationDetails each, + final DetectionStatus status) { + return makeResult(each, status, null); + } + + private MutationResult makeResult(final MutationDetails each, + final DetectionStatus status, final String killingTest) { + updatePreanalysedTotal(status); + return new MutationResult(each, new MutationStatusTestPair(0, status, + killingTest)); + } + + private void updatePreanalysedTotal(final DetectionStatus status) { + if (status != DetectionStatus.NOT_STARTED) { + final long count = this.preAnalysed.get(status); + this.preAnalysed.put(status, count + 1); + } + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/NullWriterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/NullWriterFactory.java index 77a927489..a5c38d039 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/NullWriterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/NullWriterFactory.java @@ -1,35 +1,35 @@ -package org.pitest.mutationtest.incremental; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; - -public class NullWriterFactory implements WriterFactory { - - private final PrintWriter pw; - - public NullWriterFactory() { - this.pw = new PrintWriter(new OutputStreamWriter(nullOutputStream())); - } - - private OutputStream nullOutputStream() { - return new OutputStream() { - @Override - public void write(final int b) throws IOException { - - } - }; - } - - @Override - public PrintWriter create() { - return this.pw; - } - - @Override - public void close() { - this.pw.close(); - } - -} +package org.pitest.mutationtest.incremental; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; + +public class NullWriterFactory implements WriterFactory { + + private final PrintWriter pw; + + public NullWriterFactory() { + this.pw = new PrintWriter(new OutputStreamWriter(nullOutputStream())); + } + + private OutputStream nullOutputStream() { + return new OutputStream() { + @Override + public void write(final int b) throws IOException { + + } + }; + } + + @Override + public PrintWriter create() { + return this.pw; + } + + @Override + public void close() { + this.pw.close(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/ObjectOutputStreamHistoryStore.java b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/ObjectOutputStreamHistoryStore.java index 5d05752c7..4e757736e 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/ObjectOutputStreamHistoryStore.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/ObjectOutputStreamHistoryStore.java @@ -1,159 +1,159 @@ -package org.pitest.mutationtest.incremental; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.Serializable; -import java.util.Base64; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Logger; - -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.HierarchicalClassId; -import org.pitest.coverage.CoverageDatabase; -import java.util.Optional; -import org.pitest.mutationtest.ClassHistory; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.util.Log; -import org.pitest.util.Unchecked; - -public class ObjectOutputStreamHistoryStore implements HistoryStore { - - private static final Logger LOG = Log - .getLogger(); - private final WriterFactory outputFactory; - private final BufferedReader input; - private final Map previousResults = new HashMap<>(); - private final Map previousClassPath = new HashMap<>(); - - public ObjectOutputStreamHistoryStore(final WriterFactory output, - final Optional input) { - this.outputFactory = output; - this.input = createReader(input); - } - - private BufferedReader createReader(Optional input) { - if (input.isPresent()) { - return new BufferedReader(input.get()); - } - return null; - } - - @Override - public void recordClassPath(final Collection ids, - final CoverageDatabase coverageInfo) { - final PrintWriter output = this.outputFactory.create(); - output.println(ids.size()); - for (final HierarchicalClassId each : ids) { - final ClassHistory coverage = new ClassHistory(each, - coverageInfo.getCoverageIdForClass(each.getName()).toString(16)); - output.println(serialize(coverage)); - } - output.flush(); - } - - @Override - public void recordResult(final MutationResult result) { - final PrintWriter output = this.outputFactory.create(); - output.println(serialize(new ObjectOutputStreamHistoryStore.IdResult( - result.getDetails().getId(), result.getStatusTestPair()))); - output.flush(); - } - - @Override - public Map getHistoricResults() { - return this.previousResults; - } - - @Override - public Map getHistoricClassPath() { - return this.previousClassPath; - } - - @Override - public void initialize() { - if (this.input != null) { - restoreClassPath(); - restoreResults(); - try { - this.input.close(); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - } - - private void restoreResults() { - String line; - try { - line = this.input.readLine(); - while (line != null) { - final IdResult result = deserialize(line, IdResult.class); - this.previousResults.put(result.id, result.status); - line = this.input.readLine(); - } - } catch (final IOException e) { - LOG.warning("Could not read previous results"); - } - } - - private void restoreClassPath() { - try { - final long classPathSize = Long.valueOf(this.input.readLine()); - for (int i = 0; i != classPathSize; i++) { - final ClassHistory coverage = deserialize(this.input.readLine(), - ClassHistory.class); - this.previousClassPath.put(coverage.getName(), coverage); - } - } catch (final IOException e) { - LOG.warning("Could not read previous classpath"); - } - } - - private T deserialize(String string, Class clazz) throws IOException { - try { - final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - Base64.getDecoder().decode(string)); - final ObjectInputStream objectInputStream = new ObjectInputStream( - byteArrayInputStream); - return clazz.cast(objectInputStream.readObject()); - } catch (final ClassNotFoundException e) { - throw Unchecked.translateCheckedException(e); - } - } - - private String serialize(T t) { - try { - final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - final ObjectOutputStream objectOutputStream = new ObjectOutputStream( - byteArrayOutputStream); - objectOutputStream.writeObject(t); - return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - - private static class IdResult implements Serializable { - private static final long serialVersionUID = 1L; - final MutationIdentifier id; - final MutationStatusTestPair status; - - IdResult(final MutationIdentifier id, final MutationStatusTestPair status) { - this.id = id; - this.status = status; - } - - } - +package org.pitest.mutationtest.incremental; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.Serializable; +import java.util.Base64; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.HierarchicalClassId; +import org.pitest.coverage.CoverageDatabase; +import java.util.Optional; +import org.pitest.mutationtest.ClassHistory; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.util.Log; +import org.pitest.util.Unchecked; + +public class ObjectOutputStreamHistoryStore implements HistoryStore { + + private static final Logger LOG = Log + .getLogger(); + private final WriterFactory outputFactory; + private final BufferedReader input; + private final Map previousResults = new HashMap<>(); + private final Map previousClassPath = new HashMap<>(); + + public ObjectOutputStreamHistoryStore(final WriterFactory output, + final Optional input) { + this.outputFactory = output; + this.input = createReader(input); + } + + private BufferedReader createReader(Optional input) { + if (input.isPresent()) { + return new BufferedReader(input.get()); + } + return null; + } + + @Override + public void recordClassPath(final Collection ids, + final CoverageDatabase coverageInfo) { + final PrintWriter output = this.outputFactory.create(); + output.println(ids.size()); + for (final HierarchicalClassId each : ids) { + final ClassHistory coverage = new ClassHistory(each, + coverageInfo.getCoverageIdForClass(each.getName()).toString(16)); + output.println(serialize(coverage)); + } + output.flush(); + } + + @Override + public void recordResult(final MutationResult result) { + final PrintWriter output = this.outputFactory.create(); + output.println(serialize(new ObjectOutputStreamHistoryStore.IdResult( + result.getDetails().getId(), result.getStatusTestPair()))); + output.flush(); + } + + @Override + public Map getHistoricResults() { + return this.previousResults; + } + + @Override + public Map getHistoricClassPath() { + return this.previousClassPath; + } + + @Override + public void initialize() { + if (this.input != null) { + restoreClassPath(); + restoreResults(); + try { + this.input.close(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + } + + private void restoreResults() { + String line; + try { + line = this.input.readLine(); + while (line != null) { + final IdResult result = deserialize(line, IdResult.class); + this.previousResults.put(result.id, result.status); + line = this.input.readLine(); + } + } catch (final IOException e) { + LOG.warning("Could not read previous results"); + } + } + + private void restoreClassPath() { + try { + final long classPathSize = Long.valueOf(this.input.readLine()); + for (int i = 0; i != classPathSize; i++) { + final ClassHistory coverage = deserialize(this.input.readLine(), + ClassHistory.class); + this.previousClassPath.put(coverage.getName(), coverage); + } + } catch (final IOException e) { + LOG.warning("Could not read previous classpath"); + } + } + + private T deserialize(String string, Class clazz) throws IOException { + try { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( + Base64.getDecoder().decode(string)); + final ObjectInputStream objectInputStream = new ObjectInputStream( + byteArrayInputStream); + return clazz.cast(objectInputStream.readObject()); + } catch (final ClassNotFoundException e) { + throw Unchecked.translateCheckedException(e); + } + } + + private String serialize(T t) { + try { + final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + final ObjectOutputStream objectOutputStream = new ObjectOutputStream( + byteArrayOutputStream); + objectOutputStream.writeObject(t); + return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + + private static class IdResult implements Serializable { + private static final long serialVersionUID = 1L; + final MutationIdentifier id; + final MutationStatusTestPair status; + + IdResult(final MutationIdentifier id, final MutationStatusTestPair status) { + this.id = id; + this.status = status; + } + + } + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/WriterFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/WriterFactory.java index e04d0a76c..4f60d3793 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/WriterFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/incremental/WriterFactory.java @@ -1,11 +1,11 @@ -package org.pitest.mutationtest.incremental; - -import java.io.PrintWriter; - -public interface WriterFactory { - - PrintWriter create(); - - void close(); - -} +package org.pitest.mutationtest.incremental; + +import java.io.PrintWriter; + +public interface WriterFactory { + + PrintWriter create(); + + void close(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/report/csv/CSVReportFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/report/csv/CSVReportFactory.java index 05e6c42e7..1a5fd7ef0 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/report/csv/CSVReportFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/report/csv/CSVReportFactory.java @@ -1,41 +1,41 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.csv; - -import java.util.Properties; - -import org.pitest.mutationtest.ListenerArguments; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.MutationResultListenerFactory; - -public class CSVReportFactory implements MutationResultListenerFactory { - - @Override - public MutationResultListener getListener(Properties props, - final ListenerArguments args) { - return new CSVReportListener(args.getOutputStrategy()); - } - - @Override - public String name() { - return "CSV"; - } - - @Override - public String description() { - return "Default csv report plugin"; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.csv; + +import java.util.Properties; + +import org.pitest.mutationtest.ListenerArguments; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.MutationResultListenerFactory; + +public class CSVReportFactory implements MutationResultListenerFactory { + + @Override + public MutationResultListener getListener(Properties props, + final ListenerArguments args) { + return new CSVReportListener(args.getOutputStrategy()); + } + + @Override + public String name() { + return "CSV"; + } + + @Override + public String description() { + return "Default csv report plugin"; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/report/csv/CSVReportListener.java b/pitest-entry/src/main/java/org/pitest/mutationtest/report/csv/CSVReportListener.java index 40f72731c..2ee0cb049 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/report/csv/CSVReportListener.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/report/csv/CSVReportListener.java @@ -1,91 +1,91 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.csv; - -import java.io.IOException; -import java.io.Writer; - -import java.util.Optional; -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.Unchecked; - -public class CSVReportListener implements MutationResultListener { - - private final Writer out; - - public CSVReportListener(final ResultOutputStrategy outputStrategy) { - this(outputStrategy.createWriterForFile("mutations.csv")); - } - - public CSVReportListener(final Writer out) { - this.out = out; - } - - private String createKillingTestDesc(final Optional killingTest) { - if (killingTest.isPresent()) { - return killingTest.get(); - } else { - return "none"; - } - } - - private String makeCsv(final Object... os) { - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i != os.length; i++) { - sb.append(os[i].toString()); - if (i != (os.length - 1)) { - sb.append(","); - } - } - return sb.toString(); - } - - @Override - public void runStart() { - - } - - @Override - public void runEnd() { - try { - this.out.close(); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - - @Override - public void handleMutationResult(final ClassMutationResults metaData) { - try { - - for (final MutationResult mutation : metaData.getMutations()) { - this.out.write(makeCsv(mutation.getDetails().getFilename(), mutation - .getDetails().getClassName().asJavaName(), mutation.getDetails() - .getMutator(), mutation.getDetails().getMethod(), mutation - .getDetails().getLineNumber(), mutation.getStatus(), - createKillingTestDesc(mutation.getKillingTest())) - + System.getProperty("line.separator")); - } - - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex); - } - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.csv; + +import java.io.IOException; +import java.io.Writer; + +import java.util.Optional; +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.Unchecked; + +public class CSVReportListener implements MutationResultListener { + + private final Writer out; + + public CSVReportListener(final ResultOutputStrategy outputStrategy) { + this(outputStrategy.createWriterForFile("mutations.csv")); + } + + public CSVReportListener(final Writer out) { + this.out = out; + } + + private String createKillingTestDesc(final Optional killingTest) { + if (killingTest.isPresent()) { + return killingTest.get(); + } else { + return "none"; + } + } + + private String makeCsv(final Object... os) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i != os.length; i++) { + sb.append(os[i].toString()); + if (i != (os.length - 1)) { + sb.append(","); + } + } + return sb.toString(); + } + + @Override + public void runStart() { + + } + + @Override + public void runEnd() { + try { + this.out.close(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + + @Override + public void handleMutationResult(final ClassMutationResults metaData) { + try { + + for (final MutationResult mutation : metaData.getMutations()) { + this.out.write(makeCsv(mutation.getDetails().getFilename(), mutation + .getDetails().getClassName().asJavaName(), mutation.getDetails() + .getMutator(), mutation.getDetails().getMethod(), mutation + .getDetails().getLineNumber(), mutation.getStatus(), + createKillingTestDesc(mutation.getKillingTest())) + + System.getProperty("line.separator")); + } + + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex); + } + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/report/xml/XMLReportFactory.java b/pitest-entry/src/main/java/org/pitest/mutationtest/report/xml/XMLReportFactory.java index cf2113d2b..9e0caeeab 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/report/xml/XMLReportFactory.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/report/xml/XMLReportFactory.java @@ -1,41 +1,41 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.xml; - -import java.util.Properties; - -import org.pitest.mutationtest.ListenerArguments; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.MutationResultListenerFactory; - -public class XMLReportFactory implements MutationResultListenerFactory { - - @Override - public MutationResultListener getListener(Properties props, - final ListenerArguments args) { - return new XMLReportListener(args.getOutputStrategy()); - } - - @Override - public String name() { - return "XML"; - } - - @Override - public String description() { - return "Default xml report plugin"; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.xml; + +import java.util.Properties; + +import org.pitest.mutationtest.ListenerArguments; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.MutationResultListenerFactory; + +public class XMLReportFactory implements MutationResultListenerFactory { + + @Override + public MutationResultListener getListener(Properties props, + final ListenerArguments args) { + return new XMLReportListener(args.getOutputStrategy()); + } + + @Override + public String name() { + return "XML"; + } + + @Override + public String description() { + return "Default xml report plugin"; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/report/xml/XMLReportListener.java b/pitest-entry/src/main/java/org/pitest/mutationtest/report/xml/XMLReportListener.java index bd1a03c81..375912ca4 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/report/xml/XMLReportListener.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/report/xml/XMLReportListener.java @@ -1,149 +1,149 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.xml; - -import static org.pitest.mutationtest.report.xml.Tag.block; -import static org.pitest.mutationtest.report.xml.Tag.description; -import static org.pitest.mutationtest.report.xml.Tag.index; -import static org.pitest.mutationtest.report.xml.Tag.killingTest; -import static org.pitest.mutationtest.report.xml.Tag.lineNumber; -import static org.pitest.mutationtest.report.xml.Tag.methodDescription; -import static org.pitest.mutationtest.report.xml.Tag.mutatedClass; -import static org.pitest.mutationtest.report.xml.Tag.mutatedMethod; -import static org.pitest.mutationtest.report.xml.Tag.mutation; -import static org.pitest.mutationtest.report.xml.Tag.mutator; -import static org.pitest.mutationtest.report.xml.Tag.sourceFile; - -import java.io.IOException; -import java.io.Writer; - -import java.util.Optional; -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.StringUtil; -import org.pitest.util.Unchecked; - -enum Tag { - mutation, sourceFile, mutatedClass, mutatedMethod, methodDescription, lineNumber, mutator, index, killingTest, description, block; -} - -public class XMLReportListener implements MutationResultListener { - - private final Writer out; - - public XMLReportListener(final ResultOutputStrategy outputStrategy) { - this(outputStrategy.createWriterForFile("mutations.xml")); - } - - public XMLReportListener(final Writer out) { - this.out = out; - } - - private void writeResult(final ClassMutationResults metaData) { - for (final MutationResult mutation : metaData.getMutations()) { - writeMutationResultXML(mutation); - } - } - - private void writeMutationResultXML(final MutationResult result) { - write(makeNode(makeMutationNode(result), makeMutationAttributes(result), - mutation) + "\n"); - } - - private String makeMutationAttributes(final MutationResult result) { - return "detected='" + result.getStatus().isDetected() + "' status='" - + result.getStatus() + "' numberOfTestsRun='" - + result.getNumberOfTestsRun() + "'"; - } - - private String makeMutationNode(final MutationResult mutation) { - final MutationDetails details = mutation.getDetails(); - return makeNode(clean(details.getFilename()), sourceFile) - + makeNode(clean(details.getClassName().asJavaName()), mutatedClass) - + makeNode(clean(details.getMethod().name()), mutatedMethod) - + makeNode(clean(details.getId().getLocation().getMethodDesc()), - methodDescription) - + makeNode("" + details.getLineNumber(), lineNumber) - + makeNode(clean(details.getMutator()), mutator) - + makeNode("" + details.getFirstIndex(), index) - + makeNode("" + details.getBlock(), block) - + makeNode(createKillingTestDesc(mutation.getKillingTest()), - killingTest) - + makeNode(clean(details.getDescription()), description); - } - - private String clean(final String value) { - return StringUtil.escapeBasicHtmlChars(value); - } - - private String makeNode(final String value, final String attributes, - final Tag tag) { - if (value != null) { - return "<" + tag + " " + attributes + ">" + value + ""; - } else { - return "<" + tag + attributes + "/>"; - } - - } - - private String makeNode(final String value, final Tag tag) { - if (value != null) { - return "<" + tag + ">" + value + ""; - } else { - return "<" + tag + "/>"; - } - } - - private String createKillingTestDesc(final Optional killingTest) { - if (killingTest.isPresent()) { - return clean(killingTest.get()); - } else { - return null; - } - } - - private void write(final String value) { - try { - this.out.write(value); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - - @Override - public void runStart() { - write("\n"); - write("\n"); - } - - @Override - public void handleMutationResult(final ClassMutationResults metaData) { - writeResult(metaData); - } - - @Override - public void runEnd() { - try { - write("\n"); - this.out.close(); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.xml; + +import static org.pitest.mutationtest.report.xml.Tag.block; +import static org.pitest.mutationtest.report.xml.Tag.description; +import static org.pitest.mutationtest.report.xml.Tag.index; +import static org.pitest.mutationtest.report.xml.Tag.killingTest; +import static org.pitest.mutationtest.report.xml.Tag.lineNumber; +import static org.pitest.mutationtest.report.xml.Tag.methodDescription; +import static org.pitest.mutationtest.report.xml.Tag.mutatedClass; +import static org.pitest.mutationtest.report.xml.Tag.mutatedMethod; +import static org.pitest.mutationtest.report.xml.Tag.mutation; +import static org.pitest.mutationtest.report.xml.Tag.mutator; +import static org.pitest.mutationtest.report.xml.Tag.sourceFile; + +import java.io.IOException; +import java.io.Writer; + +import java.util.Optional; +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.StringUtil; +import org.pitest.util.Unchecked; + +enum Tag { + mutation, sourceFile, mutatedClass, mutatedMethod, methodDescription, lineNumber, mutator, index, killingTest, description, block; +} + +public class XMLReportListener implements MutationResultListener { + + private final Writer out; + + public XMLReportListener(final ResultOutputStrategy outputStrategy) { + this(outputStrategy.createWriterForFile("mutations.xml")); + } + + public XMLReportListener(final Writer out) { + this.out = out; + } + + private void writeResult(final ClassMutationResults metaData) { + for (final MutationResult mutation : metaData.getMutations()) { + writeMutationResultXML(mutation); + } + } + + private void writeMutationResultXML(final MutationResult result) { + write(makeNode(makeMutationNode(result), makeMutationAttributes(result), + mutation) + "\n"); + } + + private String makeMutationAttributes(final MutationResult result) { + return "detected='" + result.getStatus().isDetected() + "' status='" + + result.getStatus() + "' numberOfTestsRun='" + + result.getNumberOfTestsRun() + "'"; + } + + private String makeMutationNode(final MutationResult mutation) { + final MutationDetails details = mutation.getDetails(); + return makeNode(clean(details.getFilename()), sourceFile) + + makeNode(clean(details.getClassName().asJavaName()), mutatedClass) + + makeNode(clean(details.getMethod().name()), mutatedMethod) + + makeNode(clean(details.getId().getLocation().getMethodDesc()), + methodDescription) + + makeNode("" + details.getLineNumber(), lineNumber) + + makeNode(clean(details.getMutator()), mutator) + + makeNode("" + details.getFirstIndex(), index) + + makeNode("" + details.getBlock(), block) + + makeNode(createKillingTestDesc(mutation.getKillingTest()), + killingTest) + + makeNode(clean(details.getDescription()), description); + } + + private String clean(final String value) { + return StringUtil.escapeBasicHtmlChars(value); + } + + private String makeNode(final String value, final String attributes, + final Tag tag) { + if (value != null) { + return "<" + tag + " " + attributes + ">" + value + ""; + } else { + return "<" + tag + attributes + "/>"; + } + + } + + private String makeNode(final String value, final Tag tag) { + if (value != null) { + return "<" + tag + ">" + value + ""; + } else { + return "<" + tag + "/>"; + } + } + + private String createKillingTestDesc(final Optional killingTest) { + if (killingTest.isPresent()) { + return clean(killingTest.get()); + } else { + return null; + } + } + + private void write(final String value) { + try { + this.out.write(value); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + + @Override + public void runStart() { + write("\n"); + write("\n"); + } + + @Override + public void handleMutationResult(final ClassMutationResults metaData) { + writeResult(metaData); + } + + @Override + public void runEnd() { + try { + write("\n"); + this.out.close(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatistics.java b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatistics.java index e2cb02bd5..df7d22252 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatistics.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatistics.java @@ -1,85 +1,85 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.statistics; - -import java.io.PrintStream; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.Locale; - -public final class MutationStatistics { - private final Iterable scores; - private final long totalMutations; - private final long numberOfTestsRun; - private final long totalDetected; - - public MutationStatistics(Iterable scores, long totalMutations, - long totalDetected, long numberOfTestsRun) { - this.scores = scores; - this.totalMutations = totalMutations; - this.totalDetected = totalDetected; - this.numberOfTestsRun = numberOfTestsRun; - } - - public Iterable getScores() { - return this.scores; - } - - public long getTotalMutations() { - return this.totalMutations; - } - - public long getTotalDetectedMutations() { - return this.totalDetected; - } - - public long getTotalSurvivingMutations() { - return getTotalMutations() - getTotalDetectedMutations(); - } - - public long getPercentageDetected() { - if (getTotalMutations() == 0) { - return 100; - } - - if (getTotalDetectedMutations() == 0) { - return 0; - } - - return Math.round((100f / getTotalMutations()) - * getTotalDetectedMutations()); - } - - public void report(final PrintStream out) { - out.println(">> Generated " + this.getTotalMutations() - + " mutations Killed " + this.getTotalDetectedMutations() + " (" - + this.getPercentageDetected() + "%)"); - out.println(">> Ran " + this.numberOfTestsRun + " tests (" - + getTestsPerMutation() + " tests per mutation)"); - - } - - private String getTestsPerMutation() { - if (this.getTotalMutations() == 0) { - return "0"; - } - - final float testsPerMutation = this.numberOfTestsRun - / (float) this.getTotalMutations(); - return new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.ENGLISH)) - .format(testsPerMutation); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.statistics; + +import java.io.PrintStream; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; + +public final class MutationStatistics { + private final Iterable scores; + private final long totalMutations; + private final long numberOfTestsRun; + private final long totalDetected; + + public MutationStatistics(Iterable scores, long totalMutations, + long totalDetected, long numberOfTestsRun) { + this.scores = scores; + this.totalMutations = totalMutations; + this.totalDetected = totalDetected; + this.numberOfTestsRun = numberOfTestsRun; + } + + public Iterable getScores() { + return this.scores; + } + + public long getTotalMutations() { + return this.totalMutations; + } + + public long getTotalDetectedMutations() { + return this.totalDetected; + } + + public long getTotalSurvivingMutations() { + return getTotalMutations() - getTotalDetectedMutations(); + } + + public long getPercentageDetected() { + if (getTotalMutations() == 0) { + return 100; + } + + if (getTotalDetectedMutations() == 0) { + return 0; + } + + return Math.round((100f / getTotalMutations()) + * getTotalDetectedMutations()); + } + + public void report(final PrintStream out) { + out.println(">> Generated " + this.getTotalMutations() + + " mutations Killed " + this.getTotalDetectedMutations() + " (" + + this.getPercentageDetected() + "%)"); + out.println(">> Ran " + this.numberOfTestsRun + " tests (" + + getTestsPerMutation() + " tests per mutation)"); + + } + + private String getTestsPerMutation() { + if (this.getTotalMutations() == 0) { + return "0"; + } + + final float testsPerMutation = this.numberOfTestsRun + / (float) this.getTotalMutations(); + return new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.ENGLISH)) + .format(testsPerMutation); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsListener.java b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsListener.java index 515bc6c55..b66beb5c5 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsListener.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsListener.java @@ -1,48 +1,48 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.statistics; - -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationResultListener; - -public class MutationStatisticsListener implements MutationResultListener, -MutationStatisticsSource { - - private final MutationStatisticsPrecursor mutatorScores = new MutationStatisticsPrecursor(); - - @Override - public MutationStatistics getStatistics() { - return this.mutatorScores.toStatistics(); - } - - @Override - public void runStart() { - - } - - @Override - public void handleMutationResult(final ClassMutationResults metaData) { - processMetaData(metaData); - } - - @Override - public void runEnd() { - - } - - private void processMetaData(final ClassMutationResults value) { - this.mutatorScores.registerResults(value.getMutations()); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.statistics; + +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationResultListener; + +public class MutationStatisticsListener implements MutationResultListener, +MutationStatisticsSource { + + private final MutationStatisticsPrecursor mutatorScores = new MutationStatisticsPrecursor(); + + @Override + public MutationStatistics getStatistics() { + return this.mutatorScores.toStatistics(); + } + + @Override + public void runStart() { + + } + + @Override + public void handleMutationResult(final ClassMutationResults metaData) { + processMetaData(metaData); + } + + @Override + public void runEnd() { + + } + + private void processMetaData(final ClassMutationResults value) { + this.mutatorScores.registerResults(value.getMutations()); + } +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsPrecursor.java b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsPrecursor.java index c5f079832..b70a5f5f8 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsPrecursor.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsPrecursor.java @@ -1,60 +1,60 @@ -package org.pitest.mutationtest.statistics; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.function.BiFunction; -import java.util.function.Function; - -import org.pitest.functional.FCollection; -import org.pitest.functional.SideEffect1; -import org.pitest.mutationtest.MutationResult; - -class MutationStatisticsPrecursor { - private final Map mutatorTotalMap = new HashMap<>(); - private long numberOfTestsRun = 0; - - public void registerResults(final Collection results) { - FCollection.forEach(results, register()); - } - - private SideEffect1 register() { - return mr -> { - MutationStatisticsPrecursor.this.numberOfTestsRun = MutationStatisticsPrecursor.this.numberOfTestsRun - + mr.getNumberOfTestsRun(); - final String key = mr.getDetails().getId().getMutator(); - ScorePrecursor total = MutationStatisticsPrecursor.this.mutatorTotalMap - .get(key); - if (total == null) { - total = new ScorePrecursor(key); - MutationStatisticsPrecursor.this.mutatorTotalMap.put(key, total); - } - total.registerResult(mr.getStatus()); - }; - } - - public MutationStatistics toStatistics() { - final Iterable scores = getScores(); - final long totalMutations = FCollection.fold(addTotals(), 0L, scores); - final long totalDetected = FCollection - .fold(addDetectedTotals(), 0L, scores); - return new MutationStatistics(scores, totalMutations, totalDetected, - this.numberOfTestsRun); - } - - Iterable getScores() { - return FCollection.map(this.mutatorTotalMap.values(), toScore()); - } - - private static Function toScore() { - return a -> a.toScore(); - } - - private static BiFunction addTotals() { - return (a, b) -> a + b.getTotalMutations(); - } - - private static BiFunction addDetectedTotals() { - return (a, b) -> a + b.getTotalDetectedMutations(); - } +package org.pitest.mutationtest.statistics; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; + +import org.pitest.functional.FCollection; +import org.pitest.functional.SideEffect1; +import org.pitest.mutationtest.MutationResult; + +class MutationStatisticsPrecursor { + private final Map mutatorTotalMap = new HashMap<>(); + private long numberOfTestsRun = 0; + + public void registerResults(final Collection results) { + FCollection.forEach(results, register()); + } + + private SideEffect1 register() { + return mr -> { + MutationStatisticsPrecursor.this.numberOfTestsRun = MutationStatisticsPrecursor.this.numberOfTestsRun + + mr.getNumberOfTestsRun(); + final String key = mr.getDetails().getId().getMutator(); + ScorePrecursor total = MutationStatisticsPrecursor.this.mutatorTotalMap + .get(key); + if (total == null) { + total = new ScorePrecursor(key); + MutationStatisticsPrecursor.this.mutatorTotalMap.put(key, total); + } + total.registerResult(mr.getStatus()); + }; + } + + public MutationStatistics toStatistics() { + final Iterable scores = getScores(); + final long totalMutations = FCollection.fold(addTotals(), 0L, scores); + final long totalDetected = FCollection + .fold(addDetectedTotals(), 0L, scores); + return new MutationStatistics(scores, totalMutations, totalDetected, + this.numberOfTestsRun); + } + + Iterable getScores() { + return FCollection.map(this.mutatorTotalMap.values(), toScore()); + } + + private static Function toScore() { + return a -> a.toScore(); + } + + private static BiFunction addTotals() { + return (a, b) -> a + b.getTotalMutations(); + } + + private static BiFunction addDetectedTotals() { + return (a, b) -> a + b.getTotalDetectedMutations(); + } } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsSource.java b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsSource.java index 19a7b71d0..6541342b4 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsSource.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/MutationStatisticsSource.java @@ -1,5 +1,5 @@ -package org.pitest.mutationtest.statistics; - -public interface MutationStatisticsSource { - MutationStatistics getStatistics(); -} +package org.pitest.mutationtest.statistics; + +public interface MutationStatisticsSource { + MutationStatistics getStatistics(); +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/Score.java b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/Score.java index e00aab564..71b37a0c1 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/Score.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/Score.java @@ -1,76 +1,76 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.statistics; - -import java.io.PrintStream; - -public final class Score { - - private final String mutatorName; - private final Iterable counts; - private final long totalMutations; - private final long totalDetected; - - public Score(final String name, Iterable counts, - long totalMutations, long totalDetected) { - this.mutatorName = name; - this.counts = counts; - this.totalMutations = totalMutations; - this.totalDetected = totalDetected; - } - - public void report(final PrintStream out) { - out.println("> " + this.mutatorName); - out.println(">> Generated " + this.totalMutations + " Killed " - + this.totalDetected + " (" + this.getPercentageDetected() + "%)"); - int i = 0; - StringBuilder sb = new StringBuilder(); - for (final StatusCount each : this.counts) { - sb.append(each + " "); - i++; - if ((i % 4) == 0) { - out.println("> " + sb.toString()); - sb = new StringBuilder(); - } - } - out.println("> " + sb.toString()); - } - - public String getMutatorName() { - return this.mutatorName; - } - - public long getTotalMutations() { - return this.totalMutations; - } - - public long getTotalDetectedMutations() { - return this.totalDetected; - } - - public int getPercentageDetected() { - if (getTotalMutations() == 0) { - return 100; - } - - if (getTotalDetectedMutations() == 0) { - return 0; - } - - return Math.round((100f / getTotalMutations()) - * getTotalDetectedMutations()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.statistics; + +import java.io.PrintStream; + +public final class Score { + + private final String mutatorName; + private final Iterable counts; + private final long totalMutations; + private final long totalDetected; + + public Score(final String name, Iterable counts, + long totalMutations, long totalDetected) { + this.mutatorName = name; + this.counts = counts; + this.totalMutations = totalMutations; + this.totalDetected = totalDetected; + } + + public void report(final PrintStream out) { + out.println("> " + this.mutatorName); + out.println(">> Generated " + this.totalMutations + " Killed " + + this.totalDetected + " (" + this.getPercentageDetected() + "%)"); + int i = 0; + StringBuilder sb = new StringBuilder(); + for (final StatusCount each : this.counts) { + sb.append(each + " "); + i++; + if ((i % 4) == 0) { + out.println("> " + sb.toString()); + sb = new StringBuilder(); + } + } + out.println("> " + sb.toString()); + } + + public String getMutatorName() { + return this.mutatorName; + } + + public long getTotalMutations() { + return this.totalMutations; + } + + public long getTotalDetectedMutations() { + return this.totalDetected; + } + + public int getPercentageDetected() { + if (getTotalMutations() == 0) { + return 100; + } + + if (getTotalDetectedMutations() == 0) { + return 0; + } + + return Math.round((100f / getTotalMutations()) + * getTotalDetectedMutations()); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/ScorePrecursor.java b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/ScorePrecursor.java index 1ff96fcc9..f488ecb5d 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/ScorePrecursor.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/ScorePrecursor.java @@ -1,60 +1,60 @@ -package org.pitest.mutationtest.statistics; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.function.BiFunction; -import java.util.function.Predicate; - -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.DetectionStatus; - -class ScorePrecursor { - - private final String mutatorName; - private final Map counts; - - ScorePrecursor(final String name) { - this.mutatorName = name; - this.counts = createMap(); - } - - void registerResult(final DetectionStatus result) { - final StatusCount total = this.counts.get(result); - total.increment(); - } - - Iterable getCounts() { - return this.counts.values(); - } - - private long getTotalMutations() { - return FCollection.fold(addTotals(), 0L, this.counts.values()); - } - - private long getTotalDetectedMutations() { - return FCollection.fold(addTotals(), 0L, - FCollection.filter(this.counts.values(), isDetected())); - } - - private static Predicate isDetected() { - return a -> a.getStatus().isDetected(); - } - - private BiFunction addTotals() { - return (a, b) -> a + b.getCount(); - } - - private static Map createMap() { - final Map map = new LinkedHashMap<>(); - for (final DetectionStatus each : DetectionStatus.values()) { - map.put(each, new StatusCount(each, 0L)); - } - return map; - } - - Score toScore() { - return new Score(this.mutatorName, this.getCounts(), this.getTotalMutations(), - this.getTotalDetectedMutations()); - } -} - +package org.pitest.mutationtest.statistics; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Predicate; + +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.DetectionStatus; + +class ScorePrecursor { + + private final String mutatorName; + private final Map counts; + + ScorePrecursor(final String name) { + this.mutatorName = name; + this.counts = createMap(); + } + + void registerResult(final DetectionStatus result) { + final StatusCount total = this.counts.get(result); + total.increment(); + } + + Iterable getCounts() { + return this.counts.values(); + } + + private long getTotalMutations() { + return FCollection.fold(addTotals(), 0L, this.counts.values()); + } + + private long getTotalDetectedMutations() { + return FCollection.fold(addTotals(), 0L, + FCollection.filter(this.counts.values(), isDetected())); + } + + private static Predicate isDetected() { + return a -> a.getStatus().isDetected(); + } + + private BiFunction addTotals() { + return (a, b) -> a + b.getCount(); + } + + private static Map createMap() { + final Map map = new LinkedHashMap<>(); + for (final DetectionStatus each : DetectionStatus.values()) { + map.put(each, new StatusCount(each, 0L)); + } + return map; + } + + Score toScore() { + return new Score(this.mutatorName, this.getCounts(), this.getTotalMutations(), + this.getTotalDetectedMutations()); + } +} + diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/StatusCount.java b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/StatusCount.java index b7bad6380..2b540d924 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/StatusCount.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/statistics/StatusCount.java @@ -1,45 +1,45 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.statistics; - -import org.pitest.mutationtest.DetectionStatus; - -public class StatusCount { - - private final DetectionStatus status; - private long count; - - StatusCount(final DetectionStatus status, final long count) { - this.status = status; - this.count = count; - } - - void increment() { - this.count++; - } - - @Override - public String toString() { - return "" + this.status + " " + this.count; - } - - public long getCount() { - return this.count; - } - - public DetectionStatus getStatus() { - return this.status; - } +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.statistics; + +import org.pitest.mutationtest.DetectionStatus; + +public class StatusCount { + + private final DetectionStatus status; + private long count; + + StatusCount(final DetectionStatus status, final long count) { + this.status = status; + this.count = count; + } + + void increment() { + this.count++; + } + + @Override + public String toString() { + return "" + this.status + " " + this.count; + } + + public long getCount() { + return this.count; + } + + public DetectionStatus getStatus() { + return this.status; + } } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/AnalysisResult.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/AnalysisResult.java index 5a2c731db..41fa2fa3b 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/AnalysisResult.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/AnalysisResult.java @@ -1,32 +1,32 @@ -package org.pitest.mutationtest.tooling; - -import java.util.Optional; - -public final class AnalysisResult { - - private final Optional statistics; - private final Optional error; - - private AnalysisResult(final CombinedStatistics statistics, - final Exception error) { - this.statistics = Optional.ofNullable(statistics); - this.error = Optional.ofNullable(error); - } - - public static AnalysisResult success(final CombinedStatistics statistics) { - return new AnalysisResult(statistics, null); - } - - public static AnalysisResult fail(final Exception error) { - return new AnalysisResult(null, error); - } - - public Optional getStatistics() { - return this.statistics; - } - - public Optional getError() { - return this.error; - } - -} +package org.pitest.mutationtest.tooling; + +import java.util.Optional; + +public final class AnalysisResult { + + private final Optional statistics; + private final Optional error; + + private AnalysisResult(final CombinedStatistics statistics, + final Exception error) { + this.statistics = Optional.ofNullable(statistics); + this.error = Optional.ofNullable(error); + } + + public static AnalysisResult success(final CombinedStatistics statistics) { + return new AnalysisResult(statistics, null); + } + + public static AnalysisResult fail(final Exception error) { + return new AnalysisResult(null, error); + } + + public Optional getStatistics() { + return this.statistics; + } + + public Optional getError() { + return this.error; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/CombinedStatistics.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/CombinedStatistics.java index b3e23473b..6b47dc918 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/CombinedStatistics.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/CombinedStatistics.java @@ -1,25 +1,25 @@ -package org.pitest.mutationtest.tooling; - -import org.pitest.coverage.CoverageSummary; -import org.pitest.mutationtest.statistics.MutationStatistics; - -public class CombinedStatistics { - - private final MutationStatistics mutationStatistics; - private final CoverageSummary coverageSummary; - - public CombinedStatistics(final MutationStatistics mutationStatistics, - final CoverageSummary coverageSummary) { - this.mutationStatistics = mutationStatistics; - this.coverageSummary = coverageSummary; - } - - public MutationStatistics getMutationStatistics() { - return this.mutationStatistics; - } - - public CoverageSummary getCoverageSummary() { - return this.coverageSummary; - } - -} +package org.pitest.mutationtest.tooling; + +import org.pitest.coverage.CoverageSummary; +import org.pitest.mutationtest.statistics.MutationStatistics; + +public class CombinedStatistics { + + private final MutationStatistics mutationStatistics; + private final CoverageSummary coverageSummary; + + public CombinedStatistics(final MutationStatistics mutationStatistics, + final CoverageSummary coverageSummary) { + this.mutationStatistics = mutationStatistics; + this.coverageSummary = coverageSummary; + } + + public MutationStatistics getMutationStatistics() { + return this.mutationStatistics; + } + + public CoverageSummary getCoverageSummary() { + return this.coverageSummary; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/DirectorySourceLocator.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/DirectorySourceLocator.java index 7420c19b2..937e8705e 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/DirectorySourceLocator.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/DirectorySourceLocator.java @@ -1,84 +1,84 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.tooling; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.Reader; -import java.util.Collection; -import java.util.Optional; -import java.util.function.Function; -import java.util.stream.Stream; - -import org.pitest.functional.Streams; -import org.pitest.mutationtest.SourceLocator; - -public class DirectorySourceLocator implements SourceLocator { - - private final File root; - private final Function> fileToReader; - - private static class FileToReader implements Function> { - - @Override - public Optional apply(final File f) { - if (f.exists()) { - try { - return Optional. ofNullable(new FileReader(f)); - } catch (final FileNotFoundException e) { - return Optional.empty(); - } - } - return Optional.empty(); - } - - }; - - DirectorySourceLocator(final File root, - final Function> fileToReader) { - this.root = root; - this.fileToReader = fileToReader; - } - - public DirectorySourceLocator(final File root) { - this(root, new FileToReader()); - } - - @Override - public Optional locate(final Collection classes, - final String fileName) { - final Stream matches = classes.stream().flatMap(classNameToSourceFileReader(fileName)); - return matches.findFirst(); - } - - private Function> classNameToSourceFileReader( - final String fileName) { - return className -> { - if (className.contains(".")) { - final File f = new File(className.replace(".", File.separator)); - return locate(f.getParent() + File.separator + fileName); - } else { - return locate(fileName); - } - }; - } - - private Stream locate(final String fileName) { - final File f = new File(this.root + File.separator + fileName); - return Streams.fromOptional(this.fileToReader.apply(f)); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.tooling; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.Reader; +import java.util.Collection; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.pitest.functional.Streams; +import org.pitest.mutationtest.SourceLocator; + +public class DirectorySourceLocator implements SourceLocator { + + private final File root; + private final Function> fileToReader; + + private static class FileToReader implements Function> { + + @Override + public Optional apply(final File f) { + if (f.exists()) { + try { + return Optional. ofNullable(new FileReader(f)); + } catch (final FileNotFoundException e) { + return Optional.empty(); + } + } + return Optional.empty(); + } + + }; + + DirectorySourceLocator(final File root, + final Function> fileToReader) { + this.root = root; + this.fileToReader = fileToReader; + } + + public DirectorySourceLocator(final File root) { + this(root, new FileToReader()); + } + + @Override + public Optional locate(final Collection classes, + final String fileName) { + final Stream matches = classes.stream().flatMap(classNameToSourceFileReader(fileName)); + return matches.findFirst(); + } + + private Function> classNameToSourceFileReader( + final String fileName) { + return className -> { + if (className.contains(".")) { + final File f = new File(className.replace(".", File.separator)); + return locate(f.getParent() + File.separator + fileName); + } else { + return locate(fileName); + } + }; + } + + private Stream locate(final String fileName) { + final File f = new File(this.root + File.separator + fileName); + return Streams.fromOptional(this.fileToReader.apply(f)); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/EntryPoint.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/EntryPoint.java index d9d3349a9..0d523072e 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/EntryPoint.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/EntryPoint.java @@ -1,155 +1,155 @@ -package org.pitest.mutationtest.tooling; - -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.util.Map; - -import org.pitest.classpath.ClassPath; -import org.pitest.classpath.ClassPathByteArraySource; -import org.pitest.classpath.CodeSource; -import org.pitest.classpath.ProjectClassPaths; -import org.pitest.coverage.CoverageGenerator; -import org.pitest.coverage.execute.CoverageOptions; -import org.pitest.coverage.execute.DefaultCoverageGenerator; -import java.util.Optional; -import org.pitest.functional.SideEffect1; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.MutationResultListenerFactory; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.config.SettingsFactory; -import org.pitest.mutationtest.incremental.ObjectOutputStreamHistoryStore; -import org.pitest.mutationtest.incremental.WriterFactory; -import org.pitest.plugin.Feature; -import org.pitest.plugin.FeatureParameter; -import org.pitest.process.JavaAgent; -import org.pitest.process.LaunchOptions; -import org.pitest.util.Log; -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.Timings; - -public class EntryPoint { - - /** - * Convenient entry point for tools to run mutation analysis. - * - * The big grab bag of config stored in ReportOptions must be setup correctly - * first. - * - * @param baseDir - * directory from which analysis will be run - * @param data - * @param environmentVariables - * - */ - public AnalysisResult execute(File baseDir, ReportOptions data, - PluginServices plugins, Map environmentVariables) { - final SettingsFactory settings = new SettingsFactory(data, plugins); - return execute(baseDir, data, settings, environmentVariables); - } - - /** - * Entry point for tools with tool specific behaviour - * - * @param baseDir - * directory from which analysis will be run - * @param data - * big mess of configuration options - * @param settings - * factory for various strategies. Override default to provide tool - * specific behaviours - */ - public AnalysisResult execute(File baseDir, ReportOptions data, - SettingsFactory settings, Map environmentVariables) { - - if (data.isVerbose()) { - Log.getLogger().info("---------------------------------------------------------------------------"); - Log.getLogger().info("Enabled (+) and disabled (-) features."); - Log.getLogger().info("-----------------------------------------"); - settings.describeFeatures(asInfo("+"), asInfo("-")); - Log.getLogger().info("---------------------------------------------------------------------------"); - } - - selectTestPlugin(data); - - final ClassPath cp = data.getClassPath(); - - final Optional reader = data.createHistoryReader(); - final WriterFactory historyWriter = data.createHistoryWriter(); - - // workaround for apparent java 1.5 JVM bug . . . might not play nicely - // with distributed testing - final JavaAgent jac = new JarCreatingJarFinder( - new ClassPathByteArraySource(cp)); - - final KnownLocationJavaAgentFinder ja = new KnownLocationJavaAgentFinder( - jac.getJarLocation().get()); - - final ResultOutputStrategy reportOutput = settings.getOutputStrategy(); - - final MutationResultListenerFactory reportFactory = settings - .createListener(); - - final CoverageOptions coverageOptions = settings.createCoverageOptions(); - final LaunchOptions launchOptions = new LaunchOptions(ja, - settings.getJavaExecutable(), data.getJvmArgs(), environmentVariables); - final ProjectClassPaths cps = data.getMutationClassPaths(); - - final CodeSource code = new CodeSource(cps); - - final Timings timings = new Timings(); - final CoverageGenerator coverageDatabase = new DefaultCoverageGenerator( - baseDir, coverageOptions, launchOptions, code, - settings.createCoverageExporter(), timings, !data.isVerbose()); - - final HistoryStore history = new ObjectOutputStreamHistoryStore(historyWriter, reader); - - final MutationStrategies strategies = new MutationStrategies( - settings.createEngine(), history, coverageDatabase, reportFactory, - reportOutput); - - final MutationCoverage report = new MutationCoverage(strategies, baseDir, - code, data, settings, timings); - - try { - return AnalysisResult.success(report.runReport()); - } catch (final IOException e) { - return AnalysisResult.fail(e); - } finally { - jac.close(); - ja.close(); - historyWriter.close(); - } - - } - - private void selectTestPlugin(ReportOptions data) { - if ((data.getTestPlugin() == null) || data.getTestPlugin().equals("")) { - if (junit5PluginIsOnClasspath()) { - data.setTestPlugin("junit5"); - } else { - data.setTestPlugin("junit"); - } - } - } - - private boolean junit5PluginIsOnClasspath() { - try { - Class.forName("org.pitest.junit5.JUnit5TestPluginFactory"); - return true; - } catch (final ClassNotFoundException e) { - return false; - } - } - - private SideEffect1 asInfo(final String leader) { - return a -> { - Log.getLogger().info(String.format("%1$-16s",leader + a.name()) + a.description()); - for (final FeatureParameter each : a.params()) { - Log.getLogger().info(String.format("%1$-18s", " [" + each.name() + "]") + each.description()); - } - }; - } - -} +package org.pitest.mutationtest.tooling; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.util.Map; + +import org.pitest.classpath.ClassPath; +import org.pitest.classpath.ClassPathByteArraySource; +import org.pitest.classpath.CodeSource; +import org.pitest.classpath.ProjectClassPaths; +import org.pitest.coverage.CoverageGenerator; +import org.pitest.coverage.execute.CoverageOptions; +import org.pitest.coverage.execute.DefaultCoverageGenerator; +import java.util.Optional; +import org.pitest.functional.SideEffect1; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.MutationResultListenerFactory; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.config.SettingsFactory; +import org.pitest.mutationtest.incremental.ObjectOutputStreamHistoryStore; +import org.pitest.mutationtest.incremental.WriterFactory; +import org.pitest.plugin.Feature; +import org.pitest.plugin.FeatureParameter; +import org.pitest.process.JavaAgent; +import org.pitest.process.LaunchOptions; +import org.pitest.util.Log; +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.Timings; + +public class EntryPoint { + + /** + * Convenient entry point for tools to run mutation analysis. + * + * The big grab bag of config stored in ReportOptions must be setup correctly + * first. + * + * @param baseDir + * directory from which analysis will be run + * @param data + * @param environmentVariables + * + */ + public AnalysisResult execute(File baseDir, ReportOptions data, + PluginServices plugins, Map environmentVariables) { + final SettingsFactory settings = new SettingsFactory(data, plugins); + return execute(baseDir, data, settings, environmentVariables); + } + + /** + * Entry point for tools with tool specific behaviour + * + * @param baseDir + * directory from which analysis will be run + * @param data + * big mess of configuration options + * @param settings + * factory for various strategies. Override default to provide tool + * specific behaviours + */ + public AnalysisResult execute(File baseDir, ReportOptions data, + SettingsFactory settings, Map environmentVariables) { + + if (data.isVerbose()) { + Log.getLogger().info("---------------------------------------------------------------------------"); + Log.getLogger().info("Enabled (+) and disabled (-) features."); + Log.getLogger().info("-----------------------------------------"); + settings.describeFeatures(asInfo("+"), asInfo("-")); + Log.getLogger().info("---------------------------------------------------------------------------"); + } + + selectTestPlugin(data); + + final ClassPath cp = data.getClassPath(); + + final Optional reader = data.createHistoryReader(); + final WriterFactory historyWriter = data.createHistoryWriter(); + + // workaround for apparent java 1.5 JVM bug . . . might not play nicely + // with distributed testing + final JavaAgent jac = new JarCreatingJarFinder( + new ClassPathByteArraySource(cp)); + + final KnownLocationJavaAgentFinder ja = new KnownLocationJavaAgentFinder( + jac.getJarLocation().get()); + + final ResultOutputStrategy reportOutput = settings.getOutputStrategy(); + + final MutationResultListenerFactory reportFactory = settings + .createListener(); + + final CoverageOptions coverageOptions = settings.createCoverageOptions(); + final LaunchOptions launchOptions = new LaunchOptions(ja, + settings.getJavaExecutable(), data.getJvmArgs(), environmentVariables); + final ProjectClassPaths cps = data.getMutationClassPaths(); + + final CodeSource code = new CodeSource(cps); + + final Timings timings = new Timings(); + final CoverageGenerator coverageDatabase = new DefaultCoverageGenerator( + baseDir, coverageOptions, launchOptions, code, + settings.createCoverageExporter(), timings, !data.isVerbose()); + + final HistoryStore history = new ObjectOutputStreamHistoryStore(historyWriter, reader); + + final MutationStrategies strategies = new MutationStrategies( + settings.createEngine(), history, coverageDatabase, reportFactory, + reportOutput); + + final MutationCoverage report = new MutationCoverage(strategies, baseDir, + code, data, settings, timings); + + try { + return AnalysisResult.success(report.runReport()); + } catch (final IOException e) { + return AnalysisResult.fail(e); + } finally { + jac.close(); + ja.close(); + historyWriter.close(); + } + + } + + private void selectTestPlugin(ReportOptions data) { + if ((data.getTestPlugin() == null) || data.getTestPlugin().equals("")) { + if (junit5PluginIsOnClasspath()) { + data.setTestPlugin("junit5"); + } else { + data.setTestPlugin("junit"); + } + } + } + + private boolean junit5PluginIsOnClasspath() { + try { + Class.forName("org.pitest.junit5.JUnit5TestPluginFactory"); + return true; + } catch (final ClassNotFoundException e) { + return false; + } + } + + private SideEffect1 asInfo(final String leader) { + return a -> { + Log.getLogger().info(String.format("%1$-16s",leader + a.name()) + a.description()); + for (final FeatureParameter each : a.params()) { + Log.getLogger().info(String.format("%1$-18s", " [" + each.name() + "]") + each.description()); + } + }; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/JarCreatingJarFinder.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/JarCreatingJarFinder.java index ca8930843..c446256e7 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/JarCreatingJarFinder.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/JarCreatingJarFinder.java @@ -1,135 +1,135 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.tooling; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.jar.Attributes; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; -import java.util.zip.ZipEntry; - -import org.pitest.boot.HotSwapAgent; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classpath.ClassPathByteArraySource; -import java.util.Optional; -import org.pitest.process.JavaAgent; -import org.pitest.util.FileUtil; -import org.pitest.util.PitError; -import org.pitest.util.Unchecked; - -import sun.pitest.CodeCoverageStore; -import sun.pitest.InvokeReceiver; - -public class JarCreatingJarFinder implements JavaAgent { - - protected static final String CAN_REDEFINE_CLASSES = "Can-Redefine-Classes"; - protected static final String PREMAIN_CLASS = "Premain-Class"; - - protected static final String CAN_SET_NATIVE_METHOD = "Can-Set-Native-Method-Prefix"; - protected static final String BOOT_CLASSPATH = "Boot-Class-Path"; - - private static final String AGENT_CLASS_NAME = HotSwapAgent.class - .getName(); - - private Optional location = Optional.empty(); - - private final ClassByteArraySource classByteSource; - - public JarCreatingJarFinder(final ClassByteArraySource classByteSource) { - this.classByteSource = classByteSource; - } - - public JarCreatingJarFinder() { - this(new ClassPathByteArraySource()); - } - - @Override - public Optional getJarLocation() { - if (!this.location.isPresent()) { - this.location = createJar(); - } - return this.location; - } - - private Optional createJar() { - try { - - final File randomName = File.createTempFile(FileUtil.randomFilename(), - ".jar"); - final FileOutputStream fos = new FileOutputStream(randomName); - createJarFromClassPathResources(fos, randomName.getAbsolutePath()); - return Optional.ofNullable(randomName.getAbsolutePath()); - - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex); - } - } - - private void createJarFromClassPathResources(final FileOutputStream fos, - final String location) throws IOException { - final Manifest m = new Manifest(); - - m.clear(); - final Attributes global = m.getMainAttributes(); - if (global.getValue(Attributes.Name.MANIFEST_VERSION) == null) { - global.put(Attributes.Name.MANIFEST_VERSION, "1.0"); - } - final File mylocation = new File(location); - global.putValue(BOOT_CLASSPATH, getBootClassPath(mylocation)); - global.putValue(PREMAIN_CLASS, AGENT_CLASS_NAME); - global.putValue(CAN_REDEFINE_CLASSES, "true"); - global.putValue(CAN_SET_NATIVE_METHOD, "true"); - - try (JarOutputStream jos = new JarOutputStream(fos, m)) { - addClass(HotSwapAgent.class, jos); - addClass(CodeCoverageStore.class, jos); - addClass(InvokeReceiver.class, jos); - } - } - - private String getBootClassPath(final File mylocation) { - return mylocation.getAbsolutePath().replace('\\', '/'); - } - - private void addClass(final Class clazz, final JarOutputStream jos) - throws IOException { - final String className = clazz.getName(); - final ZipEntry ze = new ZipEntry(className.replace(".", "/") + ".class"); - jos.putNextEntry(ze); - jos.write(classBytes(className)); - jos.closeEntry(); - } - - private byte[] classBytes(final String className) { - final Optional bytes = this.classByteSource.getBytes(className); - - if (bytes.isPresent()) { - return bytes.get(); - } - - throw new PitError("Unable to load class content for " + className); - } - - @Override - public void close() { - if (this.location.isPresent()) { - final File f = new File(this.location.get()); - f.delete(); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.tooling; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.jar.Attributes; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; + +import org.pitest.boot.HotSwapAgent; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classpath.ClassPathByteArraySource; +import java.util.Optional; +import org.pitest.process.JavaAgent; +import org.pitest.util.FileUtil; +import org.pitest.util.PitError; +import org.pitest.util.Unchecked; + +import sun.pitest.CodeCoverageStore; +import sun.pitest.InvokeReceiver; + +public class JarCreatingJarFinder implements JavaAgent { + + protected static final String CAN_REDEFINE_CLASSES = "Can-Redefine-Classes"; + protected static final String PREMAIN_CLASS = "Premain-Class"; + + protected static final String CAN_SET_NATIVE_METHOD = "Can-Set-Native-Method-Prefix"; + protected static final String BOOT_CLASSPATH = "Boot-Class-Path"; + + private static final String AGENT_CLASS_NAME = HotSwapAgent.class + .getName(); + + private Optional location = Optional.empty(); + + private final ClassByteArraySource classByteSource; + + public JarCreatingJarFinder(final ClassByteArraySource classByteSource) { + this.classByteSource = classByteSource; + } + + public JarCreatingJarFinder() { + this(new ClassPathByteArraySource()); + } + + @Override + public Optional getJarLocation() { + if (!this.location.isPresent()) { + this.location = createJar(); + } + return this.location; + } + + private Optional createJar() { + try { + + final File randomName = File.createTempFile(FileUtil.randomFilename(), + ".jar"); + final FileOutputStream fos = new FileOutputStream(randomName); + createJarFromClassPathResources(fos, randomName.getAbsolutePath()); + return Optional.ofNullable(randomName.getAbsolutePath()); + + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex); + } + } + + private void createJarFromClassPathResources(final FileOutputStream fos, + final String location) throws IOException { + final Manifest m = new Manifest(); + + m.clear(); + final Attributes global = m.getMainAttributes(); + if (global.getValue(Attributes.Name.MANIFEST_VERSION) == null) { + global.put(Attributes.Name.MANIFEST_VERSION, "1.0"); + } + final File mylocation = new File(location); + global.putValue(BOOT_CLASSPATH, getBootClassPath(mylocation)); + global.putValue(PREMAIN_CLASS, AGENT_CLASS_NAME); + global.putValue(CAN_REDEFINE_CLASSES, "true"); + global.putValue(CAN_SET_NATIVE_METHOD, "true"); + + try (JarOutputStream jos = new JarOutputStream(fos, m)) { + addClass(HotSwapAgent.class, jos); + addClass(CodeCoverageStore.class, jos); + addClass(InvokeReceiver.class, jos); + } + } + + private String getBootClassPath(final File mylocation) { + return mylocation.getAbsolutePath().replace('\\', '/'); + } + + private void addClass(final Class clazz, final JarOutputStream jos) + throws IOException { + final String className = clazz.getName(); + final ZipEntry ze = new ZipEntry(className.replace(".", "/") + ".class"); + jos.putNextEntry(ze); + jos.write(classBytes(className)); + jos.closeEntry(); + } + + private byte[] classBytes(final String className) { + final Optional bytes = this.classByteSource.getBytes(className); + + if (bytes.isPresent()) { + return bytes.get(); + } + + throw new PitError("Unable to load class content for " + className); + } + + @Override + public void close() { + if (this.location.isPresent()) { + final File f = new File(this.location.get()); + f.delete(); + } + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/KnownLocationJavaAgentFinder.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/KnownLocationJavaAgentFinder.java index 78ab970f8..dec870687 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/KnownLocationJavaAgentFinder.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/KnownLocationJavaAgentFinder.java @@ -1,23 +1,23 @@ -package org.pitest.mutationtest.tooling; - -import java.util.Optional; -import org.pitest.process.JavaAgent; - -public class KnownLocationJavaAgentFinder implements JavaAgent { - - private final String location; - - public KnownLocationJavaAgentFinder(final String location) { - this.location = location; - } - - @Override - public Optional getJarLocation() { - return Optional.ofNullable(this.location); - } - - @Override - public void close() { - } - -} +package org.pitest.mutationtest.tooling; + +import java.util.Optional; +import org.pitest.process.JavaAgent; + +public class KnownLocationJavaAgentFinder implements JavaAgent { + + private final String location; + + public KnownLocationJavaAgentFinder(final String location) { + this.location = location; + } + + @Override + public Optional getJarLocation() { + return Optional.ofNullable(this.location); + } + + @Override + public void close() { + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/MutationCoverage.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/MutationCoverage.java index 27ad0a2de..d15c50ecd 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/MutationCoverage.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/MutationCoverage.java @@ -1,321 +1,321 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.tooling; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.HierarchicalClassId; -import org.pitest.classpath.ClassPathByteArraySource; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.coverage.CoverageGenerator; -import org.pitest.coverage.TestInfo; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.help.Help; -import org.pitest.help.PitHelpError; -import org.pitest.mutationtest.EngineArguments; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.ListenerArguments; -import org.pitest.mutationtest.MutationAnalyser; -import org.pitest.mutationtest.MutationConfig; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.build.MutationAnalysisUnit; -import org.pitest.mutationtest.build.MutationGrouper; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationSource; -import org.pitest.mutationtest.build.MutationTestBuilder; -import org.pitest.mutationtest.build.PercentAndConstantTimeoutStrategy; -import org.pitest.mutationtest.build.TestPrioritiser; -import org.pitest.mutationtest.build.WorkerFactory; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.config.SettingsFactory; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.mutationtest.execute.MutationAnalysisExecutor; -import org.pitest.mutationtest.incremental.DefaultCodeHistory; -import org.pitest.mutationtest.incremental.HistoryListener; -import org.pitest.mutationtest.incremental.IncrementalAnalyser; -import org.pitest.mutationtest.statistics.MutationStatisticsListener; -import org.pitest.mutationtest.statistics.Score; -import org.pitest.util.Log; -import org.pitest.util.StringUtil; -import org.pitest.util.Timings; - -public class MutationCoverage { - - private static final int MB = 1024 * 1024; - - private static final Logger LOG = Log.getLogger(); - private final ReportOptions data; - - private final MutationStrategies strategies; - private final Timings timings; - private final CodeSource code; - private final File baseDir; - private final SettingsFactory settings; - - public MutationCoverage(final MutationStrategies strategies, - final File baseDir, final CodeSource code, final ReportOptions data, - final SettingsFactory settings, final Timings timings) { - this.strategies = strategies; - this.data = data; - this.settings = settings; - this.timings = timings; - this.code = code; - this.baseDir = baseDir; - } - - public CombinedStatistics runReport() throws IOException { - - Log.setVerbose(this.data.isVerbose()); - - final Runtime runtime = Runtime.getRuntime(); - - if (!this.data.isVerbose()) { - LOG.info("Verbose logging is disabled. If you encounter an problem please enable it before reporting an issue."); - } - - LOG.fine("Running report with " + this.data); - - LOG.fine("System class path is " + System.getProperty("java.class.path")); - LOG.fine("Maximum available memory is " + (runtime.maxMemory() / MB) - + " mb"); - - final long t0 = System.currentTimeMillis(); - - verifyBuildSuitableForMutationTesting(); - - checkExcludedRunners(); - - final CoverageDatabase coverageData = coverage().calculateCoverage(); - - LOG.fine("Used memory after coverage calculation " - + ((runtime.totalMemory() - runtime.freeMemory()) / MB) + " mb"); - LOG.fine("Free Memory after coverage calculation " - + (runtime.freeMemory() / MB) + " mb"); - - final MutationStatisticsListener stats = new MutationStatisticsListener(); - - final EngineArguments args = EngineArguments.arguments() - .withExcludedMethods(this.data.getExcludedMethods()) - .withMutators(this.data.getMutators()); - final MutationEngine engine = this.strategies.factory().createEngine(args); - - final List config = createConfig(t0, coverageData, - stats, engine); - - history().initialize(); - - this.timings.registerStart(Timings.Stage.BUILD_MUTATION_TESTS); - final List tus = buildMutationTests(coverageData, - engine, args); - this.timings.registerEnd(Timings.Stage.BUILD_MUTATION_TESTS); - - LOG.info("Created " + tus.size() + " mutation test units"); - checkMutationsFound(tus); - - recordClassPath(coverageData); - - LOG.fine("Used memory before analysis start " - + ((runtime.totalMemory() - runtime.freeMemory()) / MB) + " mb"); - LOG.fine("Free Memory before analysis start " + (runtime.freeMemory() / MB) - + " mb"); - - final MutationAnalysisExecutor mae = new MutationAnalysisExecutor( - numberOfThreads(), config); - this.timings.registerStart(Timings.Stage.RUN_MUTATION_TESTS); - mae.run(tus); - this.timings.registerEnd(Timings.Stage.RUN_MUTATION_TESTS); - - LOG.info("Completed in " + timeSpan(t0)); - - printStats(stats); - - return new CombinedStatistics(stats.getStatistics(), - coverageData.createSummary()); - - } - - private void checkExcludedRunners() { - final Collection excludedRunners = this.data.getExcludedRunners(); - if (!excludedRunners.isEmpty()) { - // Check whether JUnit4 is available or not - try { - Class.forName("org.junit.runner.RunWith"); - } catch (final ClassNotFoundException e) { - // JUnit4 is not available on the classpath - throw new PitHelpError(Help.NO_JUNIT_EXCLUDE_RUNNERS); - } - } - } - -private int numberOfThreads() { - return Math.max(1, this.data.getNumberOfThreads()); - } - - private List createConfig(final long t0, - final CoverageDatabase coverageData, - final MutationStatisticsListener stats, final MutationEngine engine) { - final List ls = new ArrayList<>(); - - ls.add(stats); - - final ListenerArguments args = new ListenerArguments( - this.strategies.output(), coverageData, new SmartSourceLocator( - this.data.getSourceDirs()), engine, t0); - - final MutationResultListener mutationReportListener = this.strategies - .listenerFactory().getListener(this.data.getFreeFormProperties(), args); - - ls.add(mutationReportListener); - ls.add(new HistoryListener(history())); - - if (!this.data.isVerbose()) { - ls.add(new SpinnerListener(System.out)); - } - return ls; - } - - private void recordClassPath(final CoverageDatabase coverageData) { - final Set allClassNames = getAllClassesAndTests(coverageData); - final Collection ids = FCollection.map( - this.code.getClassInfo(allClassNames), ClassInfo.toFullClassId()); - history().recordClassPath(ids, coverageData); - } - - private Set getAllClassesAndTests( - final CoverageDatabase coverageData) { - final Set names = new HashSet<>(); - for (final ClassName each : this.code.getCodeUnderTestNames()) { - names.add(each); - FCollection.mapTo(coverageData.getTestsForClass(each), - TestInfo.toDefiningClassName(), names); - } - return names; - } - - private void verifyBuildSuitableForMutationTesting() { - this.strategies.buildVerifier().verify(this.code); - } - - private void printStats(final MutationStatisticsListener stats) { - final PrintStream ps = System.out; - ps.println(StringUtil.separatorLine('=')); - ps.println("- Timings"); - ps.println(StringUtil.separatorLine('=')); - this.timings.report(ps); - - ps.println(StringUtil.separatorLine('=')); - ps.println("- Statistics"); - ps.println(StringUtil.separatorLine('=')); - stats.getStatistics().report(ps); - - ps.println(StringUtil.separatorLine('=')); - ps.println("- Mutators"); - ps.println(StringUtil.separatorLine('=')); - for (final Score each : stats.getStatistics().getScores()) { - each.report(ps); - ps.println(StringUtil.separatorLine()); - } - } - - private List buildMutationTests( - final CoverageDatabase coverageData, final MutationEngine engine, EngineArguments args) { - - final MutationConfig mutationConfig = new MutationConfig(engine, coverage() - .getLaunchOptions()); - - final ClassByteArraySource bas = fallbackToClassLoader(new ClassPathByteArraySource( - this.data.getClassPath())); - - final TestPrioritiser testPrioritiser = this.settings.getTestPrioritiser() - .makeTestPrioritiser(this.data.getFreeFormProperties(), this.code, - coverageData); - - final MutationInterceptor interceptor = this.settings.getInterceptor() - .createInterceptor(this.data, bas); - - final MutationSource source = new MutationSource(mutationConfig, testPrioritiser, bas, interceptor); - - final MutationAnalyser analyser = new IncrementalAnalyser( - new DefaultCodeHistory(this.code, history()), coverageData); - - final WorkerFactory wf = new WorkerFactory(this.baseDir, coverage() - .getConfiguration(), mutationConfig, args, - new PercentAndConstantTimeoutStrategy(this.data.getTimeoutFactor(), - this.data.getTimeoutConstant()), this.data.isVerbose(), this.data - .getClassPath().getLocalClassPath()); - - final MutationGrouper grouper = this.settings.getMutationGrouper().makeFactory( - this.data.getFreeFormProperties(), this.code, - this.data.getNumberOfThreads(), this.data.getMutationUnitSize()); - final MutationTestBuilder builder = new MutationTestBuilder(wf, analyser, - source, grouper); - - return builder.createMutationTestUnits(this.code.getCodeUnderTestNames()); - } - - private void checkMutationsFound(final List tus) { - if (tus.isEmpty()) { - if (this.data.shouldFailWhenNoMutations()) { - throw new PitHelpError(Help.NO_MUTATIONS_FOUND); - } else { - LOG.warning(Help.NO_MUTATIONS_FOUND.toString()); - } - } - } - - private String timeSpan(final long t0) { - return "" + ((System.currentTimeMillis() - t0) / 1000) + " seconds"; - } - - private CoverageGenerator coverage() { - return this.strategies.coverage(); - } - - private HistoryStore history() { - return this.strategies.history(); - } - - // For reasons not yet understood classes from rt.jar are not resolved for some - // projects during static analysis phase. For now fall back to the classloader when - // a class not provided by project classpath - private ClassByteArraySource fallbackToClassLoader(final ClassByteArraySource bas) { - final ClassByteArraySource clSource = ClassloaderByteArraySource.fromContext(); - return clazz -> { - final Optional maybeBytes = bas.getBytes(clazz); - if (maybeBytes.isPresent()) { - return maybeBytes; - } - LOG.log(Level.FINE, "Could not find " + clazz + " on classpath for analysis. Falling back to classloader"); - return clSource.getBytes(clazz); - }; - } - - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.tooling; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.HierarchicalClassId; +import org.pitest.classpath.ClassPathByteArraySource; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.coverage.CoverageGenerator; +import org.pitest.coverage.TestInfo; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.help.Help; +import org.pitest.help.PitHelpError; +import org.pitest.mutationtest.EngineArguments; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.ListenerArguments; +import org.pitest.mutationtest.MutationAnalyser; +import org.pitest.mutationtest.MutationConfig; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.build.MutationAnalysisUnit; +import org.pitest.mutationtest.build.MutationGrouper; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationSource; +import org.pitest.mutationtest.build.MutationTestBuilder; +import org.pitest.mutationtest.build.PercentAndConstantTimeoutStrategy; +import org.pitest.mutationtest.build.TestPrioritiser; +import org.pitest.mutationtest.build.WorkerFactory; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.config.SettingsFactory; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.mutationtest.execute.MutationAnalysisExecutor; +import org.pitest.mutationtest.incremental.DefaultCodeHistory; +import org.pitest.mutationtest.incremental.HistoryListener; +import org.pitest.mutationtest.incremental.IncrementalAnalyser; +import org.pitest.mutationtest.statistics.MutationStatisticsListener; +import org.pitest.mutationtest.statistics.Score; +import org.pitest.util.Log; +import org.pitest.util.StringUtil; +import org.pitest.util.Timings; + +public class MutationCoverage { + + private static final int MB = 1024 * 1024; + + private static final Logger LOG = Log.getLogger(); + private final ReportOptions data; + + private final MutationStrategies strategies; + private final Timings timings; + private final CodeSource code; + private final File baseDir; + private final SettingsFactory settings; + + public MutationCoverage(final MutationStrategies strategies, + final File baseDir, final CodeSource code, final ReportOptions data, + final SettingsFactory settings, final Timings timings) { + this.strategies = strategies; + this.data = data; + this.settings = settings; + this.timings = timings; + this.code = code; + this.baseDir = baseDir; + } + + public CombinedStatistics runReport() throws IOException { + + Log.setVerbose(this.data.isVerbose()); + + final Runtime runtime = Runtime.getRuntime(); + + if (!this.data.isVerbose()) { + LOG.info("Verbose logging is disabled. If you encounter an problem please enable it before reporting an issue."); + } + + LOG.fine("Running report with " + this.data); + + LOG.fine("System class path is " + System.getProperty("java.class.path")); + LOG.fine("Maximum available memory is " + (runtime.maxMemory() / MB) + + " mb"); + + final long t0 = System.currentTimeMillis(); + + verifyBuildSuitableForMutationTesting(); + + checkExcludedRunners(); + + final CoverageDatabase coverageData = coverage().calculateCoverage(); + + LOG.fine("Used memory after coverage calculation " + + ((runtime.totalMemory() - runtime.freeMemory()) / MB) + " mb"); + LOG.fine("Free Memory after coverage calculation " + + (runtime.freeMemory() / MB) + " mb"); + + final MutationStatisticsListener stats = new MutationStatisticsListener(); + + final EngineArguments args = EngineArguments.arguments() + .withExcludedMethods(this.data.getExcludedMethods()) + .withMutators(this.data.getMutators()); + final MutationEngine engine = this.strategies.factory().createEngine(args); + + final List config = createConfig(t0, coverageData, + stats, engine); + + history().initialize(); + + this.timings.registerStart(Timings.Stage.BUILD_MUTATION_TESTS); + final List tus = buildMutationTests(coverageData, + engine, args); + this.timings.registerEnd(Timings.Stage.BUILD_MUTATION_TESTS); + + LOG.info("Created " + tus.size() + " mutation test units"); + checkMutationsFound(tus); + + recordClassPath(coverageData); + + LOG.fine("Used memory before analysis start " + + ((runtime.totalMemory() - runtime.freeMemory()) / MB) + " mb"); + LOG.fine("Free Memory before analysis start " + (runtime.freeMemory() / MB) + + " mb"); + + final MutationAnalysisExecutor mae = new MutationAnalysisExecutor( + numberOfThreads(), config); + this.timings.registerStart(Timings.Stage.RUN_MUTATION_TESTS); + mae.run(tus); + this.timings.registerEnd(Timings.Stage.RUN_MUTATION_TESTS); + + LOG.info("Completed in " + timeSpan(t0)); + + printStats(stats); + + return new CombinedStatistics(stats.getStatistics(), + coverageData.createSummary()); + + } + + private void checkExcludedRunners() { + final Collection excludedRunners = this.data.getExcludedRunners(); + if (!excludedRunners.isEmpty()) { + // Check whether JUnit4 is available or not + try { + Class.forName("org.junit.runner.RunWith"); + } catch (final ClassNotFoundException e) { + // JUnit4 is not available on the classpath + throw new PitHelpError(Help.NO_JUNIT_EXCLUDE_RUNNERS); + } + } + } + +private int numberOfThreads() { + return Math.max(1, this.data.getNumberOfThreads()); + } + + private List createConfig(final long t0, + final CoverageDatabase coverageData, + final MutationStatisticsListener stats, final MutationEngine engine) { + final List ls = new ArrayList<>(); + + ls.add(stats); + + final ListenerArguments args = new ListenerArguments( + this.strategies.output(), coverageData, new SmartSourceLocator( + this.data.getSourceDirs()), engine, t0); + + final MutationResultListener mutationReportListener = this.strategies + .listenerFactory().getListener(this.data.getFreeFormProperties(), args); + + ls.add(mutationReportListener); + ls.add(new HistoryListener(history())); + + if (!this.data.isVerbose()) { + ls.add(new SpinnerListener(System.out)); + } + return ls; + } + + private void recordClassPath(final CoverageDatabase coverageData) { + final Set allClassNames = getAllClassesAndTests(coverageData); + final Collection ids = FCollection.map( + this.code.getClassInfo(allClassNames), ClassInfo.toFullClassId()); + history().recordClassPath(ids, coverageData); + } + + private Set getAllClassesAndTests( + final CoverageDatabase coverageData) { + final Set names = new HashSet<>(); + for (final ClassName each : this.code.getCodeUnderTestNames()) { + names.add(each); + FCollection.mapTo(coverageData.getTestsForClass(each), + TestInfo.toDefiningClassName(), names); + } + return names; + } + + private void verifyBuildSuitableForMutationTesting() { + this.strategies.buildVerifier().verify(this.code); + } + + private void printStats(final MutationStatisticsListener stats) { + final PrintStream ps = System.out; + ps.println(StringUtil.separatorLine('=')); + ps.println("- Timings"); + ps.println(StringUtil.separatorLine('=')); + this.timings.report(ps); + + ps.println(StringUtil.separatorLine('=')); + ps.println("- Statistics"); + ps.println(StringUtil.separatorLine('=')); + stats.getStatistics().report(ps); + + ps.println(StringUtil.separatorLine('=')); + ps.println("- Mutators"); + ps.println(StringUtil.separatorLine('=')); + for (final Score each : stats.getStatistics().getScores()) { + each.report(ps); + ps.println(StringUtil.separatorLine()); + } + } + + private List buildMutationTests( + final CoverageDatabase coverageData, final MutationEngine engine, EngineArguments args) { + + final MutationConfig mutationConfig = new MutationConfig(engine, coverage() + .getLaunchOptions()); + + final ClassByteArraySource bas = fallbackToClassLoader(new ClassPathByteArraySource( + this.data.getClassPath())); + + final TestPrioritiser testPrioritiser = this.settings.getTestPrioritiser() + .makeTestPrioritiser(this.data.getFreeFormProperties(), this.code, + coverageData); + + final MutationInterceptor interceptor = this.settings.getInterceptor() + .createInterceptor(this.data, bas); + + final MutationSource source = new MutationSource(mutationConfig, testPrioritiser, bas, interceptor); + + final MutationAnalyser analyser = new IncrementalAnalyser( + new DefaultCodeHistory(this.code, history()), coverageData); + + final WorkerFactory wf = new WorkerFactory(this.baseDir, coverage() + .getConfiguration(), mutationConfig, args, + new PercentAndConstantTimeoutStrategy(this.data.getTimeoutFactor(), + this.data.getTimeoutConstant()), this.data.isVerbose(), this.data + .getClassPath().getLocalClassPath()); + + final MutationGrouper grouper = this.settings.getMutationGrouper().makeFactory( + this.data.getFreeFormProperties(), this.code, + this.data.getNumberOfThreads(), this.data.getMutationUnitSize()); + final MutationTestBuilder builder = new MutationTestBuilder(wf, analyser, + source, grouper); + + return builder.createMutationTestUnits(this.code.getCodeUnderTestNames()); + } + + private void checkMutationsFound(final List tus) { + if (tus.isEmpty()) { + if (this.data.shouldFailWhenNoMutations()) { + throw new PitHelpError(Help.NO_MUTATIONS_FOUND); + } else { + LOG.warning(Help.NO_MUTATIONS_FOUND.toString()); + } + } + } + + private String timeSpan(final long t0) { + return "" + ((System.currentTimeMillis() - t0) / 1000) + " seconds"; + } + + private CoverageGenerator coverage() { + return this.strategies.coverage(); + } + + private HistoryStore history() { + return this.strategies.history(); + } + + // For reasons not yet understood classes from rt.jar are not resolved for some + // projects during static analysis phase. For now fall back to the classloader when + // a class not provided by project classpath + private ClassByteArraySource fallbackToClassLoader(final ClassByteArraySource bas) { + final ClassByteArraySource clSource = ClassloaderByteArraySource.fromContext(); + return clazz -> { + final Optional maybeBytes = bas.getBytes(clazz); + if (maybeBytes.isPresent()) { + return maybeBytes; + } + LOG.log(Level.FINE, "Could not find " + clazz + " on classpath for analysis. Falling back to classloader"); + return clSource.getBytes(clazz); + }; + } + + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/MutationStrategies.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/MutationStrategies.java index f59ee481e..1c1f74b22 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/MutationStrategies.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/MutationStrategies.java @@ -1,74 +1,74 @@ -package org.pitest.mutationtest.tooling; - -import org.pitest.coverage.CoverageGenerator; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.MutationEngineFactory; -import org.pitest.mutationtest.MutationResultListenerFactory; -import org.pitest.mutationtest.verify.BuildVerifier; -import org.pitest.mutationtest.verify.DefaultBuildVerifier; -import org.pitest.util.ResultOutputStrategy; - -public class MutationStrategies { - - private final HistoryStore history; - private final CoverageGenerator coverage; - private final MutationResultListenerFactory listenerFactory; - private final BuildVerifier buildVerifier; - private final MutationEngineFactory factory; - private final ResultOutputStrategy output; - - public MutationStrategies(final MutationEngineFactory factory, - final HistoryStore history, final CoverageGenerator coverage, - final MutationResultListenerFactory listenerFactory, - final ResultOutputStrategy output) { - this(factory, history, coverage, listenerFactory, output, - new DefaultBuildVerifier()); - } - - private MutationStrategies(final MutationEngineFactory factory, - final HistoryStore history, final CoverageGenerator coverage, - final MutationResultListenerFactory listenerFactory, - final ResultOutputStrategy output, final BuildVerifier buildVerifier) { - this.history = history; - this.coverage = coverage; - this.listenerFactory = listenerFactory; - this.buildVerifier = buildVerifier; - this.factory = factory; - this.output = output; - } - - public HistoryStore history() { - return this.history; - } - - public CoverageGenerator coverage() { - return this.coverage; - } - - public MutationResultListenerFactory listenerFactory() { - return this.listenerFactory; - } - - public BuildVerifier buildVerifier() { - return this.buildVerifier; - } - - public MutationEngineFactory factory() { - return this.factory; - } - - public ResultOutputStrategy output() { - return this.output; - } - - public MutationStrategies with(final MutationEngineFactory factory) { - return new MutationStrategies(factory, this.history, this.coverage, - this.listenerFactory, this.output, this.buildVerifier); - } - - public MutationStrategies with(final BuildVerifier verifier) { - return new MutationStrategies(this.factory, this.history, this.coverage, - this.listenerFactory, this.output, verifier); - } - -} +package org.pitest.mutationtest.tooling; + +import org.pitest.coverage.CoverageGenerator; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.MutationEngineFactory; +import org.pitest.mutationtest.MutationResultListenerFactory; +import org.pitest.mutationtest.verify.BuildVerifier; +import org.pitest.mutationtest.verify.DefaultBuildVerifier; +import org.pitest.util.ResultOutputStrategy; + +public class MutationStrategies { + + private final HistoryStore history; + private final CoverageGenerator coverage; + private final MutationResultListenerFactory listenerFactory; + private final BuildVerifier buildVerifier; + private final MutationEngineFactory factory; + private final ResultOutputStrategy output; + + public MutationStrategies(final MutationEngineFactory factory, + final HistoryStore history, final CoverageGenerator coverage, + final MutationResultListenerFactory listenerFactory, + final ResultOutputStrategy output) { + this(factory, history, coverage, listenerFactory, output, + new DefaultBuildVerifier()); + } + + private MutationStrategies(final MutationEngineFactory factory, + final HistoryStore history, final CoverageGenerator coverage, + final MutationResultListenerFactory listenerFactory, + final ResultOutputStrategy output, final BuildVerifier buildVerifier) { + this.history = history; + this.coverage = coverage; + this.listenerFactory = listenerFactory; + this.buildVerifier = buildVerifier; + this.factory = factory; + this.output = output; + } + + public HistoryStore history() { + return this.history; + } + + public CoverageGenerator coverage() { + return this.coverage; + } + + public MutationResultListenerFactory listenerFactory() { + return this.listenerFactory; + } + + public BuildVerifier buildVerifier() { + return this.buildVerifier; + } + + public MutationEngineFactory factory() { + return this.factory; + } + + public ResultOutputStrategy output() { + return this.output; + } + + public MutationStrategies with(final MutationEngineFactory factory) { + return new MutationStrategies(factory, this.history, this.coverage, + this.listenerFactory, this.output, this.buildVerifier); + } + + public MutationStrategies with(final BuildVerifier verifier) { + return new MutationStrategies(this.factory, this.history, this.coverage, + this.listenerFactory, this.output, verifier); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/SmartSourceLocator.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/SmartSourceLocator.java index e9f1aaf88..59b422abb 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/SmartSourceLocator.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/SmartSourceLocator.java @@ -1,72 +1,72 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.tooling; - -import java.io.File; -import java.io.Reader; -import java.util.Collection; -import java.util.function.Function; - -import org.pitest.functional.FArray; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.SourceLocator; - -public class SmartSourceLocator implements SourceLocator { - - private static final int MAX_DEPTH = 4; - - private final Collection children; - - public SmartSourceLocator(final Collection roots) { - final Collection childDirs = FCollection.flatMap(roots, - collectChildren(0)); - childDirs.addAll(roots); - - final Function fileToSourceLocator = a -> new DirectorySourceLocator(a); - this.children = FCollection.map(childDirs, fileToSourceLocator); - } - - private Function> collectChildren(final int depth) { - return a -> collectDirectories(a, depth); - } - - private Collection collectDirectories(final File root, final int depth) { - final Collection childDirs = listFirstLevelDirectories(root); - if (depth < MAX_DEPTH) { - childDirs.addAll(FCollection.flatMap(childDirs, - collectChildren(depth + 1))); - } - return childDirs; - - } - - private static Collection listFirstLevelDirectories(final File root) { - return FArray.filter(root.listFiles(), a -> a.isDirectory()); - } - - @Override - public Optional locate(final Collection classes, - final String fileName) { - for (final SourceLocator each : this.children) { - final Optional reader = each.locate(classes, fileName); - if (reader.isPresent()) { - return reader; - } - } - return Optional.empty(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.tooling; + +import java.io.File; +import java.io.Reader; +import java.util.Collection; +import java.util.function.Function; + +import org.pitest.functional.FArray; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.SourceLocator; + +public class SmartSourceLocator implements SourceLocator { + + private static final int MAX_DEPTH = 4; + + private final Collection children; + + public SmartSourceLocator(final Collection roots) { + final Collection childDirs = FCollection.flatMap(roots, + collectChildren(0)); + childDirs.addAll(roots); + + final Function fileToSourceLocator = a -> new DirectorySourceLocator(a); + this.children = FCollection.map(childDirs, fileToSourceLocator); + } + + private Function> collectChildren(final int depth) { + return a -> collectDirectories(a, depth); + } + + private Collection collectDirectories(final File root, final int depth) { + final Collection childDirs = listFirstLevelDirectories(root); + if (depth < MAX_DEPTH) { + childDirs.addAll(FCollection.flatMap(childDirs, + collectChildren(depth + 1))); + } + return childDirs; + + } + + private static Collection listFirstLevelDirectories(final File root) { + return FArray.filter(root.listFiles(), a -> a.isDirectory()); + } + + @Override + public Optional locate(final Collection classes, + final String fileName) { + for (final SourceLocator each : this.children) { + final Optional reader = each.locate(classes, fileName); + if (reader.isPresent()) { + return reader; + } + } + return Optional.empty(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/SpinnerListener.java b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/SpinnerListener.java index 8d488a181..e28cd7e25 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/SpinnerListener.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/tooling/SpinnerListener.java @@ -1,37 +1,37 @@ -package org.pitest.mutationtest.tooling; - -import java.io.PrintStream; - -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationResultListener; - -public class SpinnerListener implements MutationResultListener { - - private static final String[] SPINNER_CHARS = new String[] { "\u0008/", - "\u0008-", "\u0008\\", "\u0008|" }; - - private final PrintStream out; - - private int position = 0; - - public SpinnerListener(final PrintStream out) { - this.out = out; - } - - @Override - public void runStart() { - - } - - @Override - public void handleMutationResult(final ClassMutationResults metaData) { - this.out.printf("%s", SPINNER_CHARS[this.position % SPINNER_CHARS.length]); - this.position++; - } - - @Override - public void runEnd() { - - } - -} +package org.pitest.mutationtest.tooling; + +import java.io.PrintStream; + +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationResultListener; + +public class SpinnerListener implements MutationResultListener { + + private static final String[] SPINNER_CHARS = new String[] { "\u0008/", + "\u0008-", "\u0008\\", "\u0008|" }; + + private final PrintStream out; + + private int position = 0; + + public SpinnerListener(final PrintStream out) { + this.out = out; + } + + @Override + public void runStart() { + + } + + @Override + public void handleMutationResult(final ClassMutationResults metaData) { + this.out.printf("%s", SPINNER_CHARS[this.position % SPINNER_CHARS.length]); + this.position++; + } + + @Override + public void runEnd() { + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/verify/BuildVerifier.java b/pitest-entry/src/main/java/org/pitest/mutationtest/verify/BuildVerifier.java index 92bf91088..197c74c8c 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/verify/BuildVerifier.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/verify/BuildVerifier.java @@ -1,9 +1,9 @@ -package org.pitest.mutationtest.verify; - -import org.pitest.classpath.CodeSource; - -public interface BuildVerifier { - - void verify(CodeSource coverageDatabase); - -} +package org.pitest.mutationtest.verify; + +import org.pitest.classpath.CodeSource; + +public interface BuildVerifier { + + void verify(CodeSource coverageDatabase); + +} diff --git a/pitest-entry/src/main/java/org/pitest/mutationtest/verify/DefaultBuildVerifier.java b/pitest-entry/src/main/java/org/pitest/mutationtest/verify/DefaultBuildVerifier.java index bacb101ac..6bd43574e 100644 --- a/pitest-entry/src/main/java/org/pitest/mutationtest/verify/DefaultBuildVerifier.java +++ b/pitest-entry/src/main/java/org/pitest/mutationtest/verify/DefaultBuildVerifier.java @@ -1,77 +1,77 @@ -package org.pitest.mutationtest.verify; - -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -import java.util.Collection; -import java.util.function.Predicate; - -import org.pitest.classinfo.ClassInfo; -import org.pitest.classpath.CodeSource; -import org.pitest.functional.FCollection; -import org.pitest.functional.SideEffect1; -import org.pitest.help.Help; -import org.pitest.help.PitHelpError; - -public class DefaultBuildVerifier implements BuildVerifier { - - @Override - public void verify(final CodeSource code) { - final Collection codeClasses = FCollection.filter(code.getCode(), isNotSynthetic()); - - if (hasMutableCode(codeClasses)) { - checkAtLeastOneClassHasLineNumbers(codeClasses); - FCollection.forEach(codeClasses, throwErrorIfHasNoSourceFile()); - } - } - - private boolean hasMutableCode(Collection codeClasses ) { - return !codeClasses.isEmpty() && hasAtLeastOneClass(codeClasses); - } - - private boolean hasAtLeastOneClass(final Collection codeClasses) { - return FCollection.contains(codeClasses, aConcreteClass()); - } - - private void checkAtLeastOneClassHasLineNumbers( - final Collection codeClasses) { - // perform only a weak check for line numbers as - // some jvm languages are not guaranteed to produce them for all classes - if (!FCollection.contains(codeClasses, aClassWithLineNumbers())) { - throw new PitHelpError(Help.NO_LINE_NUMBERS); - } - } - - private static Predicate aConcreteClass() { - return a -> !a.isInterface(); - } - - private static Predicate aClassWithLineNumbers() { - return a -> a.getNumberOfCodeLines() != 0; - } - - private SideEffect1 throwErrorIfHasNoSourceFile() { - return a -> { - if (a.getSourceFileName() == null) { - throw new PitHelpError(Help.NO_SOURCE_FILE, a.getName().asJavaName()); - } - }; - } - - private static Predicate isNotSynthetic() { - return a -> !a.isSynthetic(); - } - -} +package org.pitest.mutationtest.verify; + +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +import java.util.Collection; +import java.util.function.Predicate; + +import org.pitest.classinfo.ClassInfo; +import org.pitest.classpath.CodeSource; +import org.pitest.functional.FCollection; +import org.pitest.functional.SideEffect1; +import org.pitest.help.Help; +import org.pitest.help.PitHelpError; + +public class DefaultBuildVerifier implements BuildVerifier { + + @Override + public void verify(final CodeSource code) { + final Collection codeClasses = FCollection.filter(code.getCode(), isNotSynthetic()); + + if (hasMutableCode(codeClasses)) { + checkAtLeastOneClassHasLineNumbers(codeClasses); + FCollection.forEach(codeClasses, throwErrorIfHasNoSourceFile()); + } + } + + private boolean hasMutableCode(Collection codeClasses ) { + return !codeClasses.isEmpty() && hasAtLeastOneClass(codeClasses); + } + + private boolean hasAtLeastOneClass(final Collection codeClasses) { + return FCollection.contains(codeClasses, aConcreteClass()); + } + + private void checkAtLeastOneClassHasLineNumbers( + final Collection codeClasses) { + // perform only a weak check for line numbers as + // some jvm languages are not guaranteed to produce them for all classes + if (!FCollection.contains(codeClasses, aClassWithLineNumbers())) { + throw new PitHelpError(Help.NO_LINE_NUMBERS); + } + } + + private static Predicate aConcreteClass() { + return a -> !a.isInterface(); + } + + private static Predicate aClassWithLineNumbers() { + return a -> a.getNumberOfCodeLines() != 0; + } + + private SideEffect1 throwErrorIfHasNoSourceFile() { + return a -> { + if (a.getSourceFileName() == null) { + throw new PitHelpError(Help.NO_SOURCE_FILE, a.getName().asJavaName()); + } + }; + } + + private static Predicate isNotSynthetic() { + return a -> !a.isSynthetic(); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/plugin/export/MutantExportFactory.java b/pitest-entry/src/main/java/org/pitest/plugin/export/MutantExportFactory.java index 4dcbd46b8..b2b83eec6 100644 --- a/pitest-entry/src/main/java/org/pitest/plugin/export/MutantExportFactory.java +++ b/pitest-entry/src/main/java/org/pitest/plugin/export/MutantExportFactory.java @@ -1,29 +1,29 @@ -package org.pitest.plugin.export; - -import java.nio.file.FileSystems; - -import org.pitest.mutationtest.build.InterceptorParameters; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationInterceptorFactory; -import org.pitest.plugin.Feature; - -public class MutantExportFactory implements MutationInterceptorFactory { - - @Override - public String description() { - return "Mutant export plugin"; - } - - @Override - public MutationInterceptor createInterceptor(InterceptorParameters params) { - return new MutantExportInterceptor(FileSystems.getDefault(), params.source(), params.data().getReportDir()); - } - - @Override - public Feature provides() { - return Feature.named("EXPORT") - .withDescription("Exports mutants bytecode and other details to disk") - .withOnByDefault(false); - } - -} +package org.pitest.plugin.export; + +import java.nio.file.FileSystems; + +import org.pitest.mutationtest.build.InterceptorParameters; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationInterceptorFactory; +import org.pitest.plugin.Feature; + +public class MutantExportFactory implements MutationInterceptorFactory { + + @Override + public String description() { + return "Mutant export plugin"; + } + + @Override + public MutationInterceptor createInterceptor(InterceptorParameters params) { + return new MutantExportInterceptor(FileSystems.getDefault(), params.source(), params.data().getReportDir()); + } + + @Override + public Feature provides() { + return Feature.named("EXPORT") + .withDescription("Exports mutants bytecode and other details to disk") + .withOnByDefault(false); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/plugin/export/MutantExportInterceptor.java b/pitest-entry/src/main/java/org/pitest/plugin/export/MutantExportInterceptor.java index 2e99abab9..af29d7c72 100644 --- a/pitest-entry/src/main/java/org/pitest/plugin/export/MutantExportInterceptor.java +++ b/pitest-entry/src/main/java/org/pitest/plugin/export/MutantExportInterceptor.java @@ -1,120 +1,120 @@ -package org.pitest.plugin.export; - -import java.io.CharArrayWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileSystem; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.util.Textifier; -import org.objectweb.asm.util.TraceClassVisitor; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -public class MutantExportInterceptor implements MutationInterceptor { - - private final String outDir; - private final FileSystem fileSystem; - private final ClassByteArraySource source; - - private Path mutantsDir; - private ClassName currentClass; - - public MutantExportInterceptor(FileSystem fileSystem, - ClassByteArraySource source, String outDir) { - this.fileSystem = fileSystem; - this.outDir = outDir; - this.source = source; - } - - @Override - public InterceptorType type() { - return InterceptorType.REPORT; - } - - @Override - public void begin(ClassTree clazz) { - this.currentClass = clazz.name(); - final String[] classLocation = ("export." + clazz.name().asJavaName()) - .split("\\."); - final Path classDir = this.fileSystem.getPath(this.outDir, classLocation); - this.mutantsDir = classDir.resolve("mutants"); - try { - Files.createDirectories(this.mutantsDir); - writeBytecodeToDisk(this.source.getBytes(clazz.name().asJavaName()).get(), classDir); - } catch (final IOException e) { - throw new RuntimeException("Couldn't create direectory for " + clazz, e); - } - } - - @Override - public Collection intercept( - Collection mutations, Mutater m) { - - final List indexable = new ArrayList<>(mutations); - - try { - for (int i = 0; i != indexable.size(); i++) { - exportMutantDetails(m, indexable, i); - } - } catch (final IOException ex) { - throw new RuntimeException("Error exporting mutants for report", ex); - } - - return mutations; - } - - private void exportMutantDetails(Mutater m, List indexable, - int i) throws IOException { - final MutationDetails md = indexable.get(i); - final Path mutantFolder = this.mutantsDir.resolve("" + i); - Files.createDirectories(mutantFolder); - - final Mutant mutant = m.getMutation(md.getId()); - - writeMutantToDisk(mutant, mutantFolder); - writeBytecodeToDisk(mutant.getBytes(), mutantFolder); - writeDetailsToDisk(md, mutantFolder); - } - - private void writeMutantToDisk(Mutant mutant, Path mutantFolder) throws IOException { - final Path outFile = mutantFolder.resolve(this.currentClass.asJavaName() + ".class"); - Files.write(outFile, mutant.getBytes(), StandardOpenOption.CREATE); - } - - - private void writeBytecodeToDisk(final byte[] clazz, Path folder) throws IOException { - final ClassReader reader = new ClassReader(clazz); - final CharArrayWriter buffer = new CharArrayWriter(); - reader.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter( - buffer)), ClassReader.EXPAND_FRAMES); - final Path outFile = folder.resolve(this.currentClass.asJavaName() + ".txt"); - Files.write(outFile, Collections.singleton(buffer.toString()), StandardCharsets.UTF_8, StandardOpenOption.CREATE); - } - - private void writeDetailsToDisk(MutationDetails md, - Path mutantFolder) throws IOException { - final Path outFile = mutantFolder.resolve("details.txt"); - Files.write(outFile, Collections.singleton(md.toString()), StandardCharsets.UTF_8, StandardOpenOption.CREATE); - } - - @Override - public void end() { - - } - -} +package org.pitest.plugin.export; + +import java.io.CharArrayWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.util.Textifier; +import org.objectweb.asm.util.TraceClassVisitor; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +public class MutantExportInterceptor implements MutationInterceptor { + + private final String outDir; + private final FileSystem fileSystem; + private final ClassByteArraySource source; + + private Path mutantsDir; + private ClassName currentClass; + + public MutantExportInterceptor(FileSystem fileSystem, + ClassByteArraySource source, String outDir) { + this.fileSystem = fileSystem; + this.outDir = outDir; + this.source = source; + } + + @Override + public InterceptorType type() { + return InterceptorType.REPORT; + } + + @Override + public void begin(ClassTree clazz) { + this.currentClass = clazz.name(); + final String[] classLocation = ("export." + clazz.name().asJavaName()) + .split("\\."); + final Path classDir = this.fileSystem.getPath(this.outDir, classLocation); + this.mutantsDir = classDir.resolve("mutants"); + try { + Files.createDirectories(this.mutantsDir); + writeBytecodeToDisk(this.source.getBytes(clazz.name().asJavaName()).get(), classDir); + } catch (final IOException e) { + throw new RuntimeException("Couldn't create direectory for " + clazz, e); + } + } + + @Override + public Collection intercept( + Collection mutations, Mutater m) { + + final List indexable = new ArrayList<>(mutations); + + try { + for (int i = 0; i != indexable.size(); i++) { + exportMutantDetails(m, indexable, i); + } + } catch (final IOException ex) { + throw new RuntimeException("Error exporting mutants for report", ex); + } + + return mutations; + } + + private void exportMutantDetails(Mutater m, List indexable, + int i) throws IOException { + final MutationDetails md = indexable.get(i); + final Path mutantFolder = this.mutantsDir.resolve("" + i); + Files.createDirectories(mutantFolder); + + final Mutant mutant = m.getMutation(md.getId()); + + writeMutantToDisk(mutant, mutantFolder); + writeBytecodeToDisk(mutant.getBytes(), mutantFolder); + writeDetailsToDisk(md, mutantFolder); + } + + private void writeMutantToDisk(Mutant mutant, Path mutantFolder) throws IOException { + final Path outFile = mutantFolder.resolve(this.currentClass.asJavaName() + ".class"); + Files.write(outFile, mutant.getBytes(), StandardOpenOption.CREATE); + } + + + private void writeBytecodeToDisk(final byte[] clazz, Path folder) throws IOException { + final ClassReader reader = new ClassReader(clazz); + final CharArrayWriter buffer = new CharArrayWriter(); + reader.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter( + buffer)), ClassReader.EXPAND_FRAMES); + final Path outFile = folder.resolve(this.currentClass.asJavaName() + ".txt"); + Files.write(outFile, Collections.singleton(buffer.toString()), StandardCharsets.UTF_8, StandardOpenOption.CREATE); + } + + private void writeDetailsToDisk(MutationDetails md, + Path mutantFolder) throws IOException { + final Path outFile = mutantFolder.resolve("details.txt"); + Files.write(outFile, Collections.singleton(md.toString()), StandardCharsets.UTF_8, StandardOpenOption.CREATE); + } + + @Override + public void end() { + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/process/DefaultJavaExecutableLocator.java b/pitest-entry/src/main/java/org/pitest/process/DefaultJavaExecutableLocator.java index 3c673ed48..a8f834d56 100644 --- a/pitest-entry/src/main/java/org/pitest/process/DefaultJavaExecutableLocator.java +++ b/pitest-entry/src/main/java/org/pitest/process/DefaultJavaExecutableLocator.java @@ -1,15 +1,15 @@ -package org.pitest.process; - -/** - * Returns the java binary from JAVA_HOME - */ -public class DefaultJavaExecutableLocator implements JavaExecutableLocator { - - @Override - public String javaExecutable() { - final String separator = System.getProperty("file.separator"); - return System.getProperty("java.home") + separator + "bin" + separator - + "java"; - } - -} +package org.pitest.process; + +/** + * Returns the java binary from JAVA_HOME + */ +public class DefaultJavaExecutableLocator implements JavaExecutableLocator { + + @Override + public String javaExecutable() { + final String separator = System.getProperty("file.separator"); + return System.getProperty("java.home") + separator + "bin" + separator + + "java"; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/process/JavaAgent.java b/pitest-entry/src/main/java/org/pitest/process/JavaAgent.java index 4846cb654..b2ef20a51 100644 --- a/pitest-entry/src/main/java/org/pitest/process/JavaAgent.java +++ b/pitest-entry/src/main/java/org/pitest/process/JavaAgent.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.process; - -import java.util.Optional; - -public interface JavaAgent { - - Optional getJarLocation(); - - void close(); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.process; + +import java.util.Optional; + +public interface JavaAgent { + + Optional getJarLocation(); + + void close(); + +} diff --git a/pitest-entry/src/main/java/org/pitest/process/JavaExecutableLocator.java b/pitest-entry/src/main/java/org/pitest/process/JavaExecutableLocator.java index 7925061b7..bde7b4d75 100644 --- a/pitest-entry/src/main/java/org/pitest/process/JavaExecutableLocator.java +++ b/pitest-entry/src/main/java/org/pitest/process/JavaExecutableLocator.java @@ -1,8 +1,8 @@ -package org.pitest.process; - -/** - * Returns the path to a java binary - */ -public interface JavaExecutableLocator { - String javaExecutable(); -} +package org.pitest.process; + +/** + * Returns the path to a java binary + */ +public interface JavaExecutableLocator { + String javaExecutable(); +} diff --git a/pitest-entry/src/main/java/org/pitest/process/KnownLocationJavaExecutableLocator.java b/pitest-entry/src/main/java/org/pitest/process/KnownLocationJavaExecutableLocator.java index c24a95ebb..53103280f 100644 --- a/pitest-entry/src/main/java/org/pitest/process/KnownLocationJavaExecutableLocator.java +++ b/pitest-entry/src/main/java/org/pitest/process/KnownLocationJavaExecutableLocator.java @@ -1,17 +1,17 @@ -package org.pitest.process; - -public class KnownLocationJavaExecutableLocator implements -JavaExecutableLocator { - - private final String location; - - public KnownLocationJavaExecutableLocator(final String location) { - this.location = location; - } - - @Override - public String javaExecutable() { - return this.location; - } - -} +package org.pitest.process; + +public class KnownLocationJavaExecutableLocator implements +JavaExecutableLocator { + + private final String location; + + public KnownLocationJavaExecutableLocator(final String location) { + this.location = location; + } + + @Override + public String javaExecutable() { + return this.location; + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/process/LaunchOptions.java b/pitest-entry/src/main/java/org/pitest/process/LaunchOptions.java index 155f44123..c73a0683e 100644 --- a/pitest-entry/src/main/java/org/pitest/process/LaunchOptions.java +++ b/pitest-entry/src/main/java/org/pitest/process/LaunchOptions.java @@ -1,58 +1,58 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.process; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class LaunchOptions { - - private final JavaAgent javaAgentFinder; - private final List childJVMArgs; - private final JavaExecutableLocator javaExecutable; - private final Map environmentVariables; - - public LaunchOptions(JavaAgent javaAgentFinder) { - this(javaAgentFinder, new DefaultJavaExecutableLocator(), Collections - . emptyList(), new HashMap()); - } - - public LaunchOptions(JavaAgent javaAgentFinder, - JavaExecutableLocator javaExecutable, List childJVMArgs, - Map environmentVariables) { - this.javaAgentFinder = javaAgentFinder; - this.childJVMArgs = childJVMArgs; - this.javaExecutable = javaExecutable; - this.environmentVariables = environmentVariables; - } - - public JavaAgent getJavaAgentFinder() { - return this.javaAgentFinder; - } - - public List getChildJVMArgs() { - return this.childJVMArgs; - } - - public String getJavaExecutable() { - return this.javaExecutable.javaExecutable(); - } - - public Map getEnvironmentVariables() { - return this.environmentVariables; - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.process; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class LaunchOptions { + + private final JavaAgent javaAgentFinder; + private final List childJVMArgs; + private final JavaExecutableLocator javaExecutable; + private final Map environmentVariables; + + public LaunchOptions(JavaAgent javaAgentFinder) { + this(javaAgentFinder, new DefaultJavaExecutableLocator(), Collections + . emptyList(), new HashMap()); + } + + public LaunchOptions(JavaAgent javaAgentFinder, + JavaExecutableLocator javaExecutable, List childJVMArgs, + Map environmentVariables) { + this.javaAgentFinder = javaAgentFinder; + this.childJVMArgs = childJVMArgs; + this.javaExecutable = javaExecutable; + this.environmentVariables = environmentVariables; + } + + public JavaAgent getJavaAgentFinder() { + return this.javaAgentFinder; + } + + public List getChildJVMArgs() { + return this.childJVMArgs; + } + + public String getJavaExecutable() { + return this.javaExecutable.javaExecutable(); + } + + public Map getEnvironmentVariables() { + return this.environmentVariables; + } +} diff --git a/pitest-entry/src/main/java/org/pitest/process/ProcessArgs.java b/pitest-entry/src/main/java/org/pitest/process/ProcessArgs.java index 30f284800..d83f482c1 100644 --- a/pitest-entry/src/main/java/org/pitest/process/ProcessArgs.java +++ b/pitest-entry/src/main/java/org/pitest/process/ProcessArgs.java @@ -1,117 +1,117 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.process; - -import static org.pitest.functional.prelude.Prelude.print; -import static org.pitest.functional.prelude.Prelude.printTo; - -import java.io.File; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.pitest.classpath.ClassPath; -import org.pitest.functional.SideEffect1; - -public final class ProcessArgs { - - private final String launchClassPath; - private SideEffect1 stdout = print(String.class); - private SideEffect1 stdErr = printTo(String.class, System.err); - private List jvmArgs = Collections.emptyList(); - private JavaAgent javaAgentFinder; - private File workingDir = null; - private String javaExecutable; - private Map environmentVariables; - - private ProcessArgs(final String launchClassPath) { - this.launchClassPath = launchClassPath; - } - - public static ProcessArgs withClassPath(final String cp) { - return new ProcessArgs(cp); - } - - public static ProcessArgs withClassPath(final ClassPath cp) { - return new ProcessArgs(cp.getLocalClassPath()); - } - - public ProcessArgs andBaseDir(final File baseDir) { - this.workingDir = baseDir; - return this; - } - - public ProcessArgs andStdout(final SideEffect1 stdout) { - this.stdout = stdout; - return this; - } - - public ProcessArgs andStderr(final SideEffect1 stderr) { - this.stdErr = stderr; - return this; - } - - public String getLaunchClassPath() { - return this.launchClassPath; - } - - public SideEffect1 getStdout() { - return this.stdout; - } - - public SideEffect1 getStdErr() { - return this.stdErr; - } - - public List getJvmArgs() { - return this.jvmArgs; - } - - public JavaAgent getJavaAgentFinder() { - return this.javaAgentFinder; - } - - public void setStdout(final SideEffect1 stdout) { - this.stdout = stdout; - } - - public void setStdErr(final SideEffect1 stdErr) { - this.stdErr = stdErr; - } - - public void setJvmArgs(final List jvmArgs) { - this.jvmArgs = jvmArgs; - } - - public File getWorkingDir() { - return this.workingDir; - } - - public String getJavaExecutable() { - return this.javaExecutable; - } - - public ProcessArgs andLaunchOptions(final LaunchOptions launchOptions) { - this.jvmArgs = launchOptions.getChildJVMArgs(); - this.javaAgentFinder = launchOptions.getJavaAgentFinder(); - this.javaExecutable = launchOptions.getJavaExecutable(); - this.environmentVariables = launchOptions.getEnvironmentVariables(); - return this; - } - - public Map getEnvironmentVariables() { - return this.environmentVariables; - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.process; + +import static org.pitest.functional.prelude.Prelude.print; +import static org.pitest.functional.prelude.Prelude.printTo; + +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.pitest.classpath.ClassPath; +import org.pitest.functional.SideEffect1; + +public final class ProcessArgs { + + private final String launchClassPath; + private SideEffect1 stdout = print(String.class); + private SideEffect1 stdErr = printTo(String.class, System.err); + private List jvmArgs = Collections.emptyList(); + private JavaAgent javaAgentFinder; + private File workingDir = null; + private String javaExecutable; + private Map environmentVariables; + + private ProcessArgs(final String launchClassPath) { + this.launchClassPath = launchClassPath; + } + + public static ProcessArgs withClassPath(final String cp) { + return new ProcessArgs(cp); + } + + public static ProcessArgs withClassPath(final ClassPath cp) { + return new ProcessArgs(cp.getLocalClassPath()); + } + + public ProcessArgs andBaseDir(final File baseDir) { + this.workingDir = baseDir; + return this; + } + + public ProcessArgs andStdout(final SideEffect1 stdout) { + this.stdout = stdout; + return this; + } + + public ProcessArgs andStderr(final SideEffect1 stderr) { + this.stdErr = stderr; + return this; + } + + public String getLaunchClassPath() { + return this.launchClassPath; + } + + public SideEffect1 getStdout() { + return this.stdout; + } + + public SideEffect1 getStdErr() { + return this.stdErr; + } + + public List getJvmArgs() { + return this.jvmArgs; + } + + public JavaAgent getJavaAgentFinder() { + return this.javaAgentFinder; + } + + public void setStdout(final SideEffect1 stdout) { + this.stdout = stdout; + } + + public void setStdErr(final SideEffect1 stdErr) { + this.stdErr = stdErr; + } + + public void setJvmArgs(final List jvmArgs) { + this.jvmArgs = jvmArgs; + } + + public File getWorkingDir() { + return this.workingDir; + } + + public String getJavaExecutable() { + return this.javaExecutable; + } + + public ProcessArgs andLaunchOptions(final LaunchOptions launchOptions) { + this.jvmArgs = launchOptions.getChildJVMArgs(); + this.javaAgentFinder = launchOptions.getJavaAgentFinder(); + this.javaExecutable = launchOptions.getJavaExecutable(); + this.environmentVariables = launchOptions.getEnvironmentVariables(); + return this; + } + + public Map getEnvironmentVariables() { + return this.environmentVariables; + } +} diff --git a/pitest-entry/src/main/java/org/pitest/process/WrappingProcess.java b/pitest-entry/src/main/java/org/pitest/process/WrappingProcess.java index 744a63bb6..31c2c20c7 100644 --- a/pitest-entry/src/main/java/org/pitest/process/WrappingProcess.java +++ b/pitest-entry/src/main/java/org/pitest/process/WrappingProcess.java @@ -1,125 +1,125 @@ -package org.pitest.process; - -import static org.pitest.functional.prelude.Prelude.or; - -import java.io.File; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Predicate; - -import org.pitest.functional.FCollection; - -public class WrappingProcess { - - private final int port; - private final ProcessArgs processArgs; - private final Class minionClass; - - private JavaProcess process; - - public WrappingProcess(int port, ProcessArgs args, Class minionClass) { - this.port = port; - this.processArgs = args; - this.minionClass = minionClass; - } - - public void start() throws IOException { - final String[] args = { "" + this.port }; - - final ProcessBuilder processBuilder = createProcessBuilder( - this.processArgs.getJavaExecutable(), this.processArgs.getJvmArgs(), - this.minionClass, Arrays.asList(args), - this.processArgs.getJavaAgentFinder()); - - configureProcessBuilder(processBuilder, this.processArgs.getWorkingDir(), - this.processArgs.getLaunchClassPath(), - this.processArgs.getEnvironmentVariables()); - - final Process process = processBuilder.start(); - this.process = new JavaProcess(process, this.processArgs.getStdout(), - this.processArgs.getStdErr()); - } - - private void configureProcessBuilder(ProcessBuilder processBuilder, - File workingDirectory, String initialClassPath, - Map environmentVariables) { - processBuilder.directory(workingDirectory); - final Map environment = processBuilder.environment(); - environment.put("CLASSPATH", initialClassPath); - - for (final Map.Entry entry : environmentVariables.entrySet()) { - environment.put(entry.getKey(), entry.getValue()); - } - } - - public void destroy() { - this.process.destroy(); - } - - private static ProcessBuilder createProcessBuilder(String javaProc, - List args, Class mainClass, List programArgs, - JavaAgent javaAgent) { - final List cmd = createLaunchArgs(javaProc, javaAgent, args, mainClass, - programArgs); - - // IBM jdk adds this, thereby breaking everything - removeClassPathProperties(cmd); - - return new ProcessBuilder(cmd); - } - - private static void removeClassPathProperties(List cmd) { - for (int i = cmd.size() - 1; i >= 0; i--) { - if (cmd.get(i).startsWith("-Djava.class.path")) { - cmd.remove(i); - } - } - } - - private static List createLaunchArgs(String javaProcess, - JavaAgent agentJarLocator, List args, Class mainClass, - List programArgs) { - - final List cmd = new ArrayList<>(); - cmd.add(javaProcess); - cmd.addAll(args); - - addPITJavaAgent(agentJarLocator, cmd); - addLaunchJavaAgents(cmd); - - cmd.add(mainClass.getName()); - cmd.addAll(programArgs); - return cmd; - } - - private static void addPITJavaAgent(JavaAgent agentJarLocator, - List cmd) { - final Optional jarLocation = agentJarLocator.getJarLocation(); - jarLocation.ifPresent(l -> cmd.add("-javaagent:" + l)); - } - - private static void addLaunchJavaAgents(List cmd) { - final RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean(); - final List agents = FCollection.filter(rt.getInputArguments(), - or(isJavaAgentParam(), isEnvironmentSetting())); - cmd.addAll(agents); - } - - private static Predicate isEnvironmentSetting() { - return a -> a.startsWith("-D"); - } - - private static Predicate isJavaAgentParam() { - return a -> a.toLowerCase().startsWith("-javaagent"); - } - - public JavaProcess getProcess() { - return this.process; - } -} +package org.pitest.process; + +import static org.pitest.functional.prelude.Prelude.or; + +import java.io.File; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; + +import org.pitest.functional.FCollection; + +public class WrappingProcess { + + private final int port; + private final ProcessArgs processArgs; + private final Class minionClass; + + private JavaProcess process; + + public WrappingProcess(int port, ProcessArgs args, Class minionClass) { + this.port = port; + this.processArgs = args; + this.minionClass = minionClass; + } + + public void start() throws IOException { + final String[] args = { "" + this.port }; + + final ProcessBuilder processBuilder = createProcessBuilder( + this.processArgs.getJavaExecutable(), this.processArgs.getJvmArgs(), + this.minionClass, Arrays.asList(args), + this.processArgs.getJavaAgentFinder()); + + configureProcessBuilder(processBuilder, this.processArgs.getWorkingDir(), + this.processArgs.getLaunchClassPath(), + this.processArgs.getEnvironmentVariables()); + + final Process process = processBuilder.start(); + this.process = new JavaProcess(process, this.processArgs.getStdout(), + this.processArgs.getStdErr()); + } + + private void configureProcessBuilder(ProcessBuilder processBuilder, + File workingDirectory, String initialClassPath, + Map environmentVariables) { + processBuilder.directory(workingDirectory); + final Map environment = processBuilder.environment(); + environment.put("CLASSPATH", initialClassPath); + + for (final Map.Entry entry : environmentVariables.entrySet()) { + environment.put(entry.getKey(), entry.getValue()); + } + } + + public void destroy() { + this.process.destroy(); + } + + private static ProcessBuilder createProcessBuilder(String javaProc, + List args, Class mainClass, List programArgs, + JavaAgent javaAgent) { + final List cmd = createLaunchArgs(javaProc, javaAgent, args, mainClass, + programArgs); + + // IBM jdk adds this, thereby breaking everything + removeClassPathProperties(cmd); + + return new ProcessBuilder(cmd); + } + + private static void removeClassPathProperties(List cmd) { + for (int i = cmd.size() - 1; i >= 0; i--) { + if (cmd.get(i).startsWith("-Djava.class.path")) { + cmd.remove(i); + } + } + } + + private static List createLaunchArgs(String javaProcess, + JavaAgent agentJarLocator, List args, Class mainClass, + List programArgs) { + + final List cmd = new ArrayList<>(); + cmd.add(javaProcess); + cmd.addAll(args); + + addPITJavaAgent(agentJarLocator, cmd); + addLaunchJavaAgents(cmd); + + cmd.add(mainClass.getName()); + cmd.addAll(programArgs); + return cmd; + } + + private static void addPITJavaAgent(JavaAgent agentJarLocator, + List cmd) { + final Optional jarLocation = agentJarLocator.getJarLocation(); + jarLocation.ifPresent(l -> cmd.add("-javaagent:" + l)); + } + + private static void addLaunchJavaAgents(List cmd) { + final RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean(); + final List agents = FCollection.filter(rt.getInputArguments(), + or(isJavaAgentParam(), isEnvironmentSetting())); + cmd.addAll(agents); + } + + private static Predicate isEnvironmentSetting() { + return a -> a.startsWith("-D"); + } + + private static Predicate isJavaAgentParam() { + return a -> a.toLowerCase().startsWith("-javaagent"); + } + + public JavaProcess getProcess() { + return this.process; + } +} diff --git a/pitest-entry/src/main/java/org/pitest/util/CommunicationThread.java b/pitest-entry/src/main/java/org/pitest/util/CommunicationThread.java index bffd859de..7bccae13d 100644 --- a/pitest-entry/src/main/java/org/pitest/util/CommunicationThread.java +++ b/pitest-entry/src/main/java/org/pitest/util/CommunicationThread.java @@ -1,71 +1,71 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import java.io.IOException; -import java.net.ServerSocket; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.FutureTask; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.pitest.functional.SideEffect1; - -public class CommunicationThread { - - private static final Logger LOG = Log.getLogger(); - - private final SideEffect1 sendInitialData; - private final ReceiveStrategy receive; - private final ServerSocket socket; - private FutureTask future; - - public CommunicationThread(final ServerSocket socket, - final SideEffect1 sendInitialData, - final ReceiveStrategy receive) { - this.socket = socket; - this.sendInitialData = sendInitialData; - this.receive = receive; - } - - public void start() throws IOException, InterruptedException { - this.future = createFuture(); - } - - private FutureTask createFuture() { - final FutureTask newFuture = new FutureTask<>( - new SocketReadingCallable(this.socket, this.sendInitialData, - this.receive)); - final Thread thread = new Thread(newFuture); - thread.setDaemon(true); - thread.setName("pit communication"); - thread.start(); - return newFuture; - } - - public ExitCode waitToFinish() { - try { - return this.future.get(); - } catch (final ExecutionException e) { - LOG.log(Level.WARNING, "Error while watching child process", e); - return ExitCode.UNKNOWN_ERROR; - } catch (final InterruptedException e) { - LOG.log(Level.WARNING, "interrupted while waiting for child process", e); - return ExitCode.UNKNOWN_ERROR; - } - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.pitest.functional.SideEffect1; + +public class CommunicationThread { + + private static final Logger LOG = Log.getLogger(); + + private final SideEffect1 sendInitialData; + private final ReceiveStrategy receive; + private final ServerSocket socket; + private FutureTask future; + + public CommunicationThread(final ServerSocket socket, + final SideEffect1 sendInitialData, + final ReceiveStrategy receive) { + this.socket = socket; + this.sendInitialData = sendInitialData; + this.receive = receive; + } + + public void start() throws IOException, InterruptedException { + this.future = createFuture(); + } + + private FutureTask createFuture() { + final FutureTask newFuture = new FutureTask<>( + new SocketReadingCallable(this.socket, this.sendInitialData, + this.receive)); + final Thread thread = new Thread(newFuture); + thread.setDaemon(true); + thread.setName("pit communication"); + thread.start(); + return newFuture; + } + + public ExitCode waitToFinish() { + try { + return this.future.get(); + } catch (final ExecutionException e) { + LOG.log(Level.WARNING, "Error while watching child process", e); + return ExitCode.UNKNOWN_ERROR; + } catch (final InterruptedException e) { + LOG.log(Level.WARNING, "interrupted while waiting for child process", e); + return ExitCode.UNKNOWN_ERROR; + } + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/util/FileUtil.java b/pitest-entry/src/main/java/org/pitest/util/FileUtil.java index 3b252dfc8..f89cac2b2 100644 --- a/pitest-entry/src/main/java/org/pitest/util/FileUtil.java +++ b/pitest-entry/src/main/java/org/pitest/util/FileUtil.java @@ -1,30 +1,30 @@ -package org.pitest.util; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; - -public class FileUtil { - - public static String readToString(final InputStream is) - throws java.io.IOException { - final StringBuilder fileData = new StringBuilder(1000); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { - char[] buf = new char[1024]; - int numRead = 0; - - while ((numRead = reader.read(buf)) != -1) { - final String readData = String.valueOf(buf, 0, numRead); - fileData.append(readData); - buf = new char[1024]; - } - return fileData.toString(); - } - } - - public static String randomFilename() { - return System.currentTimeMillis() - + ("" + Math.random()).replaceAll("\\.", ""); - } - -} +package org.pitest.util; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class FileUtil { + + public static String readToString(final InputStream is) + throws java.io.IOException { + final StringBuilder fileData = new StringBuilder(1000); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { + char[] buf = new char[1024]; + int numRead = 0; + + while ((numRead = reader.read(buf)) != -1) { + final String readData = String.valueOf(buf, 0, numRead); + fileData.append(readData); + buf = new char[1024]; + } + return fileData.toString(); + } + } + + public static String randomFilename() { + return System.currentTimeMillis() + + ("" + Math.random()).replaceAll("\\.", ""); + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/util/Monitor.java b/pitest-entry/src/main/java/org/pitest/util/Monitor.java index 5939f1895..ac89ac204 100644 --- a/pitest-entry/src/main/java/org/pitest/util/Monitor.java +++ b/pitest-entry/src/main/java/org/pitest/util/Monitor.java @@ -1,9 +1,9 @@ -package org.pitest.util; - -public interface Monitor { - - void requestStop(); - - void requestStart(); - +package org.pitest.util; + +public interface Monitor { + + void requestStop(); + + void requestStart(); + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/util/ResultOutputStrategy.java b/pitest-entry/src/main/java/org/pitest/util/ResultOutputStrategy.java index e4b7183d6..d75cc1907 100644 --- a/pitest-entry/src/main/java/org/pitest/util/ResultOutputStrategy.java +++ b/pitest-entry/src/main/java/org/pitest/util/ResultOutputStrategy.java @@ -1,23 +1,23 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import java.io.Writer; - -public interface ResultOutputStrategy { - - Writer createWriterForFile(String sourceFile); - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import java.io.Writer; + +public interface ResultOutputStrategy { + + Writer createWriterForFile(String sourceFile); + +} diff --git a/pitest-entry/src/main/java/org/pitest/util/SocketFinder.java b/pitest-entry/src/main/java/org/pitest/util/SocketFinder.java index 33f0e132e..e8489b821 100644 --- a/pitest-entry/src/main/java/org/pitest/util/SocketFinder.java +++ b/pitest-entry/src/main/java/org/pitest/util/SocketFinder.java @@ -1,30 +1,30 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import java.io.IOException; -import java.net.ServerSocket; - -public class SocketFinder { - - public synchronized ServerSocket getNextAvailableServerSocket() { - try { - return new ServerSocket(0); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import java.io.IOException; +import java.net.ServerSocket; + +public class SocketFinder { + + public synchronized ServerSocket getNextAvailableServerSocket() { + try { + return new ServerSocket(0); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/util/SocketReadingCallable.java b/pitest-entry/src/main/java/org/pitest/util/SocketReadingCallable.java index 4c0d375f2..39fa857de 100644 --- a/pitest-entry/src/main/java/org/pitest/util/SocketReadingCallable.java +++ b/pitest-entry/src/main/java/org/pitest/util/SocketReadingCallable.java @@ -1,64 +1,64 @@ -package org.pitest.util; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.concurrent.Callable; - -import org.pitest.functional.SideEffect1; - -class SocketReadingCallable implements Callable { - - private final SideEffect1 sendInitialData; - private final ReceiveStrategy receive; - private final ServerSocket socket; - - SocketReadingCallable(final ServerSocket socket, - final SideEffect1 sendInitialData, - final ReceiveStrategy receive) { - this.socket = socket; - this.sendInitialData = sendInitialData; - this.receive = receive; - } - - @Override - public ExitCode call() throws Exception { - try (Socket clientSocket = this.socket.accept()) { - try (BufferedInputStream bif = new BufferedInputStream( - clientSocket.getInputStream())) { - - sendDataToMinion(clientSocket); - - final SafeDataInputStream is = new SafeDataInputStream(bif); - return receiveResults(is); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } finally { - try { - this.socket.close(); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - } - - private void sendDataToMinion(final Socket clientSocket) throws IOException { - final OutputStream os = clientSocket.getOutputStream(); - final SafeDataOutputStream dos = new SafeDataOutputStream(os); - this.sendInitialData.apply(dos); - } - - private ExitCode receiveResults(final SafeDataInputStream is) { - byte control = is.readByte(); - while (control != Id.DONE) { - this.receive.apply(control, is); - control = is.readByte(); - } - return ExitCode.fromCode(is.readInt()); - - } - +package org.pitest.util; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.Callable; + +import org.pitest.functional.SideEffect1; + +class SocketReadingCallable implements Callable { + + private final SideEffect1 sendInitialData; + private final ReceiveStrategy receive; + private final ServerSocket socket; + + SocketReadingCallable(final ServerSocket socket, + final SideEffect1 sendInitialData, + final ReceiveStrategy receive) { + this.socket = socket; + this.sendInitialData = sendInitialData; + this.receive = receive; + } + + @Override + public ExitCode call() throws Exception { + try (Socket clientSocket = this.socket.accept()) { + try (BufferedInputStream bif = new BufferedInputStream( + clientSocket.getInputStream())) { + + sendDataToMinion(clientSocket); + + final SafeDataInputStream is = new SafeDataInputStream(bif); + return receiveResults(is); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } finally { + try { + this.socket.close(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + } + + private void sendDataToMinion(final Socket clientSocket) throws IOException { + final OutputStream os = clientSocket.getOutputStream(); + final SafeDataOutputStream dos = new SafeDataOutputStream(os); + this.sendInitialData.apply(dos); + } + + private ExitCode receiveResults(final SafeDataInputStream is) { + byte control = is.readByte(); + while (control != Id.DONE) { + this.receive.apply(control, is); + control = is.readByte(); + } + return ExitCode.fromCode(is.readInt()); + + } + } \ No newline at end of file diff --git a/pitest-entry/src/main/java/org/pitest/util/TimeSpan.java b/pitest-entry/src/main/java/org/pitest/util/TimeSpan.java index 7b2e501ae..7d342cfcd 100644 --- a/pitest-entry/src/main/java/org/pitest/util/TimeSpan.java +++ b/pitest-entry/src/main/java/org/pitest/util/TimeSpan.java @@ -1,71 +1,71 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -public class TimeSpan { - - private long start; - private long end; - - public TimeSpan(final long start, final long end) { - this.start = start; - this.end = end; - } - - public long duration() { - return this.end - this.start; - } - - public long getStart() { - return this.start; - } - - public long getEnd() { - return this.end; - } - - public void setStart(final long start) { - this.start = start; - } - - public void setEnd(final long end) { - this.end = end; - } - - @Override - public String toString() { - final long millis = duration(); - final int seconds = (int) (millis / 1000) % 60; - final int minutes = (int) ((millis / (1000 * 60)) % 60); - final int hours = (int) ((millis / (1000 * 60 * 60)) % 24); - - if (hours != 0) { - return "" + hours + " hours, " + minutes + " minutes and " + seconds - + " seconds"; - } - - if (minutes != 0) { - return "" + minutes + " minutes and " + seconds + " seconds"; - } - - if (seconds != 0) { - return "" + seconds + " seconds"; - } - - return "< 1 second"; - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +public class TimeSpan { + + private long start; + private long end; + + public TimeSpan(final long start, final long end) { + this.start = start; + this.end = end; + } + + public long duration() { + return this.end - this.start; + } + + public long getStart() { + return this.start; + } + + public long getEnd() { + return this.end; + } + + public void setStart(final long start) { + this.start = start; + } + + public void setEnd(final long end) { + this.end = end; + } + + @Override + public String toString() { + final long millis = duration(); + final int seconds = (int) (millis / 1000) % 60; + final int minutes = (int) ((millis / (1000 * 60)) % 60); + final int hours = (int) ((millis / (1000 * 60 * 60)) % 24); + + if (hours != 0) { + return "" + hours + " hours, " + minutes + " minutes and " + seconds + + " seconds"; + } + + if (minutes != 0) { + return "" + minutes + " minutes and " + seconds + " seconds"; + } + + if (seconds != 0) { + return "" + seconds + " seconds"; + } + + return "< 1 second"; + + } + +} diff --git a/pitest-entry/src/main/java/org/pitest/util/Timings.java b/pitest-entry/src/main/java/org/pitest/util/Timings.java index 531947cd1..2f70c3963 100644 --- a/pitest-entry/src/main/java/org/pitest/util/Timings.java +++ b/pitest-entry/src/main/java/org/pitest/util/Timings.java @@ -1,63 +1,63 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import java.io.PrintStream; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class Timings { - - public enum Stage { - BUILD_MUTATION_TESTS("build mutation tests"), RUN_MUTATION_TESTS( - "run mutation analysis"), SCAN_CLASS_PATH("scan classpath"), COVERAGE( - "coverage and dependency analysis"); - - private final String description; - - Stage(final String desc) { - this.description = desc; - } - - @Override - public String toString() { - return this.description; - } - } - - private final Map timings = new LinkedHashMap<>(); - - public void registerStart(final Stage stage) { - this.timings.put(stage, new TimeSpan(System.currentTimeMillis(), 0)); - } - - public void registerEnd(final Stage stage) { - final long end = System.currentTimeMillis(); - this.timings.get(stage).setEnd(end); - } - - public void report(final PrintStream ps) { - long total = 0; - for (final Entry each : this.timings.entrySet()) { - total = total + each.getValue().duration(); - ps.println("> " + each.getKey() + " : " + each.getValue()); - } - ps.println(StringUtil.separatorLine()); - ps.println("> Total " + " : " + new TimeSpan(0, total)); - ps.println(StringUtil.separatorLine()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import java.io.PrintStream; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + +public class Timings { + + public enum Stage { + BUILD_MUTATION_TESTS("build mutation tests"), RUN_MUTATION_TESTS( + "run mutation analysis"), SCAN_CLASS_PATH("scan classpath"), COVERAGE( + "coverage and dependency analysis"); + + private final String description; + + Stage(final String desc) { + this.description = desc; + } + + @Override + public String toString() { + return this.description; + } + } + + private final Map timings = new LinkedHashMap<>(); + + public void registerStart(final Stage stage) { + this.timings.put(stage, new TimeSpan(System.currentTimeMillis(), 0)); + } + + public void registerEnd(final Stage stage) { + final long end = System.currentTimeMillis(); + this.timings.get(stage).setEnd(end); + } + + public void report(final PrintStream ps) { + long total = 0; + for (final Entry each : this.timings.entrySet()) { + total = total + each.getValue().duration(); + ps.println("> " + each.getKey() + " : " + each.getValue()); + } + ps.println(StringUtil.separatorLine()); + ps.println("> Total " + " : " + new TimeSpan(0, total)); + ps.println(StringUtil.separatorLine()); + } + +} diff --git a/pitest-entry/src/main/resources/META-INF/services/org.pitest.mutationtest.MutationResultListenerFactory b/pitest-entry/src/main/resources/META-INF/services/org.pitest.mutationtest.MutationResultListenerFactory index 1aa1f9f0f..9f548b122 100644 --- a/pitest-entry/src/main/resources/META-INF/services/org.pitest.mutationtest.MutationResultListenerFactory +++ b/pitest-entry/src/main/resources/META-INF/services/org.pitest.mutationtest.MutationResultListenerFactory @@ -1,2 +1,2 @@ -org.pitest.mutationtest.report.csv.CSVReportFactory +org.pitest.mutationtest.report.csv.CSVReportFactory org.pitest.mutationtest.report.xml.XMLReportFactory \ No newline at end of file diff --git a/pitest-entry/src/main/resources/META-INF/services/org.pitest.mutationtest.build.MutationInterceptorFactory b/pitest-entry/src/main/resources/META-INF/services/org.pitest.mutationtest.build.MutationInterceptorFactory index 54c0faedb..52f1e82e0 100644 --- a/pitest-entry/src/main/resources/META-INF/services/org.pitest.mutationtest.build.MutationInterceptorFactory +++ b/pitest-entry/src/main/resources/META-INF/services/org.pitest.mutationtest.build.MutationInterceptorFactory @@ -1,19 +1,19 @@ -# Interceptor factories. If you add an entry here you probably should have a test case in MutationDiscoveryTest - -org.pitest.mutationtest.build.intercept.staticinitializers.StaticInitializerInterceptorFactory -org.pitest.mutationtest.build.intercept.staticinitializers.StaticInitializerFilterFactory -org.pitest.mutationtest.build.intercept.annotations.ExcludedAnnotationInterceptorFactory -org.pitest.mutationtest.build.intercept.javafeatures.InlinedFinallyBlockFilterFactory -org.pitest.mutationtest.build.intercept.javafeatures.TryWithResourcesFilterFactory -org.pitest.mutationtest.build.intercept.javafeatures.ImplicitNullCheckFilterFactory -org.pitest.mutationtest.build.intercept.javafeatures.ForEachLoopFilterFactory -org.pitest.mutationtest.build.intercept.logging.LoggingCallsFilterFactory -org.pitest.mutationtest.build.intercept.timeout.InfiniteForLoopFilterFactory -org.pitest.mutationtest.build.intercept.timeout.InfiniteIteratorLoopFilterFactory -org.pitest.mutationtest.build.intercept.timeout.AvoidForLoopCountersFilterFactory -org.pitest.mutationtest.build.intercept.kotlin.KotlinFilterFactory -org.pitest.mutationtest.filter.LimitNumberOfMutationsPerClassFilterFactory -org.pitest.mutationtest.build.intercept.equivalent.EqualsPerformanceShortcutFilterFactory -org.pitest.mutationtest.build.intercept.equivalent.EquivalentReturnMutationFilter - +# Interceptor factories. If you add an entry here you probably should have a test case in MutationDiscoveryTest + +org.pitest.mutationtest.build.intercept.staticinitializers.StaticInitializerInterceptorFactory +org.pitest.mutationtest.build.intercept.staticinitializers.StaticInitializerFilterFactory +org.pitest.mutationtest.build.intercept.annotations.ExcludedAnnotationInterceptorFactory +org.pitest.mutationtest.build.intercept.javafeatures.InlinedFinallyBlockFilterFactory +org.pitest.mutationtest.build.intercept.javafeatures.TryWithResourcesFilterFactory +org.pitest.mutationtest.build.intercept.javafeatures.ImplicitNullCheckFilterFactory +org.pitest.mutationtest.build.intercept.javafeatures.ForEachLoopFilterFactory +org.pitest.mutationtest.build.intercept.logging.LoggingCallsFilterFactory +org.pitest.mutationtest.build.intercept.timeout.InfiniteForLoopFilterFactory +org.pitest.mutationtest.build.intercept.timeout.InfiniteIteratorLoopFilterFactory +org.pitest.mutationtest.build.intercept.timeout.AvoidForLoopCountersFilterFactory +org.pitest.mutationtest.build.intercept.kotlin.KotlinFilterFactory +org.pitest.mutationtest.filter.LimitNumberOfMutationsPerClassFilterFactory +org.pitest.mutationtest.build.intercept.equivalent.EqualsPerformanceShortcutFilterFactory +org.pitest.mutationtest.build.intercept.equivalent.EquivalentReturnMutationFilter + org.pitest.plugin.export.MutantExportFactory \ No newline at end of file diff --git a/pitest-entry/src/test/java/com/example/CoveredButOnlyPartiallyTested.java b/pitest-entry/src/test/java/com/example/CoveredButOnlyPartiallyTested.java index b2fc5a578..f686f79df 100644 --- a/pitest-entry/src/test/java/com/example/CoveredButOnlyPartiallyTested.java +++ b/pitest-entry/src/test/java/com/example/CoveredButOnlyPartiallyTested.java @@ -1,28 +1,28 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package com.example; - -public class CoveredButOnlyPartiallyTested { - - public int coverMe() { - return 1; - } - - public int coverMeButDontTestMe() { - return 1; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package com.example; + +public class CoveredButOnlyPartiallyTested { + + public int coverMe() { + return 1; + } + + public int coverMeButDontTestMe() { + return 1; + } + +} diff --git a/pitest-entry/src/test/java/com/example/CoveredButOnlyPartiallyTestedTest.java b/pitest-entry/src/test/java/com/example/CoveredButOnlyPartiallyTestedTest.java index cab3ecba0..ac2f84f0f 100644 --- a/pitest-entry/src/test/java/com/example/CoveredButOnlyPartiallyTestedTest.java +++ b/pitest-entry/src/test/java/com/example/CoveredButOnlyPartiallyTestedTest.java @@ -1,36 +1,36 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package com.example; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class CoveredButOnlyPartiallyTestedTest { - - @Test - public void testCoverMe() { - final CoveredButOnlyPartiallyTested testee = new CoveredButOnlyPartiallyTested(); - assertEquals(1, testee.coverMe()); - } - - @Test - public void coverButDontTest() { - final CoveredButOnlyPartiallyTested testee = new CoveredButOnlyPartiallyTested(); - testee.coverMeButDontTestMe(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CoveredButOnlyPartiallyTestedTest { + + @Test + public void testCoverMe() { + final CoveredButOnlyPartiallyTested testee = new CoveredButOnlyPartiallyTested(); + assertEquals(1, testee.coverMe()); + } + + @Test + public void coverButDontTest() { + final CoveredButOnlyPartiallyTested testee = new CoveredButOnlyPartiallyTested(); + testee.coverMeButDontTestMe(); + } + +} diff --git a/pitest-entry/src/test/java/com/example/CoveredByEasyMock.java b/pitest-entry/src/test/java/com/example/CoveredByEasyMock.java index e7f0f42bf..e8c701a73 100644 --- a/pitest-entry/src/test/java/com/example/CoveredByEasyMock.java +++ b/pitest-entry/src/test/java/com/example/CoveredByEasyMock.java @@ -1,30 +1,30 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -public class CoveredByEasyMock { - - public static interface AnInterface { - public void callMe(); - } - - public void doStuff(final AnInterface ai) { - for (int i = 0; i != 2; i++) { - ai.callMe(); - } - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +public class CoveredByEasyMock { + + public static interface AnInterface { + public void callMe(); + } + + public void doStuff(final AnInterface ai) { + for (int i = 0; i != 2; i++) { + ai.callMe(); + } + + } + +} diff --git a/pitest-entry/src/test/java/com/example/CrashesJVMWhenMutated.java b/pitest-entry/src/test/java/com/example/CrashesJVMWhenMutated.java index 2e3f9d65d..1f36346f8 100644 --- a/pitest-entry/src/test/java/com/example/CrashesJVMWhenMutated.java +++ b/pitest-entry/src/test/java/com/example/CrashesJVMWhenMutated.java @@ -1,23 +1,23 @@ -package com.example; - -public class CrashesJVMWhenMutated { - - public static void crashJVM(final int i) { - if (i == 0) { - crashJVM(); - } - } - - private static void crashJVM() { - Runtime.getRuntime().halt(2); - - // crashes Sun Java 5, but not later versions of 6 - // and hopefully (?) other OS' - // see http://stackoverflow.com/questions/65200/how-do-you-crash-a-jvm - // Object[] o = null; - // while (true) { - // o = new Object[] { o }; - // } - } - -} +package com.example; + +public class CrashesJVMWhenMutated { + + public static void crashJVM(final int i) { + if (i == 0) { + crashJVM(); + } + } + + private static void crashJVM() { + Runtime.getRuntime().halt(2); + + // crashes Sun Java 5, but not later versions of 6 + // and hopefully (?) other OS' + // see http://stackoverflow.com/questions/65200/how-do-you-crash-a-jvm + // Object[] o = null; + // while (true) { + // o = new Object[] { o }; + // } + } + +} diff --git a/pitest-entry/src/test/java/com/example/EasyMockTest.java b/pitest-entry/src/test/java/com/example/EasyMockTest.java index e287bdefa..28080aa15 100644 --- a/pitest-entry/src/test/java/com/example/EasyMockTest.java +++ b/pitest-entry/src/test/java/com/example/EasyMockTest.java @@ -1,48 +1,48 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import org.junit.Before; -import org.junit.Test; - -import com.example.CoveredByEasyMock.AnInterface; - -public class EasyMockTest { - - private CoveredByEasyMock testee; - private AnInterface mock; - - @Before - public void setUp() { - this.mock = createMock(AnInterface.class); - this.testee = new CoveredByEasyMock(); - } - - @Test - public void testAddDocument() { - this.mock.callMe(); - expectLastCall().times(2); - - replay(this.mock); - this.testee.doStuff(this.mock); - verify(this.mock); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import org.junit.Before; +import org.junit.Test; + +import com.example.CoveredByEasyMock.AnInterface; + +public class EasyMockTest { + + private CoveredByEasyMock testee; + private AnInterface mock; + + @Before + public void setUp() { + this.mock = createMock(AnInterface.class); + this.testee = new CoveredByEasyMock(); + } + + @Test + public void testAddDocument() { + this.mock.callMe(); + expectLastCall().times(2); + + replay(this.mock); + this.testee.doStuff(this.mock); + verify(this.mock); + } + +} diff --git a/pitest-entry/src/test/java/com/example/FailsTestWhenEnvVariableSetTestee.java b/pitest-entry/src/test/java/com/example/FailsTestWhenEnvVariableSetTestee.java index 18647d53c..f05fddc46 100644 --- a/pitest-entry/src/test/java/com/example/FailsTestWhenEnvVariableSetTestee.java +++ b/pitest-entry/src/test/java/com/example/FailsTestWhenEnvVariableSetTestee.java @@ -1,18 +1,18 @@ -package com.example; - -public class FailsTestWhenEnvVariableSetTestee { - - public boolean returnTrue() { - final int i = 0; - int j = i << 2; - j = j + i; - - if (!"true".equals(System - .getProperty(FailsTestWhenEnvVariableSetTestee.class.getName()))) { - return true; - } else { - return false; - } - } - -} +package com.example; + +public class FailsTestWhenEnvVariableSetTestee { + + public boolean returnTrue() { + final int i = 0; + int j = i << 2; + j = j + i; + + if (!"true".equals(System + .getProperty(FailsTestWhenEnvVariableSetTestee.class.getName()))) { + return true; + } else { + return false; + } + } + +} diff --git a/pitest-entry/src/test/java/com/example/FailsTestWhenEnvVariableSetTesteeTest.java b/pitest-entry/src/test/java/com/example/FailsTestWhenEnvVariableSetTesteeTest.java index 2c4657a68..5d1e87925 100644 --- a/pitest-entry/src/test/java/com/example/FailsTestWhenEnvVariableSetTesteeTest.java +++ b/pitest-entry/src/test/java/com/example/FailsTestWhenEnvVariableSetTesteeTest.java @@ -1,14 +1,14 @@ -package com.example; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class FailsTestWhenEnvVariableSetTesteeTest { - - @Test - public void testNotCurrentlyFalse() { - final FailsTestWhenEnvVariableSetTestee testee = new FailsTestWhenEnvVariableSetTestee(); - assertTrue(testee.returnTrue()); - } -} +package com.example; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class FailsTestWhenEnvVariableSetTesteeTest { + + @Test + public void testNotCurrentlyFalse() { + final FailsTestWhenEnvVariableSetTestee testee = new FailsTestWhenEnvVariableSetTestee(); + assertTrue(testee.returnTrue()); + } +} diff --git a/pitest-entry/src/test/java/com/example/FullyCoveredTestee.java b/pitest-entry/src/test/java/com/example/FullyCoveredTestee.java index 706382c81..730b62dfb 100644 --- a/pitest-entry/src/test/java/com/example/FullyCoveredTestee.java +++ b/pitest-entry/src/test/java/com/example/FullyCoveredTestee.java @@ -1,24 +1,24 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package com.example; - -public class FullyCoveredTestee { - - public int coverMe() { - return 1; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package com.example; + +public class FullyCoveredTestee { + + public int coverMe() { + return 1; + } + +} diff --git a/pitest-entry/src/test/java/com/example/FullyCoveredTesteeTest.java b/pitest-entry/src/test/java/com/example/FullyCoveredTesteeTest.java index 22320dc58..16ebe8a41 100644 --- a/pitest-entry/src/test/java/com/example/FullyCoveredTesteeTest.java +++ b/pitest-entry/src/test/java/com/example/FullyCoveredTesteeTest.java @@ -1,46 +1,46 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class FullyCoveredTesteeTest { - - @Test - public void testCoverMe() { - final FullyCoveredTestee testee = new FullyCoveredTestee(); - - assertThat(testee.coverMe(), is(1)); - - assertEquals(1, testee.coverMe()); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - - if (obj instanceof Integer) { - return false; - } - - return false; - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class FullyCoveredTesteeTest { + + @Test + public void testCoverMe() { + final FullyCoveredTestee testee = new FullyCoveredTestee(); + + assertThat(testee.coverMe(), is(1)); + + assertEquals(1, testee.coverMe()); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + + if (obj instanceof Integer) { + return false; + } + + return false; + } +} diff --git a/pitest-entry/src/test/java/com/example/HasMutableStaticInitializer.java b/pitest-entry/src/test/java/com/example/HasMutableStaticInitializer.java index 26d23e7b6..1ffceb66d 100644 --- a/pitest-entry/src/test/java/com/example/HasMutableStaticInitializer.java +++ b/pitest-entry/src/test/java/com/example/HasMutableStaticInitializer.java @@ -1,33 +1,33 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package com.example; - -public class HasMutableStaticInitializer { - - public static int i; - public static int j; - - static { - final int a = Integer.valueOf(100); - i = a; - j = i + 1; - } - - public static void noticeMe() { - - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package com.example; + +public class HasMutableStaticInitializer { + + public static int i; + public static int j; + + static { + final int a = Integer.valueOf(100); + i = a; + j = i + 1; + } + + public static void noticeMe() { + + } + +} diff --git a/pitest-entry/src/test/java/com/example/HasMutableStaticInitializerTest.java b/pitest-entry/src/test/java/com/example/HasMutableStaticInitializerTest.java index 919874048..c26414fd1 100644 --- a/pitest-entry/src/test/java/com/example/HasMutableStaticInitializerTest.java +++ b/pitest-entry/src/test/java/com/example/HasMutableStaticInitializerTest.java @@ -1,37 +1,37 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package com.example; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class HasMutableStaticInitializerTest { - - @Test - public void testValueOfI() { - assertEquals(100, HasMutableStaticInitializer.i); - } - - @Test - public void testValueOfJ() { - // workaround to register this test as covering some part of the testee. - // static variable access does not currently register as coverage . . . - HasMutableStaticInitializer.noticeMe(); - - assertEquals(101, HasMutableStaticInitializer.j); - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HasMutableStaticInitializerTest { + + @Test + public void testValueOfI() { + assertEquals(100, HasMutableStaticInitializer.i); + } + + @Test + public void testValueOfJ() { + // workaround to register this test as covering some part of the testee. + // static variable access does not currently register as coverage . . . + HasMutableStaticInitializer.noticeMe(); + + assertEquals(101, HasMutableStaticInitializer.j); + } +} diff --git a/pitest-entry/src/test/java/com/example/HasMutationInFinallyBlockNonTest.java b/pitest-entry/src/test/java/com/example/HasMutationInFinallyBlockNonTest.java index 3e7d1db69..67789ae02 100644 --- a/pitest-entry/src/test/java/com/example/HasMutationInFinallyBlockNonTest.java +++ b/pitest-entry/src/test/java/com/example/HasMutationInFinallyBlockNonTest.java @@ -1,13 +1,13 @@ -package com.example; - -import org.junit.Test; - -public class HasMutationInFinallyBlockNonTest { - - @Test - public void testIncrementsI() { - final HasMutationsInFinallyBlock testee = new HasMutationsInFinallyBlock(); - testee.foo(1); // cover but don't test - } - -} +package com.example; + +import org.junit.Test; + +public class HasMutationInFinallyBlockNonTest { + + @Test + public void testIncrementsI() { + final HasMutationsInFinallyBlock testee = new HasMutationsInFinallyBlock(); + testee.foo(1); // cover but don't test + } + +} diff --git a/pitest-entry/src/test/java/com/example/HasMutationInFinallyBlockTest.java b/pitest-entry/src/test/java/com/example/HasMutationInFinallyBlockTest.java index ace5a6939..b848670a8 100644 --- a/pitest-entry/src/test/java/com/example/HasMutationInFinallyBlockTest.java +++ b/pitest-entry/src/test/java/com/example/HasMutationInFinallyBlockTest.java @@ -1,15 +1,15 @@ -package com.example; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class HasMutationInFinallyBlockTest { - - @Test - public void testIncrementsI() { - final HasMutationsInFinallyBlock testee = new HasMutationsInFinallyBlock(); - assertEquals(2, testee.foo(1)); - } - -} +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HasMutationInFinallyBlockTest { + + @Test + public void testIncrementsI() { + final HasMutationsInFinallyBlock testee = new HasMutationsInFinallyBlock(); + assertEquals(2, testee.foo(1)); + } + +} diff --git a/pitest-entry/src/test/java/com/example/HasMutationsInFinallyBlock.java b/pitest-entry/src/test/java/com/example/HasMutationsInFinallyBlock.java index f32217ecd..da883097b 100644 --- a/pitest-entry/src/test/java/com/example/HasMutationsInFinallyBlock.java +++ b/pitest-entry/src/test/java/com/example/HasMutationsInFinallyBlock.java @@ -1,14 +1,14 @@ -package com.example; - -public class HasMutationsInFinallyBlock { - - public int foo(int i) { - try { - System.out.println("don't optimise me away"); - } finally { - i++; - } - return i; - } - -} +package com.example; + +public class HasMutationsInFinallyBlock { + + public int foo(int i) { + try { + System.out.println("don't optimise me away"); + } finally { + i++; + } + return i; + } + +} diff --git a/pitest-entry/src/test/java/com/example/MockitoRunnerTest.java b/pitest-entry/src/test/java/com/example/MockitoRunnerTest.java index 32eb038b5..25b2eebd0 100644 --- a/pitest-entry/src/test/java/com/example/MockitoRunnerTest.java +++ b/pitest-entry/src/test/java/com/example/MockitoRunnerTest.java @@ -1,57 +1,57 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -import static org.mockito.Mockito.verify; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class MockitoRunnerTest { - - @Mock - MockitoFoo foo; - - @Test - public void testThings() { - final MockitoCallFoo testee = new MockitoCallFoo(this.foo); - testee.call(); - verify(this.foo).foo(); - - } - -} - -class MockitoCallFoo { - final MockitoFoo foo; - - public MockitoCallFoo(final MockitoFoo foo) { - this.foo = foo; - } - - public void call() { - this.foo.foo(); - } -} - -class MockitoFoo { - - public void foo() { - System.out.println("foo"); - } +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +import static org.mockito.Mockito.verify; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoRunnerTest { + + @Mock + MockitoFoo foo; + + @Test + public void testThings() { + final MockitoCallFoo testee = new MockitoCallFoo(this.foo); + testee.call(); + verify(this.foo).foo(); + + } + +} + +class MockitoCallFoo { + final MockitoFoo foo; + + public MockitoCallFoo(final MockitoFoo foo) { + this.foo = foo; + } + + public void call() { + this.foo.foo(); + } +} + +class MockitoFoo { + + public void foo() { + System.out.println("foo"); + } } \ No newline at end of file diff --git a/pitest-entry/src/test/java/com/example/MultiBlockCoverageTestee.java b/pitest-entry/src/test/java/com/example/MultiBlockCoverageTestee.java index c30535bc0..98d96bdc9 100644 --- a/pitest-entry/src/test/java/com/example/MultiBlockCoverageTestee.java +++ b/pitest-entry/src/test/java/com/example/MultiBlockCoverageTestee.java @@ -1,311 +1,311 @@ -package com.example; - -public class MultiBlockCoverageTestee { - - public static int blocks1(final int i) { - return i; - } - - // public void blocks2(int i) { - // switch(i) { - // case 0: - // System.out.println(); - // } - // } - - public static int blocks3(int i) { - if (i > 2) { - return i; - } - - return 1; - } - - public static int blocks4(int i) { - switch (i) { - case 1: - return 1; - default: - return 5; - } - } - - public static int blocks5(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - default: - return 5; - } - } - - public static int blocks6(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - default: - return 5; - } - } - - public static int blocks7(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - default: - return 50; - } - } - - public static int blocks8(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - default: - return 50; - } - } - - public static int blocks9(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - case 6: - return 7; - default: - return 50; - } - } - - public static int blocks10(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - case 6: - return 7; - case 7: - return 8; - default: - return 50; - } - } - - public static int blocks11(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - case 6: - return 7; - case 7: - return 8; - case 8: - return 9; - default: - return 50; - } - } - - public static int blocks12(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - case 6: - return 7; - case 7: - return 8; - case 8: - return 9; - case 9: - return 10; - default: - return 50; - } - } - - public static int blocks13(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - case 6: - return 7; - case 7: - return 8; - case 8: - return 9; - case 9: - return 10; - case 10: - return 11; - default: - return 50; - } - } - - public static int blocks14(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - case 6: - return 7; - case 7: - return 8; - case 8: - return 9; - case 9: - return 10; - case 10: - return 11; - case 11: - return 12; - default: - return 50; - } - } - - public static int blocks15(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - case 6: - return 7; - case 7: - return 8; - case 8: - return 9; - case 9: - return 10; - case 10: - return 11; - case 11: - return 12; - case 12: - return 13; - default: - return 50; - } - } - - public static int blocksMany(int i) { - switch (i) { - case 1: - return 1; - case 2: - return 3; - case 3: - return 4; - case 4: - return 5; - case 5: - return 6; - case 6: - return 7; - case 7: - return 8; - case 8: - return 9; - case 9: - return 10; - case 10: - return 11; - case 11: - return 12; - case 12: - return 13; - case 13: - return 14; - case 14: - return 15; - case 15: - return 16; - case 16: - return 17; - case 17: - return 18; - case 18: - return 19; - case 19: - return 20; - case 20: - return 21; - default: - return 50; - } - } - -} +package com.example; + +public class MultiBlockCoverageTestee { + + public static int blocks1(final int i) { + return i; + } + + // public void blocks2(int i) { + // switch(i) { + // case 0: + // System.out.println(); + // } + // } + + public static int blocks3(int i) { + if (i > 2) { + return i; + } + + return 1; + } + + public static int blocks4(int i) { + switch (i) { + case 1: + return 1; + default: + return 5; + } + } + + public static int blocks5(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + default: + return 5; + } + } + + public static int blocks6(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + default: + return 5; + } + } + + public static int blocks7(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + default: + return 50; + } + } + + public static int blocks8(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + default: + return 50; + } + } + + public static int blocks9(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + case 6: + return 7; + default: + return 50; + } + } + + public static int blocks10(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + case 6: + return 7; + case 7: + return 8; + default: + return 50; + } + } + + public static int blocks11(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + case 6: + return 7; + case 7: + return 8; + case 8: + return 9; + default: + return 50; + } + } + + public static int blocks12(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + case 6: + return 7; + case 7: + return 8; + case 8: + return 9; + case 9: + return 10; + default: + return 50; + } + } + + public static int blocks13(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + case 6: + return 7; + case 7: + return 8; + case 8: + return 9; + case 9: + return 10; + case 10: + return 11; + default: + return 50; + } + } + + public static int blocks14(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + case 6: + return 7; + case 7: + return 8; + case 8: + return 9; + case 9: + return 10; + case 10: + return 11; + case 11: + return 12; + default: + return 50; + } + } + + public static int blocks15(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + case 6: + return 7; + case 7: + return 8; + case 8: + return 9; + case 9: + return 10; + case 10: + return 11; + case 11: + return 12; + case 12: + return 13; + default: + return 50; + } + } + + public static int blocksMany(int i) { + switch (i) { + case 1: + return 1; + case 2: + return 3; + case 3: + return 4; + case 4: + return 5; + case 5: + return 6; + case 6: + return 7; + case 7: + return 8; + case 8: + return 9; + case 9: + return 10; + case 10: + return 11; + case 11: + return 12; + case 12: + return 13; + case 13: + return 14; + case 14: + return 15; + case 15: + return 16; + case 16: + return 17; + case 17: + return 18; + case 18: + return 19; + case 19: + return 20; + case 20: + return 21; + default: + return 50; + } + } + +} diff --git a/pitest-entry/src/test/java/com/example/MultiLineCoverageTestee.java b/pitest-entry/src/test/java/com/example/MultiLineCoverageTestee.java index 9148c863d..47bc9128a 100644 --- a/pitest-entry/src/test/java/com/example/MultiLineCoverageTestee.java +++ b/pitest-entry/src/test/java/com/example/MultiLineCoverageTestee.java @@ -1,203 +1,203 @@ -package com.example; - -public class MultiLineCoverageTestee { - - public int lines1(final int i) { - return i; - } - - public int lines2(int i) { - i++; - return i; - } - - public int lines3(int i) { - i++; - i++; - return i; - } - - public int lines4(int i) { - i++; - i++; - i++; - return i; - } - - public int lines5(int i) { - i++; - i++; - i++; - i++; - return i; - } - - public int lines6(int i) { - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines7(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines8(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines9(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines10(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines11(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines12(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines13(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines14(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines15(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - - public int lines30(int i) { - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - i++; - return i; - } - -} +package com.example; + +public class MultiLineCoverageTestee { + + public int lines1(final int i) { + return i; + } + + public int lines2(int i) { + i++; + return i; + } + + public int lines3(int i) { + i++; + i++; + return i; + } + + public int lines4(int i) { + i++; + i++; + i++; + return i; + } + + public int lines5(int i) { + i++; + i++; + i++; + i++; + return i; + } + + public int lines6(int i) { + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines7(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines8(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines9(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines10(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines11(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines12(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines13(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines14(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines15(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + + public int lines30(int i) { + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + i++; + return i; + } + +} diff --git a/pitest-entry/src/test/java/com/example/MultipleMutations.java b/pitest-entry/src/test/java/com/example/MultipleMutations.java index 224a14dbb..dc3de13f7 100644 --- a/pitest-entry/src/test/java/com/example/MultipleMutations.java +++ b/pitest-entry/src/test/java/com/example/MultipleMutations.java @@ -1,30 +1,30 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -public class MultipleMutations { - public int one() { - return 1; - } - - public int two() { - return 1; - } - - public int three() { - return 1; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +public class MultipleMutations { + public int one() { + return 1; + } + + public int two() { + return 1; + } + + public int three() { + return 1; + } + +} diff --git a/pitest-entry/src/test/java/com/example/PartiallyCoveredTestee.java b/pitest-entry/src/test/java/com/example/PartiallyCoveredTestee.java index 4a1de0563..78fb23b01 100644 --- a/pitest-entry/src/test/java/com/example/PartiallyCoveredTestee.java +++ b/pitest-entry/src/test/java/com/example/PartiallyCoveredTestee.java @@ -1,28 +1,28 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package com.example; - -public class PartiallyCoveredTestee { - - public int coverMe() { - return 1; - } - - public int dontCoverMe() { - return 1; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package com.example; + +public class PartiallyCoveredTestee { + + public int coverMe() { + return 1; + } + + public int dontCoverMe() { + return 1; + } + +} diff --git a/pitest-entry/src/test/java/com/example/PartiallyCoveredTesteeTest.java b/pitest-entry/src/test/java/com/example/PartiallyCoveredTesteeTest.java index 949cb1407..806bec24f 100644 --- a/pitest-entry/src/test/java/com/example/PartiallyCoveredTesteeTest.java +++ b/pitest-entry/src/test/java/com/example/PartiallyCoveredTesteeTest.java @@ -1,32 +1,32 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package com.example; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class PartiallyCoveredTesteeTest { - - @Test - public void testCoverMe() { - final PartiallyCoveredTestee testee = new PartiallyCoveredTestee(); - assertEquals(1, testee.coverMe()); - } - - // no test for dontcoverme - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class PartiallyCoveredTesteeTest { + + @Test + public void testCoverMe() { + final PartiallyCoveredTestee testee = new PartiallyCoveredTestee(); + assertEquals(1, testee.coverMe()); + } + + // no test for dontcoverme + +} diff --git a/pitest-entry/src/test/java/com/example/SuiteForFullyCovered.java b/pitest-entry/src/test/java/com/example/SuiteForFullyCovered.java index 607f0ea37..de3e37b8a 100644 --- a/pitest-entry/src/test/java/com/example/SuiteForFullyCovered.java +++ b/pitest-entry/src/test/java/com/example/SuiteForFullyCovered.java @@ -1,11 +1,11 @@ -package com.example; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses(FullyCoveredTesteeTest.class) -public class SuiteForFullyCovered { - -} +package com.example; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses(FullyCoveredTesteeTest.class) +public class SuiteForFullyCovered { + +} diff --git a/pitest-entry/src/test/java/com/example/TestCrashesJVMWhenMutated.java b/pitest-entry/src/test/java/com/example/TestCrashesJVMWhenMutated.java index d0505d888..a998db227 100644 --- a/pitest-entry/src/test/java/com/example/TestCrashesJVMWhenMutated.java +++ b/pitest-entry/src/test/java/com/example/TestCrashesJVMWhenMutated.java @@ -1,12 +1,12 @@ -package com.example; - -import org.junit.Test; - -public class TestCrashesJVMWhenMutated { - - @Test - public void runCrashMethodButDontHitCrashCode() { - CrashesJVMWhenMutated.crashJVM(42); - } - -} +package com.example; + +import org.junit.Test; + +public class TestCrashesJVMWhenMutated { + + @Test + public void runCrashMethodButDontHitCrashCode() { + CrashesJVMWhenMutated.crashJVM(42); + } + +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/CoveredBeforeExceptionTestee.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/CoveredBeforeExceptionTestee.java index 5ffdac7e5..c896f3432 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/CoveredBeforeExceptionTestee.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/CoveredBeforeExceptionTestee.java @@ -1,9 +1,9 @@ -package com.example.coverage.execute.samples.exceptions; - -public class CoveredBeforeExceptionTestee { - static int i; - - public static void bar() { - i++; - } -} +package com.example.coverage.execute.samples.exceptions; + +public class CoveredBeforeExceptionTestee { + static int i; + + public static void bar() { + i++; + } +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestThrowsExceptionFromLargeMethodTestee.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestThrowsExceptionFromLargeMethodTestee.java index 8fc076265..9847fe361 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestThrowsExceptionFromLargeMethodTestee.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestThrowsExceptionFromLargeMethodTestee.java @@ -1,13 +1,13 @@ -package com.example.coverage.execute.samples.exceptions; - -import org.junit.Test; - -public class TestThrowsExceptionFromLargeMethodTestee { - - @Test - public void test() { - ThrowsExceptionFromLargeMethodTestee testee = new ThrowsExceptionFromLargeMethodTestee(); - testee.foo(); - } - -} +package com.example.coverage.execute.samples.exceptions; + +import org.junit.Test; + +public class TestThrowsExceptionFromLargeMethodTestee { + + @Test + public void test() { + ThrowsExceptionFromLargeMethodTestee testee = new ThrowsExceptionFromLargeMethodTestee(); + testee.foo(); + } + +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestThrowsExceptionInFinallyBlock.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestThrowsExceptionInFinallyBlock.java index ed0c7fe1a..e5557082e 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestThrowsExceptionInFinallyBlock.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestThrowsExceptionInFinallyBlock.java @@ -1,13 +1,13 @@ -package com.example.coverage.execute.samples.exceptions; - -import org.junit.Test; - -public class TestThrowsExceptionInFinallyBlock { - - @Test - public void test() { - final ThrowsExceptionInFinallyBlockTestee t = new ThrowsExceptionInFinallyBlockTestee(); - t.foo(); - } - -} +package com.example.coverage.execute.samples.exceptions; + +import org.junit.Test; + +public class TestThrowsExceptionInFinallyBlock { + + @Test + public void test() { + final ThrowsExceptionInFinallyBlockTestee t = new ThrowsExceptionInFinallyBlockTestee(); + t.foo(); + } + +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestsClassWithException.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestsClassWithException.java index 82281ec1f..b14e33d09 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestsClassWithException.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/TestsClassWithException.java @@ -1,11 +1,11 @@ -package com.example.coverage.execute.samples.exceptions; - -import org.junit.Test; - -public class TestsClassWithException { - @Test - public void test() { - final ThrowsExceptionTestee t = new ThrowsExceptionTestee(); - t.foo(); - } +package com.example.coverage.execute.samples.exceptions; + +import org.junit.Test; + +public class TestsClassWithException { + @Test + public void test() { + final ThrowsExceptionTestee t = new ThrowsExceptionTestee(); + t.foo(); + } } \ No newline at end of file diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionFromLargeMethodTestee.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionFromLargeMethodTestee.java index 95ff36f2d..dad790ba2 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionFromLargeMethodTestee.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionFromLargeMethodTestee.java @@ -1,43 +1,43 @@ -package com.example.coverage.execute.samples.exceptions; - -public class ThrowsExceptionFromLargeMethodTestee { - int i; - - public int foo() { - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - this.i++; - throwsException(); - return this.i; - } - - private void throwsException() { - throw new RuntimeException(); - } -} +package com.example.coverage.execute.samples.exceptions; + +public class ThrowsExceptionFromLargeMethodTestee { + int i; + + public int foo() { + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + this.i++; + throwsException(); + return this.i; + } + + private void throwsException() { + throw new RuntimeException(); + } +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionInFinallyBlockTestee.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionInFinallyBlockTestee.java index 6cc58878f..0ea4daa61 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionInFinallyBlockTestee.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionInFinallyBlockTestee.java @@ -1,17 +1,17 @@ -package com.example.coverage.execute.samples.exceptions; - -public class ThrowsExceptionInFinallyBlockTestee { - - public void foo() { - try { - throwsException(); - } finally { - System.out.println("foo"); - } - } - - private void throwsException() { - throw new RuntimeException(); - } - -} +package com.example.coverage.execute.samples.exceptions; + +public class ThrowsExceptionInFinallyBlockTestee { + + public void foo() { + try { + throwsException(); + } finally { + System.out.println("foo"); + } + } + + private void throwsException() { + throw new RuntimeException(); + } + +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionTestee.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionTestee.java index f25494694..6b2ab58ba 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionTestee.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/exceptions/ThrowsExceptionTestee.java @@ -1,12 +1,12 @@ -package com.example.coverage.execute.samples.exceptions; - -public class ThrowsExceptionTestee { - public void foo() { - CoveredBeforeExceptionTestee.bar(); - throwsException(); - } - - private void throwsException() { - throw new RuntimeException(); - } +package com.example.coverage.execute.samples.exceptions; + +public class ThrowsExceptionTestee { + public void foo() { + CoveredBeforeExceptionTestee.bar(); + throwsException(); + } + + private void throwsException() { + throw new RuntimeException(); + } } \ No newline at end of file diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Testee.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Testee.java index 3563995a9..0a362e5b1 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Testee.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Testee.java @@ -1,16 +1,16 @@ -package com.example.coverage.execute.samples.simple; - -public class Testee implements Runnable { - public void foo() { - } - - public void bar() { - - } - - @Override - public void run() { - new Testee2().bar(); - } - +package com.example.coverage.execute.samples.simple; + +public class Testee implements Runnable { + public void foo() { + } + + public void bar() { + + } + + @Override + public void run() { + new Testee2().bar(); + } + } \ No newline at end of file diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Testee2.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Testee2.java index af19fb9a1..8b4bde94c 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Testee2.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Testee2.java @@ -1,11 +1,11 @@ -package com.example.coverage.execute.samples.simple; - -public class Testee2 { - public void foo() { - - } - - public void bar() { - - } -} +package com.example.coverage.execute.samples.simple; + +public class Testee2 { + public void foo() { + + } + + public void bar() { + + } +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithComplexConstructors.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithComplexConstructors.java index 1b35fb50c..86c91d479 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithComplexConstructors.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithComplexConstructors.java @@ -1,14 +1,14 @@ -package com.example.coverage.execute.samples.simple; - -public class TesteeWithComplexConstructors { - - public int f; - - TesteeWithComplexConstructors(int a) { - if (a > 10) { - this.f = 11; - } else { - this.f = 42; - } - } -} +package com.example.coverage.execute.samples.simple; + +public class TesteeWithComplexConstructors { + + public int f; + + TesteeWithComplexConstructors(int a) { + if (a > 10) { + this.f = 11; + } else { + this.f = 42; + } + } +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithComplexConstructorsTest.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithComplexConstructorsTest.java index 8a0eef28d..6bc231aa7 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithComplexConstructorsTest.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithComplexConstructorsTest.java @@ -1,17 +1,17 @@ -package com.example.coverage.execute.samples.simple; - -import org.junit.Test; - -public class TesteeWithComplexConstructorsTest { - - @Test - public void testLow() { - new TesteeWithComplexConstructors(1); - } - - @Test - public void testHigh() { - new TesteeWithComplexConstructors(100); - } - -} +package com.example.coverage.execute.samples.simple; + +import org.junit.Test; + +public class TesteeWithComplexConstructorsTest { + + @Test + public void testLow() { + new TesteeWithComplexConstructors(1); + } + + @Test + public void testHigh() { + new TesteeWithComplexConstructors(100); + } + +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithMultipleLines.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithMultipleLines.java index f3d3933a5..b39e16b9d 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithMultipleLines.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TesteeWithMultipleLines.java @@ -1,24 +1,24 @@ -package com.example.coverage.execute.samples.simple; - -public class TesteeWithMultipleLines { - - public int bar(int i, int j) { - i = i + j; - j = +j + j; - i = j + i; - - return i++; - } - - public int foo(final int i) { - int j = 0; - try { - j = j + 1; - j = Math.max(i, j); - return j; - } catch (final RuntimeException ex) { - return 1; - } - } - -} +package com.example.coverage.execute.samples.simple; + +public class TesteeWithMultipleLines { + + public int bar(int i, int j) { + i = i + j; + j = +j + j; + i = j + i; + + return i++; + } + + public int foo(final int i) { + int j = 0; + try { + j = j + 1; + j = Math.max(i, j); + return j; + } catch (final RuntimeException ex) { + return 1; + } + } + +} diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Tests.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Tests.java index 229f14351..a4cb69ad6 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Tests.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/Tests.java @@ -1,25 +1,25 @@ -package com.example.coverage.execute.samples.simple; - -import org.junit.Test; - -public class Tests { - - @Test - public void testFoo() { - final Testee testee = new Testee(); - testee.foo(); - - } - - @Test - public void testFoo2() { - final Testee2 testee2 = new Testee2(); - testee2.foo(); - } - - @Test - public void testFoo3() { - final TesteeWithMultipleLines testee2 = new TesteeWithMultipleLines(); - testee2.foo(1); - } +package com.example.coverage.execute.samples.simple; + +import org.junit.Test; + +public class Tests { + + @Test + public void testFoo() { + final Testee testee = new Testee(); + testee.foo(); + + } + + @Test + public void testFoo2() { + final Testee2 testee2 = new Testee2(); + testee2.foo(); + } + + @Test + public void testFoo3() { + final TesteeWithMultipleLines testee2 = new TesteeWithMultipleLines(); + testee2.foo(1); + } } \ No newline at end of file diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TestsForMultiBlockCoverage.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TestsForMultiBlockCoverage.java index e6df9a1d2..49214578b 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TestsForMultiBlockCoverage.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TestsForMultiBlockCoverage.java @@ -1,92 +1,92 @@ -package com.example.coverage.execute.samples.simple; - -import org.junit.Test; - -import com.example.MultiBlockCoverageTestee; - -public class TestsForMultiBlockCoverage { - - @Test - public void test1() { - MultiBlockCoverageTestee.blocks1(1); - } - - // @Test - // public void test2() { - // try { - // MultiBlockCoverageTestee.blocks2(1); - // } catch(UnsupportedOperationException e) { - // - // } - // } - - @Test - public void test3() { - MultiBlockCoverageTestee.blocks3(1); - } - - @Test - public void test4() { - MultiBlockCoverageTestee.blocks4(1); - } - - @Test - public void test5() { - MultiBlockCoverageTestee.blocks5(1); - } - - @Test - public void test6() { - MultiBlockCoverageTestee.blocks6(1); - } - - @Test - public void test7() { - MultiBlockCoverageTestee.blocks7(1); - } - - @Test - public void test8() { - MultiBlockCoverageTestee.blocks8(1); - } - - @Test - public void test9() { - MultiBlockCoverageTestee.blocks9(1); - } - - @Test - public void test10() { - MultiBlockCoverageTestee.blocks10(1); - } - - @Test - public void test11() { - MultiBlockCoverageTestee.blocks11(1); - } - - @Test - public void test12() { - MultiBlockCoverageTestee.blocks12(1); - } - - @Test - public void test13() { - MultiBlockCoverageTestee.blocks13(1); - } - - @Test - public void test14() { - MultiBlockCoverageTestee.blocks14(1); - } - - @Test - public void test15() { - MultiBlockCoverageTestee.blocks15(1); - } - - @Test - public void testMany() { - MultiBlockCoverageTestee.blocksMany(1); - } +package com.example.coverage.execute.samples.simple; + +import org.junit.Test; + +import com.example.MultiBlockCoverageTestee; + +public class TestsForMultiBlockCoverage { + + @Test + public void test1() { + MultiBlockCoverageTestee.blocks1(1); + } + + // @Test + // public void test2() { + // try { + // MultiBlockCoverageTestee.blocks2(1); + // } catch(UnsupportedOperationException e) { + // + // } + // } + + @Test + public void test3() { + MultiBlockCoverageTestee.blocks3(1); + } + + @Test + public void test4() { + MultiBlockCoverageTestee.blocks4(1); + } + + @Test + public void test5() { + MultiBlockCoverageTestee.blocks5(1); + } + + @Test + public void test6() { + MultiBlockCoverageTestee.blocks6(1); + } + + @Test + public void test7() { + MultiBlockCoverageTestee.blocks7(1); + } + + @Test + public void test8() { + MultiBlockCoverageTestee.blocks8(1); + } + + @Test + public void test9() { + MultiBlockCoverageTestee.blocks9(1); + } + + @Test + public void test10() { + MultiBlockCoverageTestee.blocks10(1); + } + + @Test + public void test11() { + MultiBlockCoverageTestee.blocks11(1); + } + + @Test + public void test12() { + MultiBlockCoverageTestee.blocks12(1); + } + + @Test + public void test13() { + MultiBlockCoverageTestee.blocks13(1); + } + + @Test + public void test14() { + MultiBlockCoverageTestee.blocks14(1); + } + + @Test + public void test15() { + MultiBlockCoverageTestee.blocks15(1); + } + + @Test + public void testMany() { + MultiBlockCoverageTestee.blocksMany(1); + } } \ No newline at end of file diff --git a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TestsForMultilineCoverage.java b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TestsForMultilineCoverage.java index 6361dae73..79ee90b64 100644 --- a/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TestsForMultilineCoverage.java +++ b/pitest-entry/src/test/java/com/example/coverage/execute/samples/simple/TestsForMultilineCoverage.java @@ -1,90 +1,90 @@ -package com.example.coverage.execute.samples.simple; - -import org.junit.Test; - -import com.example.MultiLineCoverageTestee; - -public class TestsForMultilineCoverage { - - private final MultiLineCoverageTestee t = new MultiLineCoverageTestee(); - - @Test - public void test1() { - this.t.lines1(1); - } - - @Test - public void test2() { - this.t.lines2(1); - } - - @Test - public void test3() { - this.t.lines3(1); - } - - @Test - public void test4() { - this.t.lines4(1); - } - - @Test - public void test5() { - this.t.lines5(1); - } - - @Test - public void test6() { - this.t.lines6(1); - } - - @Test - public void test7() { - this.t.lines7(1); - } - - @Test - public void test8() { - this.t.lines8(1); - } - - @Test - public void test9() { - this.t.lines9(1); - } - - @Test - public void test10() { - this.t.lines10(1); - } - - @Test - public void test11() { - this.t.lines11(1); - } - - @Test - public void test12() { - this.t.lines12(1); - } - - @Test - public void test13() { - this.t.lines13(1); - } - - @Test - public void test14() { - this.t.lines14(1); - } - - @Test - public void test15() { - this.t.lines15(1); - } - - @Test - public void test30() { - this.t.lines30(1); - } +package com.example.coverage.execute.samples.simple; + +import org.junit.Test; + +import com.example.MultiLineCoverageTestee; + +public class TestsForMultilineCoverage { + + private final MultiLineCoverageTestee t = new MultiLineCoverageTestee(); + + @Test + public void test1() { + this.t.lines1(1); + } + + @Test + public void test2() { + this.t.lines2(1); + } + + @Test + public void test3() { + this.t.lines3(1); + } + + @Test + public void test4() { + this.t.lines4(1); + } + + @Test + public void test5() { + this.t.lines5(1); + } + + @Test + public void test6() { + this.t.lines6(1); + } + + @Test + public void test7() { + this.t.lines7(1); + } + + @Test + public void test8() { + this.t.lines8(1); + } + + @Test + public void test9() { + this.t.lines9(1); + } + + @Test + public void test10() { + this.t.lines10(1); + } + + @Test + public void test11() { + this.t.lines11(1); + } + + @Test + public void test12() { + this.t.lines12(1); + } + + @Test + public void test13() { + this.t.lines13(1); + } + + @Test + public void test14() { + this.t.lines14(1); + } + + @Test + public void test15() { + this.t.lines15(1); + } + + @Test + public void test30() { + this.t.lines30(1); + } } \ No newline at end of file diff --git a/pitest-entry/src/test/java/com/example/mutatablecodeintest/Mutee.java b/pitest-entry/src/test/java/com/example/mutatablecodeintest/Mutee.java index eb470e967..ee2b822f3 100644 --- a/pitest-entry/src/test/java/com/example/mutatablecodeintest/Mutee.java +++ b/pitest-entry/src/test/java/com/example/mutatablecodeintest/Mutee.java @@ -1,9 +1,9 @@ -package com.example.mutatablecodeintest; - -public class Mutee { - - public static int returnOne() { - return 1; - } - -} +package com.example.mutatablecodeintest; + +public class Mutee { + + public static int returnOne() { + return 1; + } + +} diff --git a/pitest-entry/src/test/java/com/example/mutatablecodeintest/MuteeTest.java b/pitest-entry/src/test/java/com/example/mutatablecodeintest/MuteeTest.java index 4abd6dbce..8f8020545 100644 --- a/pitest-entry/src/test/java/com/example/mutatablecodeintest/MuteeTest.java +++ b/pitest-entry/src/test/java/com/example/mutatablecodeintest/MuteeTest.java @@ -1,37 +1,37 @@ -package com.example.mutatablecodeintest; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class MuteeTest { - - int i; - - public MuteeTest(final int i) { - this.i = i; - } - - @Parameters - public static Collection params() { - if (Mutee.returnOne() != 1) { - throw new RuntimeException(); - } - return Arrays.asList(new Object[][] { { 1 }, { 2 }, { 3 } }); - } - - @Test - public void test1() { - - } - - @Test - public void test2() { - - } -} +package com.example.mutatablecodeintest; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(Parameterized.class) +public class MuteeTest { + + int i; + + public MuteeTest(final int i) { + this.i = i; + } + + @Parameters + public static Collection params() { + if (Mutee.returnOne() != 1) { + throw new RuntimeException(); + } + return Arrays.asList(new Object[][] { { 1 }, { 2 }, { 3 } }); + } + + @Test + public void test1() { + + } + + @Test + public void test2() { + + } +} diff --git a/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledFromInitializerAndElseWhere.java b/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledFromInitializerAndElseWhere.java index faaa48aae..90d1ac5b3 100644 --- a/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledFromInitializerAndElseWhere.java +++ b/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledFromInitializerAndElseWhere.java @@ -1,18 +1,18 @@ -package com.example.staticinitializers; - -public class MethodsCalledFromInitializerAndElseWhere { - - static { - mutateMe(); - } - - private static boolean mutateMe() { - System.out.println("don't mutate"); - return true; - } - - public static boolean alsoCalls() { - return mutateMe(); - } - -} +package com.example.staticinitializers; + +public class MethodsCalledFromInitializerAndElseWhere { + + static { + mutateMe(); + } + + private static boolean mutateMe() { + System.out.println("don't mutate"); + return true; + } + + public static boolean alsoCalls() { + return mutateMe(); + } + +} diff --git a/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledInChainFromStaticInitializer.java b/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledInChainFromStaticInitializer.java index 75fd5d9a6..d836a29d5 100644 --- a/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledInChainFromStaticInitializer.java +++ b/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledInChainFromStaticInitializer.java @@ -1,18 +1,18 @@ -package com.example.staticinitializers; - -public class MethodsCalledInChainFromStaticInitializer { - - static { - a(); - } - - private static void a() { - System.out.println("don't mutate"); - b(); - } - - private static void b() { - System.out.println("don't mutate"); - } - -} +package com.example.staticinitializers; + +public class MethodsCalledInChainFromStaticInitializer { + + static { + a(); + } + + private static void a() { + System.out.println("don't mutate"); + b(); + } + + private static void b() { + System.out.println("don't mutate"); + } + +} diff --git a/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledOnlyFromInitializer.java b/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledOnlyFromInitializer.java index 1860c61bd..d6e3c80c0 100644 --- a/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledOnlyFromInitializer.java +++ b/pitest-entry/src/test/java/com/example/staticinitializers/MethodsCalledOnlyFromInitializer.java @@ -1,13 +1,13 @@ -package com.example.staticinitializers; - -public class MethodsCalledOnlyFromInitializer { - - static { - dontMutate(); - } - - private static void dontMutate() { - System.out.println("don't mutate"); - } - -} +package com.example.staticinitializers; + +public class MethodsCalledOnlyFromInitializer { + + static { + dontMutate(); + } + + private static void dontMutate() { + System.out.println("don't mutate"); + } + +} diff --git a/pitest-entry/src/test/java/com/example/staticinitializers/NonPrivateMethodsCalledFromInitializerOnly.java b/pitest-entry/src/test/java/com/example/staticinitializers/NonPrivateMethodsCalledFromInitializerOnly.java index f614e463b..605ecc450 100644 --- a/pitest-entry/src/test/java/com/example/staticinitializers/NonPrivateMethodsCalledFromInitializerOnly.java +++ b/pitest-entry/src/test/java/com/example/staticinitializers/NonPrivateMethodsCalledFromInitializerOnly.java @@ -1,24 +1,24 @@ -package com.example.staticinitializers; - -public class NonPrivateMethodsCalledFromInitializerOnly { - - static { - mutateDefault(); - mutateProtected(); - mutatePublic(); - } - - // NOT private - static void mutateDefault() { - System.out.println("mutate me"); - } - - protected static void mutateProtected() { - System.out.println("mutate me"); - } - - public static void mutatePublic() { - System.out.println("mutate me"); - } - -} +package com.example.staticinitializers; + +public class NonPrivateMethodsCalledFromInitializerOnly { + + static { + mutateDefault(); + mutateProtected(); + mutatePublic(); + } + + // NOT private + static void mutateDefault() { + System.out.println("mutate me"); + } + + protected static void mutateProtected() { + System.out.println("mutate me"); + } + + public static void mutatePublic() { + System.out.println("mutate me"); + } + +} diff --git a/pitest-entry/src/test/java/com/example/testhasignores/Mutee.java b/pitest-entry/src/test/java/com/example/testhasignores/Mutee.java index c6abe7def..87facdd2e 100644 --- a/pitest-entry/src/test/java/com/example/testhasignores/Mutee.java +++ b/pitest-entry/src/test/java/com/example/testhasignores/Mutee.java @@ -1,9 +1,9 @@ -package com.example.testhasignores; - -public class Mutee { - - public static int returnOne() { - return 1; - } - -} +package com.example.testhasignores; + +public class Mutee { + + public static int returnOne() { + return 1; + } + +} diff --git a/pitest-entry/src/test/java/com/example/testhasignores/MuteeTest.java b/pitest-entry/src/test/java/com/example/testhasignores/MuteeTest.java index a719048b6..a0e6cb3e4 100644 --- a/pitest-entry/src/test/java/com/example/testhasignores/MuteeTest.java +++ b/pitest-entry/src/test/java/com/example/testhasignores/MuteeTest.java @@ -1,35 +1,35 @@ -package com.example.testhasignores; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -public class MuteeTest { - - @BeforeClass - public static void foo() { - - } - - @Test(expected = NullPointerException.class) - public void test1() { - // does nothing - throw new NullPointerException(); - } - - @Ignore - @Test - public void test2() { - fail("not yet supported"); - } - - @Test(expected = NullPointerException.class) - public void thisOneKills() { - assertEquals(1, Mutee.returnOne()); - throw new NullPointerException(); - } - -} +package com.example.testhasignores; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +public class MuteeTest { + + @BeforeClass + public static void foo() { + + } + + @Test(expected = NullPointerException.class) + public void test1() { + // does nothing + throw new NullPointerException(); + } + + @Ignore + @Test + public void test2() { + fail("not yet supported"); + } + + @Test(expected = NullPointerException.class) + public void thisOneKills() { + assertEquals(1, Mutee.returnOne()); + throw new NullPointerException(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/bytecode/analysis/ClassTreeTest.java b/pitest-entry/src/test/java/org/pitest/bytecode/analysis/ClassTreeTest.java index 80694be56..4abc8595f 100644 --- a/pitest-entry/src/test/java/org/pitest/bytecode/analysis/ClassTreeTest.java +++ b/pitest-entry/src/test/java/org/pitest/bytecode/analysis/ClassTreeTest.java @@ -1,52 +1,52 @@ -package org.pitest.bytecode.analysis; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.function.Function; - -import org.junit.Test; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classpath.ClassloaderByteArraySource; - -public class ClassTreeTest { - - private final ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); - - @Test - public void shouldCreateTreeFromValidByteArray() { - final ClassTree testee = ClassTree.fromBytes(bytesFor(String.class)); - assertThat(testee.rawNode().name).isEqualTo("java/lang/String"); - } - - @Test - public void shouldAllowAccesToAllMethods() { - final ClassTree testee = ClassTree.fromBytes(bytesFor(ParseMe.class)); - assertThat(testee.methods().stream().map(toName())).containsExactly("", "a", "b"); - } - - @Test - public void toStringShouldPrintBytecode() { - final ClassTree testee = ClassTree.fromBytes(bytesFor(ParseMe.class)); - assertThat(testee.toString()).contains("ALOAD 0"); - } - - byte[] bytesFor(Class clazz) { - return this.source.getBytes(clazz.getName()).get(); - } - - private static Function toName() { - return a -> a.rawNode().name; - - } -} - - -class ParseMe { - public void a() { - b(); - } - - private int b() { - return 0; - } +package org.pitest.bytecode.analysis; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.function.Function; + +import org.junit.Test; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classpath.ClassloaderByteArraySource; + +public class ClassTreeTest { + + private final ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); + + @Test + public void shouldCreateTreeFromValidByteArray() { + final ClassTree testee = ClassTree.fromBytes(bytesFor(String.class)); + assertThat(testee.rawNode().name).isEqualTo("java/lang/String"); + } + + @Test + public void shouldAllowAccesToAllMethods() { + final ClassTree testee = ClassTree.fromBytes(bytesFor(ParseMe.class)); + assertThat(testee.methods().stream().map(toName())).containsExactly("", "a", "b"); + } + + @Test + public void toStringShouldPrintBytecode() { + final ClassTree testee = ClassTree.fromBytes(bytesFor(ParseMe.class)); + assertThat(testee.toString()).contains("ALOAD 0"); + } + + byte[] bytesFor(Class clazz) { + return this.source.getBytes(clazz.getName()).get(); + } + + private static Function toName() { + return a -> a.rawNode().name; + + } +} + + +class ParseMe { + public void a() { + b(); + } + + private int b() { + return 0; + } } \ No newline at end of file diff --git a/pitest-entry/src/test/java/org/pitest/bytecode/analysis/InstructionMatchersTest.java b/pitest-entry/src/test/java/org/pitest/bytecode/analysis/InstructionMatchersTest.java index c615117ef..9f0fa072f 100644 --- a/pitest-entry/src/test/java/org/pitest/bytecode/analysis/InstructionMatchersTest.java +++ b/pitest-entry/src/test/java/org/pitest/bytecode/analysis/InstructionMatchersTest.java @@ -1,164 +1,164 @@ -package org.pitest.bytecode.analysis; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJump; -import static org.pitest.bytecode.analysis.InstructionMatchers.aJump; -import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; -import static org.pitest.bytecode.analysis.InstructionMatchers.anILoadOf; -import static org.pitest.bytecode.analysis.InstructionMatchers.anIStore; -import static org.pitest.bytecode.analysis.InstructionMatchers.anIStoreTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.anIntegerConstant; -import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; -import static org.pitest.bytecode.analysis.InstructionMatchers.incrementsVariable; -import static org.pitest.bytecode.analysis.InstructionMatchers.isA; -import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallTo; -import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; - -import java.util.Collections; - -import org.junit.Test; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.IincInsnNode; -import org.objectweb.asm.tree.InsnNode; -import org.objectweb.asm.tree.JumpInsnNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.VarInsnNode; -import org.pitest.classinfo.ClassName; -import java.util.Optional; -import org.pitest.sequence.Context; -import org.pitest.sequence.Slot; - -public class InstructionMatchersTest { - - private final Context context = Context.start(Collections.emptyList()); - - @Test - public void anyInstructionShouldMatchAnything() { - final AbstractInsnNode node = new InsnNode(-1); - assertTrue(anyInstruction().test(this.context, node)); - } - - @Test - public void opCodeShouldMatchOnOpcode() { - final AbstractInsnNode node = new InsnNode(-1); - assertTrue(opCode(-1).test(this.context, node)); - assertFalse(opCode(0).test(this.context, node)); - } - - @Test - public void isAShouldMatchOnType() { - final AbstractInsnNode node = new InsnNode(-1); - assertTrue(isA(InsnNode.class).test(this.context, node)); - assertFalse(isA(LabelNode.class).test(this.context, node)); - } - - @Test - public void shouldMatchIncrementsToStoredLocalVariable() { - final Slot slot = Slot.create(Integer.class); - this.context.store(slot.write(), 42); - final IincInsnNode node = new IincInsnNode(42, 1); - assertTrue(incrementsVariable(slot.read()).test(this.context,node)); - } - - @Test - public void shouldNotMatchIncrementsToDifferentLocalVariable() { - final Slot slot = Slot.create(Integer.class); - this.context.store(slot.write(), 42); - final IincInsnNode node = new IincInsnNode(42 + 1, 1); - assertFalse(incrementsVariable(slot.read()).test(this.context,node)); - } - - @Test - public void shouldCaptureIStoreVariable() { - final Slot slot = Slot.create(Integer.class); - final VarInsnNode node = new VarInsnNode(Opcodes.ISTORE, 3); - assertTrue(anIStore(slot.write()).test(this.context,node)); - assertThat(this.context.retrieve(slot.read())).isEqualTo(Optional.ofNullable(3)); - } - - @Test - public void shouldMatchAgainstCapturedIStoreVariable() { - final Slot slot = Slot.create(Integer.class); - this.context.store(slot.write(), 3); - final VarInsnNode matchingNode = new VarInsnNode(Opcodes.ISTORE, 3); - assertTrue(anIStoreTo(slot.read()).test(this.context,matchingNode)); - - final VarInsnNode nonMatchingNode = new VarInsnNode(Opcodes.ISTORE, 4); - assertFalse(anIStoreTo(slot.read()).test(this.context,nonMatchingNode)); - } - - @Test - public void shouldMatchAgainstCapturedILoadVariable() { - final Slot slot = Slot.create(Integer.class); - this.context.store(slot.write(), 3); - final VarInsnNode matchingNode = new VarInsnNode(Opcodes.ILOAD, 3); - assertTrue(anILoadOf(slot.read()).test(this.context,matchingNode)); - - final VarInsnNode nonMatchingNode = new VarInsnNode(Opcodes.ILOAD, 4); - assertFalse(anILoadOf(slot.read()).test(this.context,nonMatchingNode)); - } - - @Test - public void shouldMatchAllIntegerConstants() { - assertFalse(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ACONST_NULL)))); - assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_M1)))); - assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_0)))); - assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_1)))); - assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_2)))); - assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_3)))); - assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_4)))); - assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_5)))); - } - - @Test - public void shouldCaptureLabels() { - final Slot slot = Slot.create(LabelNode.class); - final LabelNode label = new LabelNode(); - assertFalse(aLabelNode(slot.write()).test(this.context,new InsnNode(Opcodes.NULL))); - assertTrue(aLabelNode(slot.write()).test(this.context,label)); - assertThat(this.context.retrieve(slot.read())).isEqualTo(Optional.ofNullable(label)); - } - - @Test - public void shouldMatchJumps() { - assertTrue(aJump().test(this.context,new JumpInsnNode(Opcodes.GOTO, null))); - assertFalse(aJump().test(this.context, new InsnNode(Opcodes.ACONST_NULL))); - } - - @Test - public void shouldMatchConditionalJumps() { - assertFalse(aConditionalJump().test(this.context,new JumpInsnNode(Opcodes.GOTO, null))); - assertFalse(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.JSR, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFEQ, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFNE, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFLT, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFGE, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFGT, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFLE, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPEQ, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPNE, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPLT, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPGE, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPGT, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPLE, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ACMPEQ, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ACMPNE, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFNULL, null))); - assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFNONNULL, null))); - } - - @Test - public void shouldMatchMethodCallByOwnerAndName() { - final ClassName clazz = ClassName.fromString("clazz"); - assertTrue(methodCallTo(clazz, "name") - .test(this.context, new MethodInsnNode(Opcodes.INVOKEINTERFACE, "clazz", "name", "desc", true))); - assertFalse(methodCallTo(clazz, "name") - .test(this.context, new MethodInsnNode(Opcodes.INVOKEINTERFACE, "clazz", "notName", "desc", true))); - assertFalse(methodCallTo(clazz, "name") - .test(this.context, new MethodInsnNode(Opcodes.INVOKEINTERFACE, "notClazz", "name", "desc", true))); - } -} +package org.pitest.bytecode.analysis; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.pitest.bytecode.analysis.InstructionMatchers.aConditionalJump; +import static org.pitest.bytecode.analysis.InstructionMatchers.aJump; +import static org.pitest.bytecode.analysis.InstructionMatchers.aLabelNode; +import static org.pitest.bytecode.analysis.InstructionMatchers.anILoadOf; +import static org.pitest.bytecode.analysis.InstructionMatchers.anIStore; +import static org.pitest.bytecode.analysis.InstructionMatchers.anIStoreTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.anIntegerConstant; +import static org.pitest.bytecode.analysis.InstructionMatchers.anyInstruction; +import static org.pitest.bytecode.analysis.InstructionMatchers.incrementsVariable; +import static org.pitest.bytecode.analysis.InstructionMatchers.isA; +import static org.pitest.bytecode.analysis.InstructionMatchers.methodCallTo; +import static org.pitest.bytecode.analysis.InstructionMatchers.opCode; + +import java.util.Collections; + +import org.junit.Test; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.IincInsnNode; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.VarInsnNode; +import org.pitest.classinfo.ClassName; +import java.util.Optional; +import org.pitest.sequence.Context; +import org.pitest.sequence.Slot; + +public class InstructionMatchersTest { + + private final Context context = Context.start(Collections.emptyList()); + + @Test + public void anyInstructionShouldMatchAnything() { + final AbstractInsnNode node = new InsnNode(-1); + assertTrue(anyInstruction().test(this.context, node)); + } + + @Test + public void opCodeShouldMatchOnOpcode() { + final AbstractInsnNode node = new InsnNode(-1); + assertTrue(opCode(-1).test(this.context, node)); + assertFalse(opCode(0).test(this.context, node)); + } + + @Test + public void isAShouldMatchOnType() { + final AbstractInsnNode node = new InsnNode(-1); + assertTrue(isA(InsnNode.class).test(this.context, node)); + assertFalse(isA(LabelNode.class).test(this.context, node)); + } + + @Test + public void shouldMatchIncrementsToStoredLocalVariable() { + final Slot slot = Slot.create(Integer.class); + this.context.store(slot.write(), 42); + final IincInsnNode node = new IincInsnNode(42, 1); + assertTrue(incrementsVariable(slot.read()).test(this.context,node)); + } + + @Test + public void shouldNotMatchIncrementsToDifferentLocalVariable() { + final Slot slot = Slot.create(Integer.class); + this.context.store(slot.write(), 42); + final IincInsnNode node = new IincInsnNode(42 + 1, 1); + assertFalse(incrementsVariable(slot.read()).test(this.context,node)); + } + + @Test + public void shouldCaptureIStoreVariable() { + final Slot slot = Slot.create(Integer.class); + final VarInsnNode node = new VarInsnNode(Opcodes.ISTORE, 3); + assertTrue(anIStore(slot.write()).test(this.context,node)); + assertThat(this.context.retrieve(slot.read())).isEqualTo(Optional.ofNullable(3)); + } + + @Test + public void shouldMatchAgainstCapturedIStoreVariable() { + final Slot slot = Slot.create(Integer.class); + this.context.store(slot.write(), 3); + final VarInsnNode matchingNode = new VarInsnNode(Opcodes.ISTORE, 3); + assertTrue(anIStoreTo(slot.read()).test(this.context,matchingNode)); + + final VarInsnNode nonMatchingNode = new VarInsnNode(Opcodes.ISTORE, 4); + assertFalse(anIStoreTo(slot.read()).test(this.context,nonMatchingNode)); + } + + @Test + public void shouldMatchAgainstCapturedILoadVariable() { + final Slot slot = Slot.create(Integer.class); + this.context.store(slot.write(), 3); + final VarInsnNode matchingNode = new VarInsnNode(Opcodes.ILOAD, 3); + assertTrue(anILoadOf(slot.read()).test(this.context,matchingNode)); + + final VarInsnNode nonMatchingNode = new VarInsnNode(Opcodes.ILOAD, 4); + assertFalse(anILoadOf(slot.read()).test(this.context,nonMatchingNode)); + } + + @Test + public void shouldMatchAllIntegerConstants() { + assertFalse(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ACONST_NULL)))); + assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_M1)))); + assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_0)))); + assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_1)))); + assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_2)))); + assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_3)))); + assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_4)))); + assertTrue(anIntegerConstant().test(this.context,(new InsnNode(Opcodes.ICONST_5)))); + } + + @Test + public void shouldCaptureLabels() { + final Slot slot = Slot.create(LabelNode.class); + final LabelNode label = new LabelNode(); + assertFalse(aLabelNode(slot.write()).test(this.context,new InsnNode(Opcodes.NULL))); + assertTrue(aLabelNode(slot.write()).test(this.context,label)); + assertThat(this.context.retrieve(slot.read())).isEqualTo(Optional.ofNullable(label)); + } + + @Test + public void shouldMatchJumps() { + assertTrue(aJump().test(this.context,new JumpInsnNode(Opcodes.GOTO, null))); + assertFalse(aJump().test(this.context, new InsnNode(Opcodes.ACONST_NULL))); + } + + @Test + public void shouldMatchConditionalJumps() { + assertFalse(aConditionalJump().test(this.context,new JumpInsnNode(Opcodes.GOTO, null))); + assertFalse(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.JSR, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFEQ, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFNE, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFLT, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFGE, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFGT, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFLE, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPEQ, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPNE, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPLT, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPGE, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPGT, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ICMPLE, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ACMPEQ, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IF_ACMPNE, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFNULL, null))); + assertTrue(aConditionalJump().test(this.context, new JumpInsnNode(Opcodes.IFNONNULL, null))); + } + + @Test + public void shouldMatchMethodCallByOwnerAndName() { + final ClassName clazz = ClassName.fromString("clazz"); + assertTrue(methodCallTo(clazz, "name") + .test(this.context, new MethodInsnNode(Opcodes.INVOKEINTERFACE, "clazz", "name", "desc", true))); + assertFalse(methodCallTo(clazz, "name") + .test(this.context, new MethodInsnNode(Opcodes.INVOKEINTERFACE, "clazz", "notName", "desc", true))); + assertFalse(methodCallTo(clazz, "name") + .test(this.context, new MethodInsnNode(Opcodes.INVOKEINTERFACE, "notClazz", "name", "desc", true))); + } +} diff --git a/pitest-entry/src/test/java/org/pitest/classinfo/AddlerHashTest.java b/pitest-entry/src/test/java/org/pitest/classinfo/AddlerHashTest.java index 537db45cc..a82568662 100644 --- a/pitest-entry/src/test/java/org/pitest/classinfo/AddlerHashTest.java +++ b/pitest-entry/src/test/java/org/pitest/classinfo/AddlerHashTest.java @@ -1,43 +1,43 @@ -package org.pitest.classinfo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.Serializable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.coverage.codeassist.ClassUtils; - -public class AddlerHashTest { - - private AddlerHash testee; - - @Before - public void setUp() { - this.testee = new AddlerHash(); - } - - @Test - public void shouldCreateChecksumOfSuppliedBytes() - throws ClassNotFoundException { - assertTrue(this.testee.hash(ClassUtils.classAsBytes(String.class)) != 0); - } - - @Test - public void shouldGenerateSameHashForSameInput() - throws ClassNotFoundException { - final long expected = this.testee.hash(ClassUtils - .classAsBytes(String.class)); - assertEquals(expected, - this.testee.hash(ClassUtils.classAsBytes(String.class))); - } - - @Test - public void shouldCreateDifferentHashesForDifferentClasses() - throws ClassNotFoundException { - assertTrue(this.testee.hash(ClassUtils.classAsBytes(Comparable.class)) != this.testee - .hash(ClassUtils.classAsBytes(Serializable.class))); - } - -} +package org.pitest.classinfo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.Serializable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.coverage.codeassist.ClassUtils; + +public class AddlerHashTest { + + private AddlerHash testee; + + @Before + public void setUp() { + this.testee = new AddlerHash(); + } + + @Test + public void shouldCreateChecksumOfSuppliedBytes() + throws ClassNotFoundException { + assertTrue(this.testee.hash(ClassUtils.classAsBytes(String.class)) != 0); + } + + @Test + public void shouldGenerateSameHashForSameInput() + throws ClassNotFoundException { + final long expected = this.testee.hash(ClassUtils + .classAsBytes(String.class)); + assertEquals(expected, + this.testee.hash(ClassUtils.classAsBytes(String.class))); + } + + @Test + public void shouldCreateDifferentHashesForDifferentClasses() + throws ClassNotFoundException { + assertTrue(this.testee.hash(ClassUtils.classAsBytes(Comparable.class)) != this.testee + .hash(ClassUtils.classAsBytes(Serializable.class))); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/classinfo/ClassInfoMother.java b/pitest-entry/src/test/java/org/pitest/classinfo/ClassInfoMother.java index b46b77e33..a0b9f9a4a 100644 --- a/pitest-entry/src/test/java/org/pitest/classinfo/ClassInfoMother.java +++ b/pitest-entry/src/test/java/org/pitest/classinfo/ClassInfoMother.java @@ -1,41 +1,41 @@ -package org.pitest.classinfo; - -import org.pitest.quickbuilder.Builder; - -public class ClassInfoMother { - - interface ClassInfoBuilderf extends Builder { - ClassInfoBuilder withId(Builder id); - } - - public static ClassInfo make(final ClassIdentifier id) { - return make(id, new DefaultClassPointer(null)); - } - - public static ClassInfo make(final ClassIdentifier id, final ClassInfo parent) { - return make(id, new DefaultClassPointer(parent)); - } - - public static ClassInfo make(final ClassIdentifier id, - final ClassPointer parent) { - final ClassInfoBuilder data = new ClassInfoBuilder(); - data.id = id; - return new ClassInfo(parent, new DefaultClassPointer(null), data); - } - - public static ClassInfo make(final ClassName name) { - return make(new ClassIdentifier(1, name)); - } - - public static ClassInfo make(final ClassName name, final String fileName) { - final DefaultClassPointer parent = new DefaultClassPointer(null); - final ClassInfoBuilder data = new ClassInfoBuilder(); - data.id = new ClassIdentifier(1, name); - data.sourceFile = fileName; - return new ClassInfo(parent, new DefaultClassPointer(null), data); - } - - public static ClassInfo make(final String name) { - return make(new ClassIdentifier(1, ClassName.fromString(name))); - } -} +package org.pitest.classinfo; + +import org.pitest.quickbuilder.Builder; + +public class ClassInfoMother { + + interface ClassInfoBuilderf extends Builder { + ClassInfoBuilder withId(Builder id); + } + + public static ClassInfo make(final ClassIdentifier id) { + return make(id, new DefaultClassPointer(null)); + } + + public static ClassInfo make(final ClassIdentifier id, final ClassInfo parent) { + return make(id, new DefaultClassPointer(parent)); + } + + public static ClassInfo make(final ClassIdentifier id, + final ClassPointer parent) { + final ClassInfoBuilder data = new ClassInfoBuilder(); + data.id = id; + return new ClassInfo(parent, new DefaultClassPointer(null), data); + } + + public static ClassInfo make(final ClassName name) { + return make(new ClassIdentifier(1, name)); + } + + public static ClassInfo make(final ClassName name, final String fileName) { + final DefaultClassPointer parent = new DefaultClassPointer(null); + final ClassInfoBuilder data = new ClassInfoBuilder(); + data.id = new ClassIdentifier(1, name); + data.sourceFile = fileName; + return new ClassInfo(parent, new DefaultClassPointer(null), data); + } + + public static ClassInfo make(final String name) { + return make(new ClassIdentifier(1, ClassName.fromString(name))); + } +} diff --git a/pitest-entry/src/test/java/org/pitest/classinfo/ClassInfoTest.java b/pitest-entry/src/test/java/org/pitest/classinfo/ClassInfoTest.java index 1958b3d79..c0e806b5b 100644 --- a/pitest-entry/src/test/java/org/pitest/classinfo/ClassInfoTest.java +++ b/pitest-entry/src/test/java/org/pitest/classinfo/ClassInfoTest.java @@ -1,124 +1,124 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.objectweb.asm.Opcodes; -import java.util.Optional; - -public class ClassInfoTest { - - private ClassInfoBuilder data; - private ClassInfo testee; - - @Before - public void setUp() { - this.data = new ClassInfoBuilder(); - this.data.id = new ClassIdentifier(1, ClassName.fromString("foo")); - } - - @Test - public void shouldCreateDifferentHierarchicalHashWhenParentClassChanges() { - final ClassInfo parent = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - final ClassInfo classA = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - final ClassInfo classB = new ClassInfo(pointerTo(parent), - emptyClassPointer(), this.data); - - assertFalse(classA.getHierarchicalId().getHierarchicalHash() - .equals(classB.getHierarchicalId().getHierarchicalHash())); - } - - @Test - public void shouldCreateDifferentHierarchicalHashWhenOuterClassChanges() { - final ClassInfo outer = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - final ClassInfo classA = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - final ClassInfo classB = new ClassInfo(emptyClassPointer(), - pointerTo(outer), this.data); - - assertFalse(classA.getHierarchicalId().getHierarchicalHash() - .equals(classB.getHierarchicalId().getHierarchicalHash())); - } - - @Test - public void shouldReportWhenClassIsSynthetic() { - this.data.access = Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC; - final ClassInfo testee = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - assertTrue(testee.isSynthetic()); - } - - @Test - public void shouldReportWhenClassIsNotSynthetic() { - this.data.access = Opcodes.ACC_PUBLIC; - final ClassInfo testee = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - assertFalse(testee.isSynthetic()); - } - - private ClassPointer emptyClassPointer() { - return () -> Optional.empty(); - } - - private ClassPointer pointerTo(final ClassInfo ci) { - return () -> Optional.ofNullable(ci); - } - - @Test - public void isCodeLineReturnShouldTrueForCodeLines() { - final List codeLines = Arrays.asList(1, 2, 3, 4, 5, 6, 10); - addCodeLines(codeLines); - makeTestee(); - for (final int each : codeLines) { - assertTrue(this.testee.isCodeLine(each)); - } - } - - @Test - public void isCodeLineShouldReturnFalseForNonCodeLines() { - final List codeLines = Arrays.asList(1); - addCodeLines(codeLines); - makeTestee(); - assertFalse(this.testee.isCodeLine(2)); - } - - @Test - public void matchIfAbstractShouldReturnTrueForAbstractClasses() { - this.data.access = Opcodes.ACC_ABSTRACT; - makeTestee(); - assertTrue(ClassInfo.matchIfAbstract().test(this.testee)); - } - - private void makeTestee() { - this.testee = new ClassInfo(null, null, this.data); - } - - private void addCodeLines(final List lines) { - for (final int each : lines) { - this.data.registerCodeLine(each); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.objectweb.asm.Opcodes; +import java.util.Optional; + +public class ClassInfoTest { + + private ClassInfoBuilder data; + private ClassInfo testee; + + @Before + public void setUp() { + this.data = new ClassInfoBuilder(); + this.data.id = new ClassIdentifier(1, ClassName.fromString("foo")); + } + + @Test + public void shouldCreateDifferentHierarchicalHashWhenParentClassChanges() { + final ClassInfo parent = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + final ClassInfo classA = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + final ClassInfo classB = new ClassInfo(pointerTo(parent), + emptyClassPointer(), this.data); + + assertFalse(classA.getHierarchicalId().getHierarchicalHash() + .equals(classB.getHierarchicalId().getHierarchicalHash())); + } + + @Test + public void shouldCreateDifferentHierarchicalHashWhenOuterClassChanges() { + final ClassInfo outer = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + final ClassInfo classA = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + final ClassInfo classB = new ClassInfo(emptyClassPointer(), + pointerTo(outer), this.data); + + assertFalse(classA.getHierarchicalId().getHierarchicalHash() + .equals(classB.getHierarchicalId().getHierarchicalHash())); + } + + @Test + public void shouldReportWhenClassIsSynthetic() { + this.data.access = Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC; + final ClassInfo testee = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + assertTrue(testee.isSynthetic()); + } + + @Test + public void shouldReportWhenClassIsNotSynthetic() { + this.data.access = Opcodes.ACC_PUBLIC; + final ClassInfo testee = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + assertFalse(testee.isSynthetic()); + } + + private ClassPointer emptyClassPointer() { + return () -> Optional.empty(); + } + + private ClassPointer pointerTo(final ClassInfo ci) { + return () -> Optional.ofNullable(ci); + } + + @Test + public void isCodeLineReturnShouldTrueForCodeLines() { + final List codeLines = Arrays.asList(1, 2, 3, 4, 5, 6, 10); + addCodeLines(codeLines); + makeTestee(); + for (final int each : codeLines) { + assertTrue(this.testee.isCodeLine(each)); + } + } + + @Test + public void isCodeLineShouldReturnFalseForNonCodeLines() { + final List codeLines = Arrays.asList(1); + addCodeLines(codeLines); + makeTestee(); + assertFalse(this.testee.isCodeLine(2)); + } + + @Test + public void matchIfAbstractShouldReturnTrueForAbstractClasses() { + this.data.access = Opcodes.ACC_ABSTRACT; + makeTestee(); + assertTrue(ClassInfo.matchIfAbstract().test(this.testee)); + } + + private void makeTestee() { + this.testee = new ClassInfo(null, null, this.data); + } + + private void addCodeLines(final List lines) { + for (final int each : lines) { + this.data.registerCodeLine(each); + } + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/classinfo/NameToClassInfoTest.java b/pitest-entry/src/test/java/org/pitest/classinfo/NameToClassInfoTest.java index c36518b1c..fb55b12ae 100644 --- a/pitest-entry/src/test/java/org/pitest/classinfo/NameToClassInfoTest.java +++ b/pitest-entry/src/test/java/org/pitest/classinfo/NameToClassInfoTest.java @@ -1,18 +1,18 @@ -package org.pitest.classinfo; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import org.junit.Test; - -public class NameToClassInfoTest { - - @Test - public void shouldFetchClassWhenApplied() { - final Repository repository = mock(Repository.class); - final NameToClassInfo testee = new NameToClassInfo(repository); - testee.apply(ClassName.fromString("foo")); - verify(repository).fetchClass(ClassName.fromString("foo")); - } - -} +package org.pitest.classinfo; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import org.junit.Test; + +public class NameToClassInfoTest { + + @Test + public void shouldFetchClassWhenApplied() { + final Repository repository = mock(Repository.class); + final NameToClassInfo testee = new NameToClassInfo(repository); + testee.apply(ClassName.fromString("foo")); + verify(repository).fetchClass(ClassName.fromString("foo")); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/classinfo/RepositoryTest.java b/pitest-entry/src/test/java/org/pitest/classinfo/RepositoryTest.java index 81f79a857..b41ed76bf 100644 --- a/pitest-entry/src/test/java/org/pitest/classinfo/RepositoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/classinfo/RepositoryTest.java @@ -1,291 +1,291 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.Serializable; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.coverage.codeassist.ClassUtils; -import java.util.Optional; -import org.pitest.util.IsolationUtils; - -public class RepositoryTest { - - private Repository testee; - - @Mock - private ClassByteArraySource source; - - @Mock - private HashFunction hashFunction; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new Repository(new ClassloaderByteArraySource( - IsolationUtils.getContextClassLoader()), this.hashFunction); - } - - @Test - public void shouldReturnTrueWhenAskedForKnownClass() { - assertTrue(this.testee.hasClass(ClassName.fromClass(Integer.class))); - } - - @Test - public void shouldReturnFalseWhenAskedForUnknownClass() { - assertFalse(this.testee.hasClass(ClassName.fromString("never.heard.of.you"))); - } - - @Test - public void shouldOnlyCheckSourceForUnknownClassesOnce() { - this.testee = new Repository(this.source); - when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); - this.testee.hasClass(ClassName.fromString("foo")); - this.testee.hasClass(ClassName.fromString("foo")); - verify(this.source, times(1)).getBytes("foo"); - } - - @Test - public void shouldReturnNoneWhenAskedForUnknownClass() { - assertEquals(Optional.empty(), - this.testee.fetchClass(ClassName.fromString("never.heard.of.you"))); - } - - @Test - public void shouldOnlyLookForUnknownClassesOnce() { - this.testee = new Repository(this.source); - when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); - this.testee.fetchClass(ClassName.fromString("foo")); - this.testee.fetchClass(ClassName.fromString("foo")); - verify(this.source, times(1)).getBytes("foo"); - } - - @Test - public void shouldOnlyQuerySourceForAnUnknownClassOnce() { - this.testee = new Repository(this.source); - when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); - this.testee.hasClass(ClassName.fromString("foo")); - this.testee.fetchClass(ClassName.fromString("foo")); - verify(this.source, times(1)).getBytes("foo"); - } - - @Test - public void shouldReturnInfoForClassOnClassPath() { - assertTrue(this.testee.fetchClass(Integer.class).isPresent()); - } - - @Test - public void shouldOnlyLookForKnownClassOnce() throws ClassNotFoundException { - this.testee = new Repository(this.source); - when(this.source.getBytes(anyString())).thenReturn( - Optional.ofNullable(ClassUtils.classAsBytes(String.class))); - this.testee.fetchClass(ClassName.fromString("foo")); - this.testee.fetchClass(ClassName.fromString("foo")); - verify(this.source, times(1)).getBytes("foo"); - } - - @Test - public void shouldDetectInterfacesAsInterfaces() { - final Optional anInterface = this.testee - .fetchClass(Serializable.class); - assertTrue(anInterface.get().isInterface()); - } - - @Test - public void shouldDetectInterfacesAsAbstract() { - final Optional anInterface = this.testee - .fetchClass(Serializable.class); - assertTrue(anInterface.get().isAbstract()); - } - - @Test - public void shouldDetectConcreteClassesAsNotInterfaces() { - final Optional aClass = this.testee.fetchClass(String.class); - assertFalse(aClass.get().isInterface()); - } - - @Test - public void shouldDetectConcreteClassesAsNotAbstract() { - final Optional aClass = this.testee.fetchClass(String.class); - assertFalse(aClass.get().isAbstract()); - } - - public static class SimpleInnerClass { - - } - - @Test - public void shouldReportOuterClassForStaticInnerClasses() { - final String actual = getOuterClassNameFor(SimpleInnerClass.class); - assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); - } - - @Test - public void shouldReportOuterClassForLocalClasses() { - final Object local = new Object() { - - }; - - final String actual = getOuterClassNameFor(local.getClass()); - assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); - } - - public class NonStaticInnerClass { - - } - - @Test - public void shouldReportOuterClassForNonStaticInnerClasses() { - final String actual = getOuterClassNameFor(NonStaticInnerClass.class); - assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); - } - - public static class OuterStaticInnerClass { - public static class InnerStaticClass { - - } - } - - @Test - public void shouldReportInnermstOuterClassForNestedInnerClasses() { - final String actual = getOuterClassNameFor(OuterStaticInnerClass.InnerStaticClass.class); - assertEquals( - RepositoryTest.OuterStaticInnerClass.class.getName().replace(".", "/"), - actual); - } - - static class Foo { - - } - - static class Bar extends Foo { - - } - - @Test - public void shouldReportSuperClass() { - final Optional aClass = this.testee.fetchClass(Bar.class); - assertEquals(ClassName.fromClass(Foo.class), aClass.get().getSuperClass() - .get().getName()); - } - - @Test - public void shouldReportSuperClassAsObjectWhenNoneDeclared() { - final Optional aClass = this.testee.fetchClass(Foo.class); - assertEquals(ClassName.fromClass(Object.class), aClass.get().getSuperClass() - .get().getName()); - } - - @Test - public void shouldReportNoSuperClassForObject() { - final Optional aClass = this.testee.fetchClass(Object.class); - assertEquals(Optional.empty(), aClass.get().getSuperClass()); - } - - @Test - public void shouldReportCodeLines() { - final Optional aClass = this.testee - .fetchClass(RepositoryTest.class); - aClass.get().isCodeLine(139); // flakey - } - - @Ignore - static class Annotated { - - } - - @Test - public void shouldRecordClassLevelAnnotations() { - final Optional aClass = this.testee.fetchClass(Annotated.class); - assertTrue(aClass.get().hasAnnotation(Ignore.class)); - } - - static class HasAnnotatedMethod { - @Test - public void foo() { - - } - } - - @Test - public void shouldRecordMethodLevelAnnotations() { - final Optional aClass = this.testee - .fetchClass(HasAnnotatedMethod.class); - assertTrue(aClass.get().hasAnnotation(Test.class)); - } - - static interface ITop { - - } - - static class Top implements ITop { - - } - - static class Middle extends Top { - - } - - static class Bottom extends Middle { - - } - - @Test - public void shouldCorrectlyNegotiateClassHierachies() { - final Optional aClass = this.testee.fetchClass(Bottom.class); - assertTrue(aClass.get().descendsFrom(Middle.class)); - assertTrue(aClass.get().descendsFrom(Top.class)); - assertTrue(aClass.get().descendsFrom(Object.class)); - assertFalse(aClass.get().descendsFrom(String.class)); - } - - @Test - public void doesNotTreatInterfacesAsPartOfClassHierachy() { - final Optional aClass = this.testee.fetchClass(Bottom.class); - assertFalse(aClass.get().descendsFrom(ITop.class)); - } - - @Test - public void shouldRecordSourceFile() { - final Optional aClass = this.testee.fetchClass(String.class); - assertEquals("String.java", aClass.get().getSourceFileName()); - } - - @Test - public void shouldCalculateHashForSuppledClass() { - this.testee.fetchClass(String.class); - verify(this.hashFunction).hash(any(byte[].class)); - } - - private String getOuterClassNameFor(final Class clazz) { - return this.testee.fetchClass(clazz).get().getOuterClass().get() - .getName().asInternalName(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.Serializable; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.coverage.codeassist.ClassUtils; +import java.util.Optional; +import org.pitest.util.IsolationUtils; + +public class RepositoryTest { + + private Repository testee; + + @Mock + private ClassByteArraySource source; + + @Mock + private HashFunction hashFunction; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new Repository(new ClassloaderByteArraySource( + IsolationUtils.getContextClassLoader()), this.hashFunction); + } + + @Test + public void shouldReturnTrueWhenAskedForKnownClass() { + assertTrue(this.testee.hasClass(ClassName.fromClass(Integer.class))); + } + + @Test + public void shouldReturnFalseWhenAskedForUnknownClass() { + assertFalse(this.testee.hasClass(ClassName.fromString("never.heard.of.you"))); + } + + @Test + public void shouldOnlyCheckSourceForUnknownClassesOnce() { + this.testee = new Repository(this.source); + when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); + this.testee.hasClass(ClassName.fromString("foo")); + this.testee.hasClass(ClassName.fromString("foo")); + verify(this.source, times(1)).getBytes("foo"); + } + + @Test + public void shouldReturnNoneWhenAskedForUnknownClass() { + assertEquals(Optional.empty(), + this.testee.fetchClass(ClassName.fromString("never.heard.of.you"))); + } + + @Test + public void shouldOnlyLookForUnknownClassesOnce() { + this.testee = new Repository(this.source); + when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); + this.testee.fetchClass(ClassName.fromString("foo")); + this.testee.fetchClass(ClassName.fromString("foo")); + verify(this.source, times(1)).getBytes("foo"); + } + + @Test + public void shouldOnlyQuerySourceForAnUnknownClassOnce() { + this.testee = new Repository(this.source); + when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); + this.testee.hasClass(ClassName.fromString("foo")); + this.testee.fetchClass(ClassName.fromString("foo")); + verify(this.source, times(1)).getBytes("foo"); + } + + @Test + public void shouldReturnInfoForClassOnClassPath() { + assertTrue(this.testee.fetchClass(Integer.class).isPresent()); + } + + @Test + public void shouldOnlyLookForKnownClassOnce() throws ClassNotFoundException { + this.testee = new Repository(this.source); + when(this.source.getBytes(anyString())).thenReturn( + Optional.ofNullable(ClassUtils.classAsBytes(String.class))); + this.testee.fetchClass(ClassName.fromString("foo")); + this.testee.fetchClass(ClassName.fromString("foo")); + verify(this.source, times(1)).getBytes("foo"); + } + + @Test + public void shouldDetectInterfacesAsInterfaces() { + final Optional anInterface = this.testee + .fetchClass(Serializable.class); + assertTrue(anInterface.get().isInterface()); + } + + @Test + public void shouldDetectInterfacesAsAbstract() { + final Optional anInterface = this.testee + .fetchClass(Serializable.class); + assertTrue(anInterface.get().isAbstract()); + } + + @Test + public void shouldDetectConcreteClassesAsNotInterfaces() { + final Optional aClass = this.testee.fetchClass(String.class); + assertFalse(aClass.get().isInterface()); + } + + @Test + public void shouldDetectConcreteClassesAsNotAbstract() { + final Optional aClass = this.testee.fetchClass(String.class); + assertFalse(aClass.get().isAbstract()); + } + + public static class SimpleInnerClass { + + } + + @Test + public void shouldReportOuterClassForStaticInnerClasses() { + final String actual = getOuterClassNameFor(SimpleInnerClass.class); + assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); + } + + @Test + public void shouldReportOuterClassForLocalClasses() { + final Object local = new Object() { + + }; + + final String actual = getOuterClassNameFor(local.getClass()); + assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); + } + + public class NonStaticInnerClass { + + } + + @Test + public void shouldReportOuterClassForNonStaticInnerClasses() { + final String actual = getOuterClassNameFor(NonStaticInnerClass.class); + assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); + } + + public static class OuterStaticInnerClass { + public static class InnerStaticClass { + + } + } + + @Test + public void shouldReportInnermstOuterClassForNestedInnerClasses() { + final String actual = getOuterClassNameFor(OuterStaticInnerClass.InnerStaticClass.class); + assertEquals( + RepositoryTest.OuterStaticInnerClass.class.getName().replace(".", "/"), + actual); + } + + static class Foo { + + } + + static class Bar extends Foo { + + } + + @Test + public void shouldReportSuperClass() { + final Optional aClass = this.testee.fetchClass(Bar.class); + assertEquals(ClassName.fromClass(Foo.class), aClass.get().getSuperClass() + .get().getName()); + } + + @Test + public void shouldReportSuperClassAsObjectWhenNoneDeclared() { + final Optional aClass = this.testee.fetchClass(Foo.class); + assertEquals(ClassName.fromClass(Object.class), aClass.get().getSuperClass() + .get().getName()); + } + + @Test + public void shouldReportNoSuperClassForObject() { + final Optional aClass = this.testee.fetchClass(Object.class); + assertEquals(Optional.empty(), aClass.get().getSuperClass()); + } + + @Test + public void shouldReportCodeLines() { + final Optional aClass = this.testee + .fetchClass(RepositoryTest.class); + aClass.get().isCodeLine(139); // flakey + } + + @Ignore + static class Annotated { + + } + + @Test + public void shouldRecordClassLevelAnnotations() { + final Optional aClass = this.testee.fetchClass(Annotated.class); + assertTrue(aClass.get().hasAnnotation(Ignore.class)); + } + + static class HasAnnotatedMethod { + @Test + public void foo() { + + } + } + + @Test + public void shouldRecordMethodLevelAnnotations() { + final Optional aClass = this.testee + .fetchClass(HasAnnotatedMethod.class); + assertTrue(aClass.get().hasAnnotation(Test.class)); + } + + static interface ITop { + + } + + static class Top implements ITop { + + } + + static class Middle extends Top { + + } + + static class Bottom extends Middle { + + } + + @Test + public void shouldCorrectlyNegotiateClassHierachies() { + final Optional aClass = this.testee.fetchClass(Bottom.class); + assertTrue(aClass.get().descendsFrom(Middle.class)); + assertTrue(aClass.get().descendsFrom(Top.class)); + assertTrue(aClass.get().descendsFrom(Object.class)); + assertFalse(aClass.get().descendsFrom(String.class)); + } + + @Test + public void doesNotTreatInterfacesAsPartOfClassHierachy() { + final Optional aClass = this.testee.fetchClass(Bottom.class); + assertFalse(aClass.get().descendsFrom(ITop.class)); + } + + @Test + public void shouldRecordSourceFile() { + final Optional aClass = this.testee.fetchClass(String.class); + assertEquals("String.java", aClass.get().getSourceFileName()); + } + + @Test + public void shouldCalculateHashForSuppledClass() { + this.testee.fetchClass(String.class); + verify(this.hashFunction).hash(any(byte[].class)); + } + + private String getOuterClassNameFor(final Class clazz) { + return this.testee.fetchClass(clazz).get().getOuterClass().get() + .getName().asInternalName(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/classinfo/TestToClassMapperTest.java b/pitest-entry/src/test/java/org/pitest/classinfo/TestToClassMapperTest.java index 3fc78f01e..5f2d976b9 100644 --- a/pitest-entry/src/test/java/org/pitest/classinfo/TestToClassMapperTest.java +++ b/pitest-entry/src/test/java/org/pitest/classinfo/TestToClassMapperTest.java @@ -1,68 +1,68 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import java.util.Optional; - -public class TestToClassMapperTest { - - @Mock - private ClassByteArraySource source; - - private Repository repository; - - private TestToClassMapper testee; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.repository = new Repository(this.source); - this.testee = new TestToClassMapper(this.repository); - } - - @Test - public void shouldMapTestsPostfixedWithTestToTesteeWhenTesteeExists() { - final byte[] bytes = { 0 }; - when(this.source.getBytes("com.example.Foo")) - .thenReturn(Optional.ofNullable(bytes)); - assertEquals(ClassName.fromString("com.example.Foo"), - this.testee.findTestee("com.example.FooTest").get()); - } - - @Test - public void shouldMapTestsPrefixedWithTestToTesteeWhenTesteeExists() { - final byte[] bytes = { 0 }; - when(this.source.getBytes("com.example.Foo")) - .thenReturn(Optional.ofNullable(bytes)); - assertEquals(ClassName.fromString("com.example.Foo"), - this.testee.findTestee("com.example.TestFoo").get()); - } - - @Test - public void shouldReturnNoneWhenNoTesteeExistsMatchingNamingConvention() { - final byte[] bytes = null; - when(this.source.getBytes("com.example.Foo")) - .thenReturn(Optional.ofNullable(bytes)); - assertEquals(Optional.empty(), this.testee.findTestee("com.example.TestFoo")); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import java.util.Optional; + +public class TestToClassMapperTest { + + @Mock + private ClassByteArraySource source; + + private Repository repository; + + private TestToClassMapper testee; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.repository = new Repository(this.source); + this.testee = new TestToClassMapper(this.repository); + } + + @Test + public void shouldMapTestsPostfixedWithTestToTesteeWhenTesteeExists() { + final byte[] bytes = { 0 }; + when(this.source.getBytes("com.example.Foo")) + .thenReturn(Optional.ofNullable(bytes)); + assertEquals(ClassName.fromString("com.example.Foo"), + this.testee.findTestee("com.example.FooTest").get()); + } + + @Test + public void shouldMapTestsPrefixedWithTestToTesteeWhenTesteeExists() { + final byte[] bytes = { 0 }; + when(this.source.getBytes("com.example.Foo")) + .thenReturn(Optional.ofNullable(bytes)); + assertEquals(ClassName.fromString("com.example.Foo"), + this.testee.findTestee("com.example.TestFoo").get()); + } + + @Test + public void shouldReturnNoneWhenNoTesteeExistsMatchingNamingConvention() { + final byte[] bytes = null; + when(this.source.getBytes("com.example.Foo")) + .thenReturn(Optional.ofNullable(bytes)); + assertEquals(Optional.empty(), this.testee.findTestee("com.example.TestFoo")); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/coverage/CoverageDataTest.java b/pitest-entry/src/test/java/org/pitest/coverage/CoverageDataTest.java index 2beb03ea5..bd71c8a7f 100644 --- a/pitest-entry/src/test/java/org/pitest/coverage/CoverageDataTest.java +++ b/pitest-entry/src/test/java/org/pitest/coverage/CoverageDataTest.java @@ -1,303 +1,303 @@ -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.coverage; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.pitest.coverage.CoverageMother.aBlockLocation; -import static org.pitest.coverage.CoverageMother.aCoverageResult; -import static org.pitest.mutationtest.LocationMother.aLocation; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Function; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassInfoMother; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.CoverageMother.BlockLocationBuilder; -import org.pitest.coverage.CoverageMother.CoverageResultBuilder; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.testapi.Description; - -public class CoverageDataTest { - - private CoverageData testee; - - @Mock - private CodeSource code; - - @Mock - private LineMap lm; - - private final ClassName foo = ClassName.fromString("foo"); - private final ClassName bar = ClassName.fromString("bar"); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - when(this.lm.mapLines(any(ClassName.class))).thenReturn( - new HashMap>()); - when(this.code.findTestee(any())).thenReturn(Optional.empty()); - this.testee = new CoverageData(this.code, this.lm); - } - - @Test - public void shouldReturnNoTestsWhenNoTestsCoverALine() { - when(this.lm.mapLines(any(ClassName.class))).thenReturn( - new HashMap>()); - final ClassLine line = new ClassLine("foo", 1); - assertEquals(Collections.emptyList(), - this.testee.getTestsForClassLine(line)); - } - - @Test - public void shouldStoreExecutionTimesOfTests() { - - final int line = 1; - final int time = 42; - - final BlockLocationBuilder block = aBlockLocation().withLocation( - aLocation().withClass(this.foo)); - when(this.lm.mapLines(any(ClassName.class))).thenReturn( - makeCoverageMapForBlock(block, line)); - - final CoverageResultBuilder cr = aCoverageResult().withVisitedBlocks( - block.build(1)).withExecutionTime(time); - - this.testee.calculateClassCoverage(cr.build()); - - assertEquals(Arrays.asList(42), FCollection.map( - this.testee.getTestsForClassLine(new ClassLine(this.foo, line)), - testInfoToExecutionTime())); - } - - @Test - public void shouldReportNumberOfCoveredLinesWhenNoneCovered() { - assertEquals(0, this.testee.getNumberOfCoveredLines(Collections - .singletonList(ClassName.fromString("foo")))); - } - - @Test - public void shouldReportNumberOfCoveredLinesWhenSomeCovered() { - - final BlockLocationBuilder block = aBlockLocation().withLocation( - aLocation().withClass(this.foo)); - when(this.lm.mapLines(any(ClassName.class))).thenReturn( - makeCoverageMapForBlock(block, 101, 300)); - - final CoverageResultBuilder cr = aCoverageResult().withVisitedBlocks( - block.build(1)); - - this.testee.calculateClassCoverage(cr.build()); - - assertEquals(2, this.testee.getNumberOfCoveredLines(Collections - .singletonList(this.foo))); - } - - @Test - public void shouldReturnNotTestsWhenNoTestsCoverClass() { - assertTrue(this.testee.getTestsForClass(this.foo).isEmpty()); - } - - @Test - public void shouldReturnUniqueTestsForClassWhenSomeTestsCoverClass() { - this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 0, - 1)); - this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 0, - 2)); - this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest2", 0, - 2)); - assertEquals(Arrays.asList("fooTest", "fooTest2"), FCollection.map( - this.testee.getTestsForClass(this.foo), testInfoToString())); - } - - @Test - public void shouldReportAGreenSuiteWhenNoTestHasFailed() { - this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 42, - 1)); - assertTrue(this.testee.allTestsGreen()); - } - - @Test - public void shouldNotReportAGreenSuiteWhenATestHasFailed() { - this.testee.calculateClassCoverage(makeCoverageResult("foo", - new Description("fooTest"), 42, 1, false)); - assertFalse(this.testee.allTestsGreen()); - } - - @Test - public void shouldProvideAccessToClassData() { - final Collection classes = Arrays.asList(ClassName - .fromString("foo")); - this.testee.getClassInfo(classes); - verify(this.code).getClassInfo(classes); - } - - @Test - public void shouldReturnCoverageIdOf0WhenNoTestsCoverClass() { - assertEquals(0, - this.testee.getCoverageIdForClass(ClassName.fromString("unknown")) - .longValue()); - } - - @Test - public void shouldReturnNonZeroCoverageIdWhenTestsCoverClass() { - - final ClassName foo = ClassName.fromString("Foo"); - final ClassInfo ci = ClassInfoMother.make(foo); - - when(this.code.getClassInfo(any(Collection.class))).thenReturn( - Collections.singletonList(ci)); - - final BlockLocationBuilder block = aBlockLocation().withLocation( - aLocation().withClass(foo)); - final HashMap> map = makeCoverageMapForBlock(block, - 42); - when(this.lm.mapLines(any(ClassName.class))).thenReturn(map); - this.testee.calculateClassCoverage(aCoverageResult().withVisitedBlocks( - block.build(1)).build()); - - assertThat(this.testee.getCoverageIdForClass(foo).longValue()) - .isNotEqualTo(0); - - } - - @Test - public void shouldProvideEmptyBlockCoverageListWhenNoCoverage() { - assertEquals(Collections.emptyList(), this.testee.createCoverage()); - } - - @Test - public void shouldProvideCoverageListWhenCoverageRecorded() { - - final BlockLocationBuilder block = aBlockLocation().withLocation( - aLocation().withClass(this.foo)); - final CoverageResultBuilder cr = aCoverageResult().withVisitedBlocks( - block.build(1)); - - this.testee.calculateClassCoverage(cr.build()); - - this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 0, - 1)); - final BlockCoverage actual = this.testee.createCoverage().get(0); - assertEquals(block.build(), actual.getBlock()); - assertThat(actual.getTests()).contains("FooTest.fooTest"); - } - - @Test - public void shouldProvideListOfClassesForSourceFile() { - - final ClassInfo fooClass = ClassInfoMother.make(this.foo, "foo.java"); - final ClassInfo barClass = ClassInfoMother.make(this.bar, "bar.java"); - final Collection classes = Arrays.asList(fooClass, barClass); - when(this.code.getCode()).thenReturn(classes); - - this.testee = new CoverageData(this.code, this.lm); - - assertEquals(Arrays.asList(barClass), - this.testee.getClassesForFile("bar.java", "")); - } - - @Test - public void shouldMatchPackageWhenFindingSources() { - final ClassName foo1 = ClassName.fromString("a.b.c.foo"); - final ClassName foo2 = ClassName.fromString("d.e.f.foo"); - final ClassInfo foo1Class = ClassInfoMother.make(foo1, "foo.java"); - final ClassInfo foo2Class = ClassInfoMother.make(foo2, "foo.java"); - final Collection classes = Arrays.asList(foo1Class, foo2Class); - when(this.code.getCode()).thenReturn(classes); - - this.testee = new CoverageData(this.code, this.lm); - - assertEquals(Arrays.asList(foo1Class), - this.testee.getClassesForFile("foo.java", "a.b.c")); - } - - @Test - public void shouldIncludeAllCoveredLinesInCoverageSummary() { - - final BlockLocationBuilder block = aBlockLocation(); - when(this.code.getCodeUnderTestNames()).thenReturn( - Collections.singleton(block.build().getLocation().getClassName())); - when(this.lm.mapLines(any(ClassName.class))).thenReturn( - makeCoverageMapForBlock(block, 1, 2, 3, 4)); - - final CoverageResultBuilder cr = aCoverageResult().withVisitedBlocks( - block.build(1)); - - this.testee.calculateClassCoverage(cr.build()); - - final CoverageSummary actual = this.testee.createSummary(); - assertEquals(4, actual.getNumberOfCoveredLines()); - } - - private static Function testInfoToExecutionTime() { - return a -> a.getTime(); - } - - private static Function testInfoToString() { - return a -> a.getName(); - } - - private CoverageResult makeCoverageResult(final String clazz, - final String testName, final int time, final int block) { - return makeCoverageResult(clazz, new Description(testName), time, block, - true); - } - - private CoverageResult makeCoverageResult(final String clazz, - final Description desc, final int time, final int block, - final boolean testPassed) { - return new CoverageResult(desc, time, testPassed, - makeCoverage(clazz, block)); - } - - private Collection makeCoverage(final String clazz, - final int block) { - final BlockLocation cs = new BlockLocation(Location.location( - ClassName.fromString(clazz), MethodName.fromString("foo"), "V"), block); - - return Collections.singleton(cs); - } - - private HashMap> makeCoverageMapForBlock( - BlockLocationBuilder blocks, Integer... lines) { - final HashMap> map = new HashMap<>(); - final Set s = new HashSet<>(); - s.addAll(Arrays.asList(lines)); - map.put(blocks.build(), s); - return map; - } - -} +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.coverage; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.pitest.coverage.CoverageMother.aBlockLocation; +import static org.pitest.coverage.CoverageMother.aCoverageResult; +import static org.pitest.mutationtest.LocationMother.aLocation; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Function; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassInfoMother; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.CoverageMother.BlockLocationBuilder; +import org.pitest.coverage.CoverageMother.CoverageResultBuilder; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.testapi.Description; + +public class CoverageDataTest { + + private CoverageData testee; + + @Mock + private CodeSource code; + + @Mock + private LineMap lm; + + private final ClassName foo = ClassName.fromString("foo"); + private final ClassName bar = ClassName.fromString("bar"); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + when(this.lm.mapLines(any(ClassName.class))).thenReturn( + new HashMap>()); + when(this.code.findTestee(any())).thenReturn(Optional.empty()); + this.testee = new CoverageData(this.code, this.lm); + } + + @Test + public void shouldReturnNoTestsWhenNoTestsCoverALine() { + when(this.lm.mapLines(any(ClassName.class))).thenReturn( + new HashMap>()); + final ClassLine line = new ClassLine("foo", 1); + assertEquals(Collections.emptyList(), + this.testee.getTestsForClassLine(line)); + } + + @Test + public void shouldStoreExecutionTimesOfTests() { + + final int line = 1; + final int time = 42; + + final BlockLocationBuilder block = aBlockLocation().withLocation( + aLocation().withClass(this.foo)); + when(this.lm.mapLines(any(ClassName.class))).thenReturn( + makeCoverageMapForBlock(block, line)); + + final CoverageResultBuilder cr = aCoverageResult().withVisitedBlocks( + block.build(1)).withExecutionTime(time); + + this.testee.calculateClassCoverage(cr.build()); + + assertEquals(Arrays.asList(42), FCollection.map( + this.testee.getTestsForClassLine(new ClassLine(this.foo, line)), + testInfoToExecutionTime())); + } + + @Test + public void shouldReportNumberOfCoveredLinesWhenNoneCovered() { + assertEquals(0, this.testee.getNumberOfCoveredLines(Collections + .singletonList(ClassName.fromString("foo")))); + } + + @Test + public void shouldReportNumberOfCoveredLinesWhenSomeCovered() { + + final BlockLocationBuilder block = aBlockLocation().withLocation( + aLocation().withClass(this.foo)); + when(this.lm.mapLines(any(ClassName.class))).thenReturn( + makeCoverageMapForBlock(block, 101, 300)); + + final CoverageResultBuilder cr = aCoverageResult().withVisitedBlocks( + block.build(1)); + + this.testee.calculateClassCoverage(cr.build()); + + assertEquals(2, this.testee.getNumberOfCoveredLines(Collections + .singletonList(this.foo))); + } + + @Test + public void shouldReturnNotTestsWhenNoTestsCoverClass() { + assertTrue(this.testee.getTestsForClass(this.foo).isEmpty()); + } + + @Test + public void shouldReturnUniqueTestsForClassWhenSomeTestsCoverClass() { + this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 0, + 1)); + this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 0, + 2)); + this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest2", 0, + 2)); + assertEquals(Arrays.asList("fooTest", "fooTest2"), FCollection.map( + this.testee.getTestsForClass(this.foo), testInfoToString())); + } + + @Test + public void shouldReportAGreenSuiteWhenNoTestHasFailed() { + this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 42, + 1)); + assertTrue(this.testee.allTestsGreen()); + } + + @Test + public void shouldNotReportAGreenSuiteWhenATestHasFailed() { + this.testee.calculateClassCoverage(makeCoverageResult("foo", + new Description("fooTest"), 42, 1, false)); + assertFalse(this.testee.allTestsGreen()); + } + + @Test + public void shouldProvideAccessToClassData() { + final Collection classes = Arrays.asList(ClassName + .fromString("foo")); + this.testee.getClassInfo(classes); + verify(this.code).getClassInfo(classes); + } + + @Test + public void shouldReturnCoverageIdOf0WhenNoTestsCoverClass() { + assertEquals(0, + this.testee.getCoverageIdForClass(ClassName.fromString("unknown")) + .longValue()); + } + + @Test + public void shouldReturnNonZeroCoverageIdWhenTestsCoverClass() { + + final ClassName foo = ClassName.fromString("Foo"); + final ClassInfo ci = ClassInfoMother.make(foo); + + when(this.code.getClassInfo(any(Collection.class))).thenReturn( + Collections.singletonList(ci)); + + final BlockLocationBuilder block = aBlockLocation().withLocation( + aLocation().withClass(foo)); + final HashMap> map = makeCoverageMapForBlock(block, + 42); + when(this.lm.mapLines(any(ClassName.class))).thenReturn(map); + this.testee.calculateClassCoverage(aCoverageResult().withVisitedBlocks( + block.build(1)).build()); + + assertThat(this.testee.getCoverageIdForClass(foo).longValue()) + .isNotEqualTo(0); + + } + + @Test + public void shouldProvideEmptyBlockCoverageListWhenNoCoverage() { + assertEquals(Collections.emptyList(), this.testee.createCoverage()); + } + + @Test + public void shouldProvideCoverageListWhenCoverageRecorded() { + + final BlockLocationBuilder block = aBlockLocation().withLocation( + aLocation().withClass(this.foo)); + final CoverageResultBuilder cr = aCoverageResult().withVisitedBlocks( + block.build(1)); + + this.testee.calculateClassCoverage(cr.build()); + + this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 0, + 1)); + final BlockCoverage actual = this.testee.createCoverage().get(0); + assertEquals(block.build(), actual.getBlock()); + assertThat(actual.getTests()).contains("FooTest.fooTest"); + } + + @Test + public void shouldProvideListOfClassesForSourceFile() { + + final ClassInfo fooClass = ClassInfoMother.make(this.foo, "foo.java"); + final ClassInfo barClass = ClassInfoMother.make(this.bar, "bar.java"); + final Collection classes = Arrays.asList(fooClass, barClass); + when(this.code.getCode()).thenReturn(classes); + + this.testee = new CoverageData(this.code, this.lm); + + assertEquals(Arrays.asList(barClass), + this.testee.getClassesForFile("bar.java", "")); + } + + @Test + public void shouldMatchPackageWhenFindingSources() { + final ClassName foo1 = ClassName.fromString("a.b.c.foo"); + final ClassName foo2 = ClassName.fromString("d.e.f.foo"); + final ClassInfo foo1Class = ClassInfoMother.make(foo1, "foo.java"); + final ClassInfo foo2Class = ClassInfoMother.make(foo2, "foo.java"); + final Collection classes = Arrays.asList(foo1Class, foo2Class); + when(this.code.getCode()).thenReturn(classes); + + this.testee = new CoverageData(this.code, this.lm); + + assertEquals(Arrays.asList(foo1Class), + this.testee.getClassesForFile("foo.java", "a.b.c")); + } + + @Test + public void shouldIncludeAllCoveredLinesInCoverageSummary() { + + final BlockLocationBuilder block = aBlockLocation(); + when(this.code.getCodeUnderTestNames()).thenReturn( + Collections.singleton(block.build().getLocation().getClassName())); + when(this.lm.mapLines(any(ClassName.class))).thenReturn( + makeCoverageMapForBlock(block, 1, 2, 3, 4)); + + final CoverageResultBuilder cr = aCoverageResult().withVisitedBlocks( + block.build(1)); + + this.testee.calculateClassCoverage(cr.build()); + + final CoverageSummary actual = this.testee.createSummary(); + assertEquals(4, actual.getNumberOfCoveredLines()); + } + + private static Function testInfoToExecutionTime() { + return a -> a.getTime(); + } + + private static Function testInfoToString() { + return a -> a.getName(); + } + + private CoverageResult makeCoverageResult(final String clazz, + final String testName, final int time, final int block) { + return makeCoverageResult(clazz, new Description(testName), time, block, + true); + } + + private CoverageResult makeCoverageResult(final String clazz, + final Description desc, final int time, final int block, + final boolean testPassed) { + return new CoverageResult(desc, time, testPassed, + makeCoverage(clazz, block)); + } + + private Collection makeCoverage(final String clazz, + final int block) { + final BlockLocation cs = new BlockLocation(Location.location( + ClassName.fromString(clazz), MethodName.fromString("foo"), "V"), block); + + return Collections.singleton(cs); + } + + private HashMap> makeCoverageMapForBlock( + BlockLocationBuilder blocks, Integer... lines) { + final HashMap> map = new HashMap<>(); + final Set s = new HashSet<>(); + s.addAll(Arrays.asList(lines)); + map.put(blocks.build(), s); + return map; + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/coverage/CoverageMother.java b/pitest-entry/src/test/java/org/pitest/coverage/CoverageMother.java index 9d5385588..043071478 100644 --- a/pitest-entry/src/test/java/org/pitest/coverage/CoverageMother.java +++ b/pitest-entry/src/test/java/org/pitest/coverage/CoverageMother.java @@ -1,75 +1,75 @@ -package org.pitest.coverage; - -import static org.pitest.mutationtest.LocationMother.aLocation; - -import java.util.Collection; -import java.util.Collections; - -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.Location; -import org.pitest.quickbuilder.Builder; -import org.pitest.quickbuilder.Generator; -import org.pitest.quickbuilder.SequenceBuilder; -import org.pitest.quickbuilder.builders.QB; -import org.pitest.testapi.Description; - -public class CoverageMother { - - public interface BlockLocationBuilder extends SequenceBuilder { - BlockLocationBuilder withLocation(Builder location); - - BlockLocationBuilder withLocation(Location location); - - BlockLocationBuilder withBlock(int block); - - Location _Location(); - - int _Block(); - } - - public interface CoverageResultBuilder extends - SequenceBuilder { - - CoverageResultBuilder withTestUnitDescription(Description d); - - CoverageResultBuilder withExecutionTime(int time); - - CoverageResultBuilder withVisitedBlocks(Collection blocks); - - CoverageResultBuilder withGreenSuite(boolean green); - - Description _TestUnitDescription(); - - int _ExecutionTime(); - - Collection _VisitedBlocks(); - - boolean _GreenSuite(); - - } - - public static BlockLocationBuilder aBlockLocation() { - return QB.builder(BlockLocationBuilder.class, blockLocationSeed()) - .withBlock(1).withLocation(aLocation()); - } - - public static CoverageResultBuilder aCoverageResult() { - final ClassName fooTest = ClassName.fromString("FooTest"); - return QB - .builder(CoverageResultBuilder.class, CoverageResultSeed()) - .withTestUnitDescription( - new Description("fooTest", fooTest.asJavaName())) - .withExecutionTime(1).withGreenSuite(true) - .withVisitedBlocks(Collections. emptyList()); - } - - private static Generator blockLocationSeed() { - return b -> BlockLocation.blockLocation(b._Location(), b._Block()); - } - - private static Generator CoverageResultSeed() { - return b -> new CoverageResult(b._TestUnitDescription(), b._ExecutionTime(), - b._GreenSuite(), b._VisitedBlocks()); - } - -} +package org.pitest.coverage; + +import static org.pitest.mutationtest.LocationMother.aLocation; + +import java.util.Collection; +import java.util.Collections; + +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.Location; +import org.pitest.quickbuilder.Builder; +import org.pitest.quickbuilder.Generator; +import org.pitest.quickbuilder.SequenceBuilder; +import org.pitest.quickbuilder.builders.QB; +import org.pitest.testapi.Description; + +public class CoverageMother { + + public interface BlockLocationBuilder extends SequenceBuilder { + BlockLocationBuilder withLocation(Builder location); + + BlockLocationBuilder withLocation(Location location); + + BlockLocationBuilder withBlock(int block); + + Location _Location(); + + int _Block(); + } + + public interface CoverageResultBuilder extends + SequenceBuilder { + + CoverageResultBuilder withTestUnitDescription(Description d); + + CoverageResultBuilder withExecutionTime(int time); + + CoverageResultBuilder withVisitedBlocks(Collection blocks); + + CoverageResultBuilder withGreenSuite(boolean green); + + Description _TestUnitDescription(); + + int _ExecutionTime(); + + Collection _VisitedBlocks(); + + boolean _GreenSuite(); + + } + + public static BlockLocationBuilder aBlockLocation() { + return QB.builder(BlockLocationBuilder.class, blockLocationSeed()) + .withBlock(1).withLocation(aLocation()); + } + + public static CoverageResultBuilder aCoverageResult() { + final ClassName fooTest = ClassName.fromString("FooTest"); + return QB + .builder(CoverageResultBuilder.class, CoverageResultSeed()) + .withTestUnitDescription( + new Description("fooTest", fooTest.asJavaName())) + .withExecutionTime(1).withGreenSuite(true) + .withVisitedBlocks(Collections. emptyList()); + } + + private static Generator blockLocationSeed() { + return b -> BlockLocation.blockLocation(b._Location(), b._Block()); + } + + private static Generator CoverageResultSeed() { + return b -> new CoverageResult(b._TestUnitDescription(), b._ExecutionTime(), + b._GreenSuite(), b._VisitedBlocks()); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/coverage/CoverageSummaryTest.java b/pitest-entry/src/test/java/org/pitest/coverage/CoverageSummaryTest.java index a91cdae14..3b3086500 100644 --- a/pitest-entry/src/test/java/org/pitest/coverage/CoverageSummaryTest.java +++ b/pitest-entry/src/test/java/org/pitest/coverage/CoverageSummaryTest.java @@ -1,29 +1,29 @@ -package org.pitest.coverage; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class CoverageSummaryTest { - - @Test - public void shouldCorrectlyCalculateLineCoverageWhenNoLinesPresent() { - assertEquals(100, new CoverageSummary(0, 0).getCoverage()); - } - - @Test - public void shouldCorrectlyCalculateLineCoverageWhenNoLinesCovered() { - assertEquals(0, new CoverageSummary(100, 0).getCoverage()); - } - - @Test - public void shouldCorrectlyCalculateLineCoverageWhenAllLinesCovered() { - assertEquals(100, new CoverageSummary(100, 100).getCoverage()); - } - - @Test - public void shouldCorrectlyCalculateLineCoverageWhenPartiallyCovered() { - assertEquals(50, new CoverageSummary(100, 50).getCoverage()); - } - -} +package org.pitest.coverage; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CoverageSummaryTest { + + @Test + public void shouldCorrectlyCalculateLineCoverageWhenNoLinesPresent() { + assertEquals(100, new CoverageSummary(0, 0).getCoverage()); + } + + @Test + public void shouldCorrectlyCalculateLineCoverageWhenNoLinesCovered() { + assertEquals(0, new CoverageSummary(100, 0).getCoverage()); + } + + @Test + public void shouldCorrectlyCalculateLineCoverageWhenAllLinesCovered() { + assertEquals(100, new CoverageSummary(100, 100).getCoverage()); + } + + @Test + public void shouldCorrectlyCalculateLineCoverageWhenPartiallyCovered() { + assertEquals(50, new CoverageSummary(100, 50).getCoverage()); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/coverage/execute/CoverageProcessSystemTest.java b/pitest-entry/src/test/java/org/pitest/coverage/execute/CoverageProcessSystemTest.java index 250d83ad3..4fc7b552d 100644 --- a/pitest-entry/src/test/java/org/pitest/coverage/execute/CoverageProcessSystemTest.java +++ b/pitest-entry/src/test/java/org/pitest/coverage/execute/CoverageProcessSystemTest.java @@ -1,428 +1,428 @@ -package org.pitest.coverage.execute; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.pitest.SystemTest; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassPath; -import org.pitest.coverage.BlockLocation; -import org.pitest.coverage.CoverageResult; -import org.pitest.functional.FCollection; -import org.pitest.functional.SideEffect1; -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.mutationtest.execute.DefaultPITClassloader; -import org.pitest.mutationtest.tooling.JarCreatingJarFinder; -import org.pitest.process.LaunchOptions; -import org.pitest.process.ProcessArgs; -import org.pitest.util.ExitCode; -import org.pitest.util.SocketFinder; -import org.pitest.util.XStreamCloning; - -import com.example.coverage.execute.samples.exceptions.CoveredBeforeExceptionTestee; -import com.example.coverage.execute.samples.exceptions.TestThrowsExceptionFromLargeMethodTestee; -import com.example.coverage.execute.samples.exceptions.TestThrowsExceptionInFinallyBlock; -import com.example.coverage.execute.samples.exceptions.TestsClassWithException; -import com.example.coverage.execute.samples.exceptions.ThrowsExceptionFromLargeMethodTestee; -import com.example.coverage.execute.samples.exceptions.ThrowsExceptionInFinallyBlockTestee; -import com.example.coverage.execute.samples.exceptions.ThrowsExceptionTestee; -import com.example.coverage.execute.samples.simple.Testee; -import com.example.coverage.execute.samples.simple.Testee2; -import com.example.coverage.execute.samples.simple.TesteeWithComplexConstructorsTest; -import com.example.coverage.execute.samples.simple.TesteeWithMultipleLines; -import com.example.coverage.execute.samples.simple.Tests; -import com.example.coverage.execute.samples.simple.TestsForMultiBlockCoverage; - -@Category(SystemTest.class) -public class CoverageProcessSystemTest { - - private final MethodName foo = MethodName.fromString("foo"); - - @Test - public void shouldRecordSomeCoverage() throws IOException, - InterruptedException, ExecutionException { - final List coverage = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertFalse(coverage.iterator().next().getCoverage().isEmpty()); - } - - // check all the specialised implementations broadly work - @Test - public void shouldCalculateCoverageForSingleBlockMethods() - throws IOException, InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test1", 1); - } - - // @Test - // public void shouldCalculateCoverageFor2BlockMethods() throws IOException, - // InterruptedException, ExecutionException { - // final List coveredClasses = - // runCoverageForTest(TestsForMultiBlockCoverage.class); - // assertCoverage(coveredClasses, "test2", 2); - // } - - @Test - public void shouldCalculateCoverageFor3BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test3", 2); - } - - @Test - public void shouldCalculateCoverageForConstructors() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TesteeWithComplexConstructorsTest.class); - assertTrue(coversBlock(coveredClasses, "testHigh", 0)); - assertTrue(coversBlock(coveredClasses, "testHigh", 1)); - assertFalse(coversBlock(coveredClasses, "testHigh", 2)); - - assertTrue(coversBlock(coveredClasses, "testLow", 0)); - assertTrue(coversBlock(coveredClasses, "testLow", 2)); - assertFalse(coversBlock(coveredClasses, "testLow", 1)); - } - - @Test - public void shouldCalculateCoverageFor4BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test4", 2); - } - - @Test - public void shouldCalculateCoverageFor5BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test5", 2); - } - - @Test - public void shouldCalculateCoverageForBlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test6", 2); - } - - @Test - public void shouldCalculateCoverageFor7BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test7", 2); - } - - @Test - public void shouldCalculateCoverageFor8BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test8", 2); - } - - @Test - public void shouldCalculateCoverageFor9BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test9", 2); - } - - @Test - public void shouldCalculateCoverageFor10BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test10", 2); - } - - @Test - public void shouldCalculateCoverageFor11BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test11", 2); - } - - @Test - public void shouldCalculateCoverageFor12BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test12", 2); - } - - @Test - public void shouldCalculateCoverageFor13BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test13", 2); - } - - @Test - public void shouldCalculateCoverageFor14BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test14", 2); - } - - @Test - public void shouldCalculateCoverageFor15BlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "test15", 2); - } - - @Test - public void shouldCalculateCoverageForLargeBlockMethods() throws IOException, - InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); - assertCoverage(coveredClasses, "testMany", 2); - } - - @Test - public void shouldCalculateCoverageForAllRelevantClasses() - throws IOException, InterruptedException, ExecutionException { - - final List coveredClasses = runCoverageForTest(Tests.class); - - assertThat(coveredClasses).anyMatch(coverageFor(Testee2.class)); - assertThat(coveredClasses).anyMatch(coverageFor(Testee.class)); - assertThat(coveredClasses).anyMatch(coverageFor(TesteeWithMultipleLines.class)); - } - - @Test - public void shouldCalculateCoverageForSmallMethodThatThrowsException() - throws IOException, InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestsClassWithException.class); - assertThat(coveredClasses).anyMatch(coverageFor(CoveredBeforeExceptionTestee.class)); - - final ClassName throwsException = ClassName - .fromClass(ThrowsExceptionTestee.class); - - assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( - Location.location(throwsException, this.foo, "()V"), 0))); - - assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( - Location.location(throwsException, - MethodName.fromString("throwsException"), "()V"), 0))); - - } - - @Test - public void shouldCalculateCoverageForMethodThatThrowsExceptionWithFinallyBlock() - throws IOException, InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestThrowsExceptionInFinallyBlock.class); - - final ClassName clazz = ClassName - .fromClass(ThrowsExceptionInFinallyBlockTestee.class); - - assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( - Location.location(clazz, this.foo, "()V"), 0))); - - assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( - Location.location(clazz, this.foo, "()V"), 1))); - } - - @Test - public void shouldCalculateCoverageForLargeMethodThatThrowsException() - throws IOException, InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestThrowsExceptionFromLargeMethodTestee.class); - - final ClassName clazz = ClassName - .fromClass(ThrowsExceptionFromLargeMethodTestee.class); - - assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( - Location.location(clazz, this.foo, "()I"), 0))); - - } - - public static class TestInDifferentClassLoader { - @Test - public void testFoo() { - final ClassLoader cl = new DefaultPITClassloader(new ClassPath(), - XStreamCloning.bootClassLoader()); - final Testee testee = new Testee(); - final Runnable r = (Runnable) XStreamCloning.cloneForLoader(testee, cl); - r.run(); - } - - } - - @Test - public void shouldCalculateCoverageOfClassesRunInDifferentClassLoader() - throws IOException, InterruptedException, ExecutionException { - final List coveredClasses = runCoverageForTest(TestInDifferentClassLoader.class); - assertThat(coveredClasses).anyMatch(coverageFor(Testee2.class)); - assertThat(coveredClasses).anyMatch(coverageFor(Testee.class)); - } - - public static class ReliesOnNewLine { - public static String parseNewLines() throws IOException { - final StringWriter sw = new StringWriter(); - final PrintWriter pw = new PrintWriter(sw); - pw.println("foo"); - pw.println("bar"); - - final BufferedReader in = new BufferedReader(new StringReader(sw - .getBuffer().toString())); - return in.readLine(); - } - } - - public static class ReliesOnNewLineTest { - @Test - public void testNewLine() throws IOException { - assertEquals("foo", ReliesOnNewLine.parseNewLines()); - } - } - - @Test - public void shouldNotCorruptedTheSystemNewLineProperty() throws Exception { - final List coveredClasses = runCoverageForTest(ReliesOnNewLineTest.class); - assertThat(coveredClasses).noneMatch(failingTest()); - } - - @Test - public void shouldFailWithExitCode() throws Exception { - final SideEffect1 noOpHandler = a -> { - }; - - final CoverageOptions sa = new CoverageOptions(coverOnlyTestees(), excludeTests(), TestPluginArguments.defaults(), true, -1); - - final JarCreatingJarFinder agent = new JarCreatingJarFinder(); - final LaunchOptions lo = new LaunchOptions(agent); - final SocketFinder sf = new SocketFinder(); - final CoverageProcess process = new CoverageProcess(ProcessArgs - .withClassPath(classPathWithoutJUnit()).andLaunchOptions(lo), sa, - sf.getNextAvailableServerSocket(), - Arrays.asList(TestsForMultiBlockCoverage.class.getName()), noOpHandler); - process.start(); - - final ExitCode exitCode = process.waitToDie(); - assertEquals(ExitCode.JUNIT_ISSUE, exitCode); - } - - private ClassPath classPathWithoutJUnit() { - final List cpWithoutJUnit = - ClassPath.getClassPathElementsAsFiles().stream() - .filter(file -> !file.getName().contains("junit")) - .collect(Collectors.toList()); - - return new ClassPath(cpWithoutJUnit); - } - - private Predicate failingTest() { - return a -> !a.isGreenTest(); - } - - private List runCoverageForTest(final Class test) - throws IOException, InterruptedException, ExecutionException { - - final List coveredClasses = new ArrayList<>(); - - runCoverageProcess(test, coveredClasses); - return coveredClasses; - } - - private void runCoverageProcess(final Class test, - final List coveredClasses) throws IOException, - InterruptedException { - final SideEffect1 handler = a -> coveredClasses.add(a); - - final CoverageOptions sa = new CoverageOptions(coverOnlyTestees(), excludeTests(), TestPluginArguments.defaults(), true, -1); - - final JarCreatingJarFinder agent = new JarCreatingJarFinder(); - try { - final LaunchOptions lo = new LaunchOptions(agent); - final SocketFinder sf = new SocketFinder(); - final CoverageProcess process = new CoverageProcess(ProcessArgs - .withClassPath(new ClassPath()).andLaunchOptions(lo), sa, - sf.getNextAvailableServerSocket(), Arrays.asList(test.getName()), - handler); - process.start(); - - final ExitCode exitCode = process.waitToDie(); - assertEquals(ExitCode.OK, exitCode); - } finally { - agent.close(); - } - } - - private Predicate coverageFor(final Class class1) { - return new Predicate() { - - @Override - public boolean test(final CoverageResult a) { - return FCollection.contains(a.getCoverage(), resultFor(class1)); - } - - private Predicate resultFor(final Class class1) { - return a -> a.isFor(ClassName.fromClass(class1)); - } - }; - } - - private Predicate coverageFor(final BlockLocation location) { - return a -> a.getCoverage().contains(location); - } - - private List coverOnlyTestees() { - return Arrays.asList("*Testee*"); - } - - private List excludeTests() { - return Arrays.asList("*Test"); - } - - private Predicate coverage(final String testName, - final int numberOfBlocks) { - return a -> a.getTestUnitDescription().getName().startsWith(testName) - && (a.getNumberOfCoveredBlocks() == numberOfBlocks); - } - - private void assertCoverage( - final List coveredClasses, - final String testName, final int numberOfBlocks) { - assertThat(coveredClasses).anyMatch(coverage(testName, numberOfBlocks)); - } - - private boolean coversBlock( - final List coveredClasses, - final String testName, final int block) { - return coveredClasses.stream().filter(hitsBlock(testName, block)).findFirst().isPresent(); - } - - private Predicate hitsBlock(final String testName, - final int block) { - return new Predicate() { - @Override - public boolean test(final CoverageResult a) { - return a.getTestUnitDescription().getName().startsWith(testName) - && (FCollection.contains(a.getCoverage(), hasBlock(block))); - } - - private Predicate hasBlock(final int block) { - return a -> { - System.out.println(a); - return a.getBlock() == block; - }; - } - - }; - } - - - -} +package org.pitest.coverage.execute; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.pitest.SystemTest; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassPath; +import org.pitest.coverage.BlockLocation; +import org.pitest.coverage.CoverageResult; +import org.pitest.functional.FCollection; +import org.pitest.functional.SideEffect1; +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.mutationtest.execute.DefaultPITClassloader; +import org.pitest.mutationtest.tooling.JarCreatingJarFinder; +import org.pitest.process.LaunchOptions; +import org.pitest.process.ProcessArgs; +import org.pitest.util.ExitCode; +import org.pitest.util.SocketFinder; +import org.pitest.util.XStreamCloning; + +import com.example.coverage.execute.samples.exceptions.CoveredBeforeExceptionTestee; +import com.example.coverage.execute.samples.exceptions.TestThrowsExceptionFromLargeMethodTestee; +import com.example.coverage.execute.samples.exceptions.TestThrowsExceptionInFinallyBlock; +import com.example.coverage.execute.samples.exceptions.TestsClassWithException; +import com.example.coverage.execute.samples.exceptions.ThrowsExceptionFromLargeMethodTestee; +import com.example.coverage.execute.samples.exceptions.ThrowsExceptionInFinallyBlockTestee; +import com.example.coverage.execute.samples.exceptions.ThrowsExceptionTestee; +import com.example.coverage.execute.samples.simple.Testee; +import com.example.coverage.execute.samples.simple.Testee2; +import com.example.coverage.execute.samples.simple.TesteeWithComplexConstructorsTest; +import com.example.coverage.execute.samples.simple.TesteeWithMultipleLines; +import com.example.coverage.execute.samples.simple.Tests; +import com.example.coverage.execute.samples.simple.TestsForMultiBlockCoverage; + +@Category(SystemTest.class) +public class CoverageProcessSystemTest { + + private final MethodName foo = MethodName.fromString("foo"); + + @Test + public void shouldRecordSomeCoverage() throws IOException, + InterruptedException, ExecutionException { + final List coverage = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertFalse(coverage.iterator().next().getCoverage().isEmpty()); + } + + // check all the specialised implementations broadly work + @Test + public void shouldCalculateCoverageForSingleBlockMethods() + throws IOException, InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test1", 1); + } + + // @Test + // public void shouldCalculateCoverageFor2BlockMethods() throws IOException, + // InterruptedException, ExecutionException { + // final List coveredClasses = + // runCoverageForTest(TestsForMultiBlockCoverage.class); + // assertCoverage(coveredClasses, "test2", 2); + // } + + @Test + public void shouldCalculateCoverageFor3BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test3", 2); + } + + @Test + public void shouldCalculateCoverageForConstructors() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TesteeWithComplexConstructorsTest.class); + assertTrue(coversBlock(coveredClasses, "testHigh", 0)); + assertTrue(coversBlock(coveredClasses, "testHigh", 1)); + assertFalse(coversBlock(coveredClasses, "testHigh", 2)); + + assertTrue(coversBlock(coveredClasses, "testLow", 0)); + assertTrue(coversBlock(coveredClasses, "testLow", 2)); + assertFalse(coversBlock(coveredClasses, "testLow", 1)); + } + + @Test + public void shouldCalculateCoverageFor4BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test4", 2); + } + + @Test + public void shouldCalculateCoverageFor5BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test5", 2); + } + + @Test + public void shouldCalculateCoverageForBlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test6", 2); + } + + @Test + public void shouldCalculateCoverageFor7BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test7", 2); + } + + @Test + public void shouldCalculateCoverageFor8BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test8", 2); + } + + @Test + public void shouldCalculateCoverageFor9BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test9", 2); + } + + @Test + public void shouldCalculateCoverageFor10BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test10", 2); + } + + @Test + public void shouldCalculateCoverageFor11BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test11", 2); + } + + @Test + public void shouldCalculateCoverageFor12BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test12", 2); + } + + @Test + public void shouldCalculateCoverageFor13BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test13", 2); + } + + @Test + public void shouldCalculateCoverageFor14BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test14", 2); + } + + @Test + public void shouldCalculateCoverageFor15BlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "test15", 2); + } + + @Test + public void shouldCalculateCoverageForLargeBlockMethods() throws IOException, + InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsForMultiBlockCoverage.class); + assertCoverage(coveredClasses, "testMany", 2); + } + + @Test + public void shouldCalculateCoverageForAllRelevantClasses() + throws IOException, InterruptedException, ExecutionException { + + final List coveredClasses = runCoverageForTest(Tests.class); + + assertThat(coveredClasses).anyMatch(coverageFor(Testee2.class)); + assertThat(coveredClasses).anyMatch(coverageFor(Testee.class)); + assertThat(coveredClasses).anyMatch(coverageFor(TesteeWithMultipleLines.class)); + } + + @Test + public void shouldCalculateCoverageForSmallMethodThatThrowsException() + throws IOException, InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestsClassWithException.class); + assertThat(coveredClasses).anyMatch(coverageFor(CoveredBeforeExceptionTestee.class)); + + final ClassName throwsException = ClassName + .fromClass(ThrowsExceptionTestee.class); + + assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( + Location.location(throwsException, this.foo, "()V"), 0))); + + assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( + Location.location(throwsException, + MethodName.fromString("throwsException"), "()V"), 0))); + + } + + @Test + public void shouldCalculateCoverageForMethodThatThrowsExceptionWithFinallyBlock() + throws IOException, InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestThrowsExceptionInFinallyBlock.class); + + final ClassName clazz = ClassName + .fromClass(ThrowsExceptionInFinallyBlockTestee.class); + + assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( + Location.location(clazz, this.foo, "()V"), 0))); + + assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( + Location.location(clazz, this.foo, "()V"), 1))); + } + + @Test + public void shouldCalculateCoverageForLargeMethodThatThrowsException() + throws IOException, InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestThrowsExceptionFromLargeMethodTestee.class); + + final ClassName clazz = ClassName + .fromClass(ThrowsExceptionFromLargeMethodTestee.class); + + assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation( + Location.location(clazz, this.foo, "()I"), 0))); + + } + + public static class TestInDifferentClassLoader { + @Test + public void testFoo() { + final ClassLoader cl = new DefaultPITClassloader(new ClassPath(), + XStreamCloning.bootClassLoader()); + final Testee testee = new Testee(); + final Runnable r = (Runnable) XStreamCloning.cloneForLoader(testee, cl); + r.run(); + } + + } + + @Test + public void shouldCalculateCoverageOfClassesRunInDifferentClassLoader() + throws IOException, InterruptedException, ExecutionException { + final List coveredClasses = runCoverageForTest(TestInDifferentClassLoader.class); + assertThat(coveredClasses).anyMatch(coverageFor(Testee2.class)); + assertThat(coveredClasses).anyMatch(coverageFor(Testee.class)); + } + + public static class ReliesOnNewLine { + public static String parseNewLines() throws IOException { + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + pw.println("foo"); + pw.println("bar"); + + final BufferedReader in = new BufferedReader(new StringReader(sw + .getBuffer().toString())); + return in.readLine(); + } + } + + public static class ReliesOnNewLineTest { + @Test + public void testNewLine() throws IOException { + assertEquals("foo", ReliesOnNewLine.parseNewLines()); + } + } + + @Test + public void shouldNotCorruptedTheSystemNewLineProperty() throws Exception { + final List coveredClasses = runCoverageForTest(ReliesOnNewLineTest.class); + assertThat(coveredClasses).noneMatch(failingTest()); + } + + @Test + public void shouldFailWithExitCode() throws Exception { + final SideEffect1 noOpHandler = a -> { + }; + + final CoverageOptions sa = new CoverageOptions(coverOnlyTestees(), excludeTests(), TestPluginArguments.defaults(), true, -1); + + final JarCreatingJarFinder agent = new JarCreatingJarFinder(); + final LaunchOptions lo = new LaunchOptions(agent); + final SocketFinder sf = new SocketFinder(); + final CoverageProcess process = new CoverageProcess(ProcessArgs + .withClassPath(classPathWithoutJUnit()).andLaunchOptions(lo), sa, + sf.getNextAvailableServerSocket(), + Arrays.asList(TestsForMultiBlockCoverage.class.getName()), noOpHandler); + process.start(); + + final ExitCode exitCode = process.waitToDie(); + assertEquals(ExitCode.JUNIT_ISSUE, exitCode); + } + + private ClassPath classPathWithoutJUnit() { + final List cpWithoutJUnit = + ClassPath.getClassPathElementsAsFiles().stream() + .filter(file -> !file.getName().contains("junit")) + .collect(Collectors.toList()); + + return new ClassPath(cpWithoutJUnit); + } + + private Predicate failingTest() { + return a -> !a.isGreenTest(); + } + + private List runCoverageForTest(final Class test) + throws IOException, InterruptedException, ExecutionException { + + final List coveredClasses = new ArrayList<>(); + + runCoverageProcess(test, coveredClasses); + return coveredClasses; + } + + private void runCoverageProcess(final Class test, + final List coveredClasses) throws IOException, + InterruptedException { + final SideEffect1 handler = a -> coveredClasses.add(a); + + final CoverageOptions sa = new CoverageOptions(coverOnlyTestees(), excludeTests(), TestPluginArguments.defaults(), true, -1); + + final JarCreatingJarFinder agent = new JarCreatingJarFinder(); + try { + final LaunchOptions lo = new LaunchOptions(agent); + final SocketFinder sf = new SocketFinder(); + final CoverageProcess process = new CoverageProcess(ProcessArgs + .withClassPath(new ClassPath()).andLaunchOptions(lo), sa, + sf.getNextAvailableServerSocket(), Arrays.asList(test.getName()), + handler); + process.start(); + + final ExitCode exitCode = process.waitToDie(); + assertEquals(ExitCode.OK, exitCode); + } finally { + agent.close(); + } + } + + private Predicate coverageFor(final Class class1) { + return new Predicate() { + + @Override + public boolean test(final CoverageResult a) { + return FCollection.contains(a.getCoverage(), resultFor(class1)); + } + + private Predicate resultFor(final Class class1) { + return a -> a.isFor(ClassName.fromClass(class1)); + } + }; + } + + private Predicate coverageFor(final BlockLocation location) { + return a -> a.getCoverage().contains(location); + } + + private List coverOnlyTestees() { + return Arrays.asList("*Testee*"); + } + + private List excludeTests() { + return Arrays.asList("*Test"); + } + + private Predicate coverage(final String testName, + final int numberOfBlocks) { + return a -> a.getTestUnitDescription().getName().startsWith(testName) + && (a.getNumberOfCoveredBlocks() == numberOfBlocks); + } + + private void assertCoverage( + final List coveredClasses, + final String testName, final int numberOfBlocks) { + assertThat(coveredClasses).anyMatch(coverage(testName, numberOfBlocks)); + } + + private boolean coversBlock( + final List coveredClasses, + final String testName, final int block) { + return coveredClasses.stream().filter(hitsBlock(testName, block)).findFirst().isPresent(); + } + + private Predicate hitsBlock(final String testName, + final int block) { + return new Predicate() { + @Override + public boolean test(final CoverageResult a) { + return a.getTestUnitDescription().getName().startsWith(testName) + && (FCollection.contains(a.getCoverage(), hasBlock(block))); + } + + private Predicate hasBlock(final int block) { + return a -> { + System.out.println(a); + return a.getBlock() == block; + }; + } + + }; + } + + + +} diff --git a/pitest-entry/src/test/java/org/pitest/coverage/execute/ReceiveTest.java b/pitest-entry/src/test/java/org/pitest/coverage/execute/ReceiveTest.java index e2c9c7712..4a355a26f 100644 --- a/pitest-entry/src/test/java/org/pitest/coverage/execute/ReceiveTest.java +++ b/pitest-entry/src/test/java/org/pitest/coverage/execute/ReceiveTest.java @@ -1,77 +1,77 @@ -package org.pitest.coverage.execute; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.coverage.CoverageResult; -import org.pitest.functional.SideEffect1; -import org.pitest.testapi.Description; -import org.pitest.util.Id; -import org.pitest.util.SafeDataInputStream; - -import sun.pitest.CodeCoverageStore; - -// does this test add any value? -public class ReceiveTest { - - private Receive testee; - - private SideEffect1 handler; - - private CoverageResult result; - - private Description description; - - @Mock - private SafeDataInputStream is; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.handler = stubHandler(); - this.testee = new Receive(this.handler); - this.description = new Description("foo", "bar"); - } - - private SideEffect1 stubHandler() { - return a -> ReceiveTest.this.result = a; - } - - @Test - public void shouldReportNoCoverageWhenNoTestsRun() { - this.testee.apply(Id.DONE, this.is); - assertNull(this.result); - } - - @Test - public void shouldReportWhenTestFails() { - recordTestCoverage(0, 0, 0, false); - assertEquals(false, this.result.isGreenTest()); - } - - @Test - public void shouldReportWhenTestPasses() { - recordTestCoverage(0, 0, 0, true); - assertEquals(true, this.result.isGreenTest()); - } - - private void recordTestCoverage(final int executionTime, final int classId, - final int probeNumber, final boolean testPassed) { - when(this.is.readInt()).thenReturn(classId, executionTime); - when(this.is.readString()).thenReturn("foo"); - this.testee.apply(Id.CLAZZ, this.is); - - when(this.is.read(Description.class)).thenReturn(this.description); - when(this.is.readInt()).thenReturn(1); - when(this.is.readLong()).thenReturn(1l, - CodeCoverageStore.encode(classId, probeNumber)); - when(this.is.readBoolean()).thenReturn(testPassed); - this.testee.apply(Id.OUTCOME, this.is); - } - -} +package org.pitest.coverage.execute; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.coverage.CoverageResult; +import org.pitest.functional.SideEffect1; +import org.pitest.testapi.Description; +import org.pitest.util.Id; +import org.pitest.util.SafeDataInputStream; + +import sun.pitest.CodeCoverageStore; + +// does this test add any value? +public class ReceiveTest { + + private Receive testee; + + private SideEffect1 handler; + + private CoverageResult result; + + private Description description; + + @Mock + private SafeDataInputStream is; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.handler = stubHandler(); + this.testee = new Receive(this.handler); + this.description = new Description("foo", "bar"); + } + + private SideEffect1 stubHandler() { + return a -> ReceiveTest.this.result = a; + } + + @Test + public void shouldReportNoCoverageWhenNoTestsRun() { + this.testee.apply(Id.DONE, this.is); + assertNull(this.result); + } + + @Test + public void shouldReportWhenTestFails() { + recordTestCoverage(0, 0, 0, false); + assertEquals(false, this.result.isGreenTest()); + } + + @Test + public void shouldReportWhenTestPasses() { + recordTestCoverage(0, 0, 0, true); + assertEquals(true, this.result.isGreenTest()); + } + + private void recordTestCoverage(final int executionTime, final int classId, + final int probeNumber, final boolean testPassed) { + when(this.is.readInt()).thenReturn(classId, executionTime); + when(this.is.readString()).thenReturn("foo"); + this.testee.apply(Id.CLAZZ, this.is); + + when(this.is.read(Description.class)).thenReturn(this.description); + when(this.is.readInt()).thenReturn(1); + when(this.is.readLong()).thenReturn(1l, + CodeCoverageStore.encode(classId, probeNumber)); + when(this.is.readBoolean()).thenReturn(testPassed); + this.testee.apply(Id.OUTCOME, this.is); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/coverage/execute/SendDataTest.java b/pitest-entry/src/test/java/org/pitest/coverage/execute/SendDataTest.java index 52ce09958..e6349a83f 100644 --- a/pitest-entry/src/test/java/org/pitest/coverage/execute/SendDataTest.java +++ b/pitest-entry/src/test/java/org/pitest/coverage/execute/SendDataTest.java @@ -1,49 +1,49 @@ -package org.pitest.coverage.execute; - -import static org.mockito.Mockito.verify; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.util.SafeDataOutputStream; - -public class SendDataTest { - - private SendData testee; - - private List testClasses; - - @Mock - private CoverageOptions arguments; - - @Mock - private SafeDataOutputStream os; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testClasses = new ArrayList<>(); - this.testee = new SendData(this.arguments, this.testClasses); - } - - @Test - public void shouldSendArgumentsToMinion() { - this.testee.apply(this.os); - verify(this.os).write(this.arguments); - } - - @Test - public void shouldSendTestClassesToMinion() { - this.testClasses.add("foo"); - this.testClasses.add("bar"); - this.testee.apply(this.os); - verify(this.os).writeInt(this.testClasses.size()); - verify(this.os).writeString("foo"); - verify(this.os).writeString("bar"); - } - -} +package org.pitest.coverage.execute; + +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.util.SafeDataOutputStream; + +public class SendDataTest { + + private SendData testee; + + private List testClasses; + + @Mock + private CoverageOptions arguments; + + @Mock + private SafeDataOutputStream os; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testClasses = new ArrayList<>(); + this.testee = new SendData(this.arguments, this.testClasses); + } + + @Test + public void shouldSendArgumentsToMinion() { + this.testee.apply(this.os); + verify(this.os).write(this.arguments); + } + + @Test + public void shouldSendTestClassesToMinion() { + this.testClasses.add("foo"); + this.testClasses.add("bar"); + this.testee.apply(this.os); + verify(this.os).writeInt(this.testClasses.size()); + verify(this.os).writeString("foo"); + verify(this.os).writeString("bar"); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/coverage/export/DefaultCoverageExporterTest.java b/pitest-entry/src/test/java/org/pitest/coverage/export/DefaultCoverageExporterTest.java index 15b3d86c4..6d832cdae 100644 --- a/pitest-entry/src/test/java/org/pitest/coverage/export/DefaultCoverageExporterTest.java +++ b/pitest-entry/src/test/java/org/pitest/coverage/export/DefaultCoverageExporterTest.java @@ -1,69 +1,69 @@ -package org.pitest.coverage.export; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.pitest.coverage.CoverageMother.aBlockLocation; -import static org.pitest.mutationtest.LocationMother.aLocation; - -import java.io.StringWriter; -import java.io.Writer; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.BlockCoverage; -import org.pitest.coverage.CoverageMother.BlockLocationBuilder; -import org.pitest.mutationtest.LocationMother.LocationBuilder; -import org.pitest.util.ResultOutputStrategy; - -public class DefaultCoverageExporterTest { - - private DefaultCoverageExporter testee; - - private final Writer out = new StringWriter(); - - @Before - public void setup() { - this.testee = new DefaultCoverageExporter(createOutputStrategy()); - } - - private ResultOutputStrategy createOutputStrategy() { - return sourceFile -> DefaultCoverageExporterTest.this.out; - } - - @Test - public void shouldWriteValidXMLDocumentWhenNoCoverage() { - this.testee.recordCoverage(Collections. emptyList()); - final String actual = this.out.toString(); - assertThat(actual).contains(""); - assertThat(actual).contains(""); - assertThat(actual).contains(""); - } - - @Test - public void shouldExportSuppliedCoverage() { - final LocationBuilder loc = aLocation().withMethod("method"); - final BlockLocationBuilder block = aBlockLocation().withBlock(42); - final Collection coverage = Arrays.asList( - new BlockCoverage(block.withLocation( - loc.withClass(ClassName.fromString("Foo"))).build(), Arrays.asList( - "Test1", "Test2")), - new BlockCoverage(block.withLocation( - loc.withClass(ClassName.fromString("Bar"))).build(), Arrays.asList( - "Test3", "Test4"))); - this.testee.recordCoverage(coverage); - - final String actual = this.out.toString(); - assertThat(actual).contains( - ""); - assertThat(actual).contains( - ""); - assertThat(actual).contains( - "\n\n\n"); - assertThat(actual).contains( - "\n\n\n"); - } - -} +package org.pitest.coverage.export; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.pitest.coverage.CoverageMother.aBlockLocation; +import static org.pitest.mutationtest.LocationMother.aLocation; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.BlockCoverage; +import org.pitest.coverage.CoverageMother.BlockLocationBuilder; +import org.pitest.mutationtest.LocationMother.LocationBuilder; +import org.pitest.util.ResultOutputStrategy; + +public class DefaultCoverageExporterTest { + + private DefaultCoverageExporter testee; + + private final Writer out = new StringWriter(); + + @Before + public void setup() { + this.testee = new DefaultCoverageExporter(createOutputStrategy()); + } + + private ResultOutputStrategy createOutputStrategy() { + return sourceFile -> DefaultCoverageExporterTest.this.out; + } + + @Test + public void shouldWriteValidXMLDocumentWhenNoCoverage() { + this.testee.recordCoverage(Collections. emptyList()); + final String actual = this.out.toString(); + assertThat(actual).contains(""); + assertThat(actual).contains(""); + assertThat(actual).contains(""); + } + + @Test + public void shouldExportSuppliedCoverage() { + final LocationBuilder loc = aLocation().withMethod("method"); + final BlockLocationBuilder block = aBlockLocation().withBlock(42); + final Collection coverage = Arrays.asList( + new BlockCoverage(block.withLocation( + loc.withClass(ClassName.fromString("Foo"))).build(), Arrays.asList( + "Test1", "Test2")), + new BlockCoverage(block.withLocation( + loc.withClass(ClassName.fromString("Bar"))).build(), Arrays.asList( + "Test3", "Test4"))); + this.testee.recordCoverage(coverage); + + final String actual = this.out.toString(); + assertThat(actual).contains( + ""); + assertThat(actual).contains( + ""); + assertThat(actual).contains( + "\n\n\n"); + assertThat(actual).contains( + "\n\n\n"); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/MetaDataExtractor.java b/pitest-entry/src/test/java/org/pitest/mutationtest/MetaDataExtractor.java index 8eea50950..c69a07903 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/MetaDataExtractor.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/MetaDataExtractor.java @@ -1,64 +1,64 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.BiFunction; - -import org.pitest.functional.FCollection; - -public class MetaDataExtractor implements MutationResultListener { - - private final List data = new ArrayList<>(); - - public List getDetectionStatus() { - final List dss = new ArrayList<>(); - for (final MutationResult each : this.data) { - dss.add(each.getStatus()); - } - return dss; - } - - public List getLineNumbers() { - final List dss = new ArrayList<>(); - for (final MutationResult each : this.data) { - dss.add(each.getDetails().getLineNumber()); - } - return dss; - } - - public int getNumberOfTestsRun() { - final BiFunction sum = (a, b) -> a + b.getNumberOfTestsRun(); - return FCollection.fold(sum, 0, this.data); - } - - @Override - public void runStart() { - - } - - @Override - public void handleMutationResult(final ClassMutationResults metaData) { - this.data.addAll(metaData.getMutations()); - } - - @Override - public void runEnd() { - // TODO Auto-generated method stub - - } - +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; + +import org.pitest.functional.FCollection; + +public class MetaDataExtractor implements MutationResultListener { + + private final List data = new ArrayList<>(); + + public List getDetectionStatus() { + final List dss = new ArrayList<>(); + for (final MutationResult each : this.data) { + dss.add(each.getStatus()); + } + return dss; + } + + public List getLineNumbers() { + final List dss = new ArrayList<>(); + for (final MutationResult each : this.data) { + dss.add(each.getDetails().getLineNumber()); + } + return dss; + } + + public int getNumberOfTestsRun() { + final BiFunction sum = (a, b) -> a + b.getNumberOfTestsRun(); + return FCollection.fold(sum, 0, this.data); + } + + @Override + public void runStart() { + + } + + @Override + public void handleMutationResult(final ClassMutationResults metaData) { + this.data.addAll(metaData.getMutations()); + } + + @Override + public void runEnd() { + // TODO Auto-generated method stub + + } + } \ No newline at end of file diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/MutationCoverageReportSystemTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/MutationCoverageReportSystemTest.java index 381d6207f..2b723a6ea 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/MutationCoverageReportSystemTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/MutationCoverageReportSystemTest.java @@ -1,424 +1,424 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest; - -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.pitest.mutationtest.DetectionStatus.KILLED; -import static org.pitest.mutationtest.DetectionStatus.NO_COVERAGE; -import static org.pitest.mutationtest.DetectionStatus.RUN_ERROR; -import static org.pitest.mutationtest.DetectionStatus.SURVIVED; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.pitest.SystemTest; -import org.pitest.classpath.ClassPath; -import org.pitest.help.PitHelpError; -import org.pitest.mutationtest.engine.gregor.Generated; -import org.pitest.util.FileUtil; -import org.pitest.util.IsolationUtils; - -import com.example.BeforeAfterClassTest; -import com.example.CoveredByABeforeAfterClass; -import com.example.CoveredByEasyMock; -import com.example.CoveredByJUnitThreeSuite; -import com.example.CrashesJVMWhenMutated; -import com.example.FailsTestWhenEnvVariableSetTestee; -import com.example.FullyCoveredTestee; -import com.example.FullyCoveredTesteeTest; -import com.example.HasMutationInFinallyBlockNonTest; -import com.example.HasMutationInFinallyBlockTest; -import com.example.HasMutationsInFinallyBlock; -import com.example.JUnitThreeSuite; -import com.example.KeepAliveThread; -import com.example.MultipleMutations; - -@Category(SystemTest.class) -public class MutationCoverageReportSystemTest extends ReportTestBase { - - private static final int ONE_MINUTE = 60000; - - @Before - public void excludeTests() { - this.data.setExcludedClasses(asList("*Test")); - this.data.setTestPlugin("junit"); - } - - @Test - public void shouldPickRelevantTestsAndKillMutationsBasedOnCoverageData() { - this.data.setTargetClasses(asList("com.example.FullyCovered*")); - this.data.setVerbose(true); - createAndRun(); - verifyResults(KILLED); - } - - @Test - public void shouldPickRelevantTestsAndKillMutationsBasedOnCoverageDataWhenLimitedByClassReach() { - this.data.setDependencyAnalysisMaxDistance(2); - this.data.setTargetTests(predicateFor("com.example.*FullyCovered*")); - this.data.setTargetClasses(asList("com.example.FullyCovered*")); - createAndRun(); - verifyResults(KILLED); - } - - @Test - public void shouldReportUnCoveredMutations() { - this.data.setTargetClasses(asList("com.example.PartiallyCovered*")); - createAndRun(); - verifyResults(KILLED, NO_COVERAGE); - } - - @Test - public void shouldReportSurvivingMutations() { - this.data - .setTargetClasses(asList("com.example.CoveredButOnlyPartiallyTested*")); - createAndRun(); - verifyResults(KILLED, SURVIVED); - } - - - @Test(expected = PitHelpError.class) - public void shouldFailRunWithHelpfulMessageIfTestsNotGreen() { - setMutators("MATH"); - this.data - .setTargetClasses(asList("com.example.FailsTestWhenEnvVariableSet*")); - this.data.addChildJVMArgs(Arrays.asList("-D" - + FailsTestWhenEnvVariableSetTestee.class.getName() + "=true")); - createAndRun(); - // should not get here - } - - @Test - public void shouldLoadResoucesOffClassPathFromFolderWithSpaces() { - setMutators("RETURN_VALS"); - this.data - .setTargetClasses(asList("com.example.LoadsResourcesFromClassPath*")); - this.data.setVerbose(true); - createAndRun(); - verifyResults(KILLED); - } - - @Test - public void shouldPickRelevantTestsFromSuppliedTestSuites() { - this.data.setTargetClasses(asList("com.example.FullyCovered*")); - this.data - .setTargetTests(predicateFor(com.example.SuiteForFullyCovered.class)); - createAndRun(); - verifyResults(KILLED); - } - - @Test - public void shouldNotMutateMethodsMatchingExclusionPredicate() { - this.data.setTargetClasses(asList("com.example.HasExcludedMethods*")); - this.data.setExcludedMethods(Arrays.asList("excludeMe")); - createAndRun(); - verifyResults(); - } - - @Test - public void shouldLimitNumberOfMutationsPerClass() { - this.data.setTargetClasses(asGlobs(MultipleMutations.class)); - this.data - .setTargetTests(predicateFor(com.example.FullyCoveredTesteeTest.class)); - this.data.setFeatures(Collections.singletonList("+CLASSLIMIT(limit[1])")); - createAndRun(); - verifyResults(NO_COVERAGE); - } - - @Test - public void shouldWorkWithEasyMock() { - this.data.setTargetClasses(asGlobs(CoveredByEasyMock.class)); - this.data.setTargetTests(predicateFor(com.example.EasyMockTest.class)); - createAndRun(); - verifyResults(KILLED, KILLED, KILLED); - } - - @Test - public void shouldWorkWithMockitoJUnitRunner() { - this.data.setTargetClasses(asList("com.example.MockitoCallFoo")); - this.data.setTargetTests(predicateFor(com.example.MockitoRunnerTest.class)); - this.data.setVerbose(true); - createAndRun(); - verifyResults(KILLED); - } - - @Test(expected = PitHelpError.class) - public void shouldReportHelpfulErrorIfNoMutationsFounds() { - this.data.setFailWhenNoMutations(true); - this.data.setTargetClasses(asList("foo")); - createAndRun(); - } - - @Test - public void shouldExcludeFilteredTests() { - this.data.setTargetTests(predicateFor("com.example.*FullyCoveredTestee*")); - this.data.setTargetClasses(asList("com.example.FullyCovered*")); - this.data.setExcludedTestClasses(predicateFor(FullyCoveredTesteeTest.class)); - createAndRun(); - verifyResults(NO_COVERAGE); - } - - @Test - public void willAllowExcludedClassesToBeReIncludedViaSuite() { - this.data - .setTargetTests(predicateFor("com.example.*SuiteForFullyCovered*")); - this.data.setTargetClasses(asList("com.example.FullyCovered*")); - this.data.setExcludedClasses(asGlobs(FullyCoveredTesteeTest.class)); - createAndRun(); - verifyResults(KILLED); - } - - @Test(expected = PitHelpError.class) - public void shouldExcludeFilteredClasses() { - this.data.setFailWhenNoMutations(true); - this.data.setTargetClasses(asGlobs(FullyCoveredTestee.class)); - this.data.setExcludedClasses(asGlobs(FullyCoveredTestee.class)); - createAndRun(); - } - - @Test - public void shouldMutateClassesSuppliedToAlternateClassPath() - throws IOException { - // yes, this is horrid - final String location = FileUtil.randomFilename() + ".jar"; - try { - try (FileOutputStream fos = new FileOutputStream(location)) { - final InputStream stream = IsolationUtils.getContextClassLoader() - .getResourceAsStream("outofcp.jar"); - copy(stream, fos); - } - - this.data.setTargetClasses(asList("com.outofclasspath.*Mutee*")); - this.data.setTargetTests(predicateFor("com.outofclasspath.*")); - - final List cp = new ArrayList<>(); - cp.addAll(ClassPath.getClassPathElementsAsPaths()); - cp.add(location); - - this.data.setClassPathElements(cp); - this.data.setDependencyAnalysisMaxDistance(-1); - this.data.setExcludedClasses(asList("*Power*", "*JMockit*")); - createAndRun(); - verifyResults(KILLED); - } finally { - new File(location).delete(); - } - } - - @Test - public void shouldSupportTestNG() { - this.data - .setTargetClasses(asList("com.example.testng.FullyCovered*")); - this.data.setVerbose(true); - this.data.setTestPlugin("testng"); - createAndRun(); - verifyResults(KILLED); - } - - @Test(timeout = ONE_MINUTE) - public void shouldTerminateWhenThreadpoolCreated() { - this.data.setTargetClasses(asGlobs(KeepAliveThread.class)); - this.data - .setTargetTests(predicateFor(com.example.KeepAliveThreadTest.class)); - createAndRun(); - verifyResults(SURVIVED); - } - - @Test - public void shouldMarkChildJVMCrashesAsRunErrors() { - setMutators("NEGATE_CONDITIONALS"); - this.data.setTargetClasses(asGlobs(CrashesJVMWhenMutated.class)); - this.data - .setTargetTests(predicateFor(com.example.TestCrashesJVMWhenMutated.class)); - createAndRun(); - - verifyResults(RUN_ERROR); - - } - - @Test - public void shouldCombineAndKillInlinedMutationsInFinallyBlocks() { - setMutators("INCREMENTS"); - this.data.setTargetClasses(asGlobs(HasMutationsInFinallyBlock.class)); - this.data.setTargetTests(predicateFor(HasMutationInFinallyBlockTest.class)); - this.data.setDetectInlinedCode(true); - createAndRun(); - - verifyResults(KILLED); - } - - @Test - public void shouldUseTestsDefinedInASuppliedJUnitThreeSuite() { - setMutators("RETURN_VALS"); - this.data.setTargetClasses(asGlobs(CoveredByJUnitThreeSuite.class)); - this.data.setTargetTests(predicateFor(JUnitThreeSuite.class)); - this.data.setVerbose(true); - createAndRun(); - - verifyResults(KILLED); - } - - @Test - public void shouldReportCombinedCoveredButNotTestedMutationsInFinallyBlocksAsSurvived() { - setMutators("INCREMENTS"); - this.data.setTargetClasses(asGlobs(HasMutationsInFinallyBlock.class)); - this.data - .setTargetTests(predicateFor(HasMutationInFinallyBlockNonTest.class)); - this.data.setDetectInlinedCode(true); - createAndRun(); - - verifyResults(SURVIVED); - } - - @Test - public void shouldExitAfterFirstFailureWhenTestClassAnnotatedWithBeforeClass() { - setMutators("RETURN_VALS"); - this.data - .setTargetClasses(asGlobs(CoveredByABeforeAfterClass.class)); - this.data.setTargetTests(predicateFor(BeforeAfterClassTest.class)); - - createAndRun(); - - verifyResults(KILLED); - assertEquals(1, this.metaDataExtractor.getNumberOfTestsRun()); - } - - @Test - public void shouldKillMutationsWhenMutationsPreventsConstructionOfTestClass() { - setMutators("RETURN_VALS"); - - this.data - .setTargetClasses(asGlobs(com.example.mutatablecodeintest.Mutee.class)); - this.data - .setTargetTests(predicateFor(com.example.mutatablecodeintest.MuteeTest.class)); - - createAndRun(); - - verifyResults(KILLED); - } - - @Test - public void shouldKillMutationsWhenKillingTestClassContainsAnIgnoreOnAnotherMethod() { - setMutators("RETURN_VALS"); - - this.data - .setTargetClasses(asGlobs(com.example.testhasignores.Mutee.class)); - this.data - .setTargetTests(predicateFor(com.example.testhasignores.MuteeTest.class)); - - createAndRun(); - - verifyResults(KILLED); - } - - - @Test - public void shouldNotMutateStaticMethodsOnlyCalledFromInitializer() { - setMutators("VOID_METHOD_CALLS"); - - this.data - .setTargetClasses(asGlobs(com.example.staticinitializers.MethodsCalledOnlyFromInitializer.class)); - - createAndRun(); - - verifyResults(); - } - - @Test - public void willMutateStaticMethodsCalledFromInitializerAndElsewhere() { - setMutators("VOID_METHOD_CALLS"); - - this.data - .setTargetClasses(asGlobs(com.example.staticinitializers.MethodsCalledFromInitializerAndElseWhere.class)); - - createAndRun(); - - // would prefer NO_COVERAGE here - verifyResults(); - } - - @Test - public void shouldMutateNonPrivateStaticMethodsCalledFromInitializerOnly() { - setMutators("VOID_METHOD_CALLS"); - - this.data - .setTargetClasses(asGlobs(com.example.staticinitializers.NonPrivateMethodsCalledFromInitializerOnly.class)); - - createAndRun(); - - verifyResults(NO_COVERAGE,NO_COVERAGE,NO_COVERAGE); - } - - @Test - public void willMutatePriveMethodsCalledInChainFromInitializer() { - setMutators("VOID_METHOD_CALLS"); - - this.data - .setTargetClasses(asGlobs(com.example.staticinitializers.MethodsCalledInChainFromStaticInitializer.class)); - - createAndRun(); - - // would prefer removed here - verifyResults(NO_COVERAGE); - } - - @Test - public void shouldNotMutateClassesAnnotatedWithGenerated() { - setMutators("RETURN_VALS"); - this.data - .setTargetClasses(asGlobs(AnnotatedToAvoidAtClassLevel.class)); - - createAndRun(); - - verifyResults(); - } - - @Generated - public static class AnnotatedToAvoidAtClassLevel { - public int mutateMe() { - return 42; - } - } - - - private static void copy(final InputStream in, final OutputStream out) - throws IOException { - // Read bytes and write to destination until eof - - final byte[] buf = new byte[1024]; - int len = 0; - while ((len = in.read(buf)) >= 0) { - out.write(buf, 0, len); - } - } - - private static Collection asGlobs(Class clazz) { - return Collections.singleton(clazz.getName()); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest; + +import static java.util.Arrays.asList; +import static org.junit.Assert.assertEquals; +import static org.pitest.mutationtest.DetectionStatus.KILLED; +import static org.pitest.mutationtest.DetectionStatus.NO_COVERAGE; +import static org.pitest.mutationtest.DetectionStatus.RUN_ERROR; +import static org.pitest.mutationtest.DetectionStatus.SURVIVED; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.pitest.SystemTest; +import org.pitest.classpath.ClassPath; +import org.pitest.help.PitHelpError; +import org.pitest.mutationtest.engine.gregor.Generated; +import org.pitest.util.FileUtil; +import org.pitest.util.IsolationUtils; + +import com.example.BeforeAfterClassTest; +import com.example.CoveredByABeforeAfterClass; +import com.example.CoveredByEasyMock; +import com.example.CoveredByJUnitThreeSuite; +import com.example.CrashesJVMWhenMutated; +import com.example.FailsTestWhenEnvVariableSetTestee; +import com.example.FullyCoveredTestee; +import com.example.FullyCoveredTesteeTest; +import com.example.HasMutationInFinallyBlockNonTest; +import com.example.HasMutationInFinallyBlockTest; +import com.example.HasMutationsInFinallyBlock; +import com.example.JUnitThreeSuite; +import com.example.KeepAliveThread; +import com.example.MultipleMutations; + +@Category(SystemTest.class) +public class MutationCoverageReportSystemTest extends ReportTestBase { + + private static final int ONE_MINUTE = 60000; + + @Before + public void excludeTests() { + this.data.setExcludedClasses(asList("*Test")); + this.data.setTestPlugin("junit"); + } + + @Test + public void shouldPickRelevantTestsAndKillMutationsBasedOnCoverageData() { + this.data.setTargetClasses(asList("com.example.FullyCovered*")); + this.data.setVerbose(true); + createAndRun(); + verifyResults(KILLED); + } + + @Test + public void shouldPickRelevantTestsAndKillMutationsBasedOnCoverageDataWhenLimitedByClassReach() { + this.data.setDependencyAnalysisMaxDistance(2); + this.data.setTargetTests(predicateFor("com.example.*FullyCovered*")); + this.data.setTargetClasses(asList("com.example.FullyCovered*")); + createAndRun(); + verifyResults(KILLED); + } + + @Test + public void shouldReportUnCoveredMutations() { + this.data.setTargetClasses(asList("com.example.PartiallyCovered*")); + createAndRun(); + verifyResults(KILLED, NO_COVERAGE); + } + + @Test + public void shouldReportSurvivingMutations() { + this.data + .setTargetClasses(asList("com.example.CoveredButOnlyPartiallyTested*")); + createAndRun(); + verifyResults(KILLED, SURVIVED); + } + + + @Test(expected = PitHelpError.class) + public void shouldFailRunWithHelpfulMessageIfTestsNotGreen() { + setMutators("MATH"); + this.data + .setTargetClasses(asList("com.example.FailsTestWhenEnvVariableSet*")); + this.data.addChildJVMArgs(Arrays.asList("-D" + + FailsTestWhenEnvVariableSetTestee.class.getName() + "=true")); + createAndRun(); + // should not get here + } + + @Test + public void shouldLoadResoucesOffClassPathFromFolderWithSpaces() { + setMutators("RETURN_VALS"); + this.data + .setTargetClasses(asList("com.example.LoadsResourcesFromClassPath*")); + this.data.setVerbose(true); + createAndRun(); + verifyResults(KILLED); + } + + @Test + public void shouldPickRelevantTestsFromSuppliedTestSuites() { + this.data.setTargetClasses(asList("com.example.FullyCovered*")); + this.data + .setTargetTests(predicateFor(com.example.SuiteForFullyCovered.class)); + createAndRun(); + verifyResults(KILLED); + } + + @Test + public void shouldNotMutateMethodsMatchingExclusionPredicate() { + this.data.setTargetClasses(asList("com.example.HasExcludedMethods*")); + this.data.setExcludedMethods(Arrays.asList("excludeMe")); + createAndRun(); + verifyResults(); + } + + @Test + public void shouldLimitNumberOfMutationsPerClass() { + this.data.setTargetClasses(asGlobs(MultipleMutations.class)); + this.data + .setTargetTests(predicateFor(com.example.FullyCoveredTesteeTest.class)); + this.data.setFeatures(Collections.singletonList("+CLASSLIMIT(limit[1])")); + createAndRun(); + verifyResults(NO_COVERAGE); + } + + @Test + public void shouldWorkWithEasyMock() { + this.data.setTargetClasses(asGlobs(CoveredByEasyMock.class)); + this.data.setTargetTests(predicateFor(com.example.EasyMockTest.class)); + createAndRun(); + verifyResults(KILLED, KILLED, KILLED); + } + + @Test + public void shouldWorkWithMockitoJUnitRunner() { + this.data.setTargetClasses(asList("com.example.MockitoCallFoo")); + this.data.setTargetTests(predicateFor(com.example.MockitoRunnerTest.class)); + this.data.setVerbose(true); + createAndRun(); + verifyResults(KILLED); + } + + @Test(expected = PitHelpError.class) + public void shouldReportHelpfulErrorIfNoMutationsFounds() { + this.data.setFailWhenNoMutations(true); + this.data.setTargetClasses(asList("foo")); + createAndRun(); + } + + @Test + public void shouldExcludeFilteredTests() { + this.data.setTargetTests(predicateFor("com.example.*FullyCoveredTestee*")); + this.data.setTargetClasses(asList("com.example.FullyCovered*")); + this.data.setExcludedTestClasses(predicateFor(FullyCoveredTesteeTest.class)); + createAndRun(); + verifyResults(NO_COVERAGE); + } + + @Test + public void willAllowExcludedClassesToBeReIncludedViaSuite() { + this.data + .setTargetTests(predicateFor("com.example.*SuiteForFullyCovered*")); + this.data.setTargetClasses(asList("com.example.FullyCovered*")); + this.data.setExcludedClasses(asGlobs(FullyCoveredTesteeTest.class)); + createAndRun(); + verifyResults(KILLED); + } + + @Test(expected = PitHelpError.class) + public void shouldExcludeFilteredClasses() { + this.data.setFailWhenNoMutations(true); + this.data.setTargetClasses(asGlobs(FullyCoveredTestee.class)); + this.data.setExcludedClasses(asGlobs(FullyCoveredTestee.class)); + createAndRun(); + } + + @Test + public void shouldMutateClassesSuppliedToAlternateClassPath() + throws IOException { + // yes, this is horrid + final String location = FileUtil.randomFilename() + ".jar"; + try { + try (FileOutputStream fos = new FileOutputStream(location)) { + final InputStream stream = IsolationUtils.getContextClassLoader() + .getResourceAsStream("outofcp.jar"); + copy(stream, fos); + } + + this.data.setTargetClasses(asList("com.outofclasspath.*Mutee*")); + this.data.setTargetTests(predicateFor("com.outofclasspath.*")); + + final List cp = new ArrayList<>(); + cp.addAll(ClassPath.getClassPathElementsAsPaths()); + cp.add(location); + + this.data.setClassPathElements(cp); + this.data.setDependencyAnalysisMaxDistance(-1); + this.data.setExcludedClasses(asList("*Power*", "*JMockit*")); + createAndRun(); + verifyResults(KILLED); + } finally { + new File(location).delete(); + } + } + + @Test + public void shouldSupportTestNG() { + this.data + .setTargetClasses(asList("com.example.testng.FullyCovered*")); + this.data.setVerbose(true); + this.data.setTestPlugin("testng"); + createAndRun(); + verifyResults(KILLED); + } + + @Test(timeout = ONE_MINUTE) + public void shouldTerminateWhenThreadpoolCreated() { + this.data.setTargetClasses(asGlobs(KeepAliveThread.class)); + this.data + .setTargetTests(predicateFor(com.example.KeepAliveThreadTest.class)); + createAndRun(); + verifyResults(SURVIVED); + } + + @Test + public void shouldMarkChildJVMCrashesAsRunErrors() { + setMutators("NEGATE_CONDITIONALS"); + this.data.setTargetClasses(asGlobs(CrashesJVMWhenMutated.class)); + this.data + .setTargetTests(predicateFor(com.example.TestCrashesJVMWhenMutated.class)); + createAndRun(); + + verifyResults(RUN_ERROR); + + } + + @Test + public void shouldCombineAndKillInlinedMutationsInFinallyBlocks() { + setMutators("INCREMENTS"); + this.data.setTargetClasses(asGlobs(HasMutationsInFinallyBlock.class)); + this.data.setTargetTests(predicateFor(HasMutationInFinallyBlockTest.class)); + this.data.setDetectInlinedCode(true); + createAndRun(); + + verifyResults(KILLED); + } + + @Test + public void shouldUseTestsDefinedInASuppliedJUnitThreeSuite() { + setMutators("RETURN_VALS"); + this.data.setTargetClasses(asGlobs(CoveredByJUnitThreeSuite.class)); + this.data.setTargetTests(predicateFor(JUnitThreeSuite.class)); + this.data.setVerbose(true); + createAndRun(); + + verifyResults(KILLED); + } + + @Test + public void shouldReportCombinedCoveredButNotTestedMutationsInFinallyBlocksAsSurvived() { + setMutators("INCREMENTS"); + this.data.setTargetClasses(asGlobs(HasMutationsInFinallyBlock.class)); + this.data + .setTargetTests(predicateFor(HasMutationInFinallyBlockNonTest.class)); + this.data.setDetectInlinedCode(true); + createAndRun(); + + verifyResults(SURVIVED); + } + + @Test + public void shouldExitAfterFirstFailureWhenTestClassAnnotatedWithBeforeClass() { + setMutators("RETURN_VALS"); + this.data + .setTargetClasses(asGlobs(CoveredByABeforeAfterClass.class)); + this.data.setTargetTests(predicateFor(BeforeAfterClassTest.class)); + + createAndRun(); + + verifyResults(KILLED); + assertEquals(1, this.metaDataExtractor.getNumberOfTestsRun()); + } + + @Test + public void shouldKillMutationsWhenMutationsPreventsConstructionOfTestClass() { + setMutators("RETURN_VALS"); + + this.data + .setTargetClasses(asGlobs(com.example.mutatablecodeintest.Mutee.class)); + this.data + .setTargetTests(predicateFor(com.example.mutatablecodeintest.MuteeTest.class)); + + createAndRun(); + + verifyResults(KILLED); + } + + @Test + public void shouldKillMutationsWhenKillingTestClassContainsAnIgnoreOnAnotherMethod() { + setMutators("RETURN_VALS"); + + this.data + .setTargetClasses(asGlobs(com.example.testhasignores.Mutee.class)); + this.data + .setTargetTests(predicateFor(com.example.testhasignores.MuteeTest.class)); + + createAndRun(); + + verifyResults(KILLED); + } + + + @Test + public void shouldNotMutateStaticMethodsOnlyCalledFromInitializer() { + setMutators("VOID_METHOD_CALLS"); + + this.data + .setTargetClasses(asGlobs(com.example.staticinitializers.MethodsCalledOnlyFromInitializer.class)); + + createAndRun(); + + verifyResults(); + } + + @Test + public void willMutateStaticMethodsCalledFromInitializerAndElsewhere() { + setMutators("VOID_METHOD_CALLS"); + + this.data + .setTargetClasses(asGlobs(com.example.staticinitializers.MethodsCalledFromInitializerAndElseWhere.class)); + + createAndRun(); + + // would prefer NO_COVERAGE here + verifyResults(); + } + + @Test + public void shouldMutateNonPrivateStaticMethodsCalledFromInitializerOnly() { + setMutators("VOID_METHOD_CALLS"); + + this.data + .setTargetClasses(asGlobs(com.example.staticinitializers.NonPrivateMethodsCalledFromInitializerOnly.class)); + + createAndRun(); + + verifyResults(NO_COVERAGE,NO_COVERAGE,NO_COVERAGE); + } + + @Test + public void willMutatePriveMethodsCalledInChainFromInitializer() { + setMutators("VOID_METHOD_CALLS"); + + this.data + .setTargetClasses(asGlobs(com.example.staticinitializers.MethodsCalledInChainFromStaticInitializer.class)); + + createAndRun(); + + // would prefer removed here + verifyResults(NO_COVERAGE); + } + + @Test + public void shouldNotMutateClassesAnnotatedWithGenerated() { + setMutators("RETURN_VALS"); + this.data + .setTargetClasses(asGlobs(AnnotatedToAvoidAtClassLevel.class)); + + createAndRun(); + + verifyResults(); + } + + @Generated + public static class AnnotatedToAvoidAtClassLevel { + public int mutateMe() { + return 42; + } + } + + + private static void copy(final InputStream in, final OutputStream out) + throws IOException { + // Read bytes and write to destination until eof + + final byte[] buf = new byte[1024]; + int len = 0; + while ((len = in.read(buf)) >= 0) { + out.write(buf, 0, len); + } + } + + private static Collection asGlobs(Class clazz) { + return Collections.singleton(clazz.getName()); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/MutationMetaDataTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/MutationMetaDataTest.java index f8b09d563..b1b04d1c4 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/MutationMetaDataTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/MutationMetaDataTest.java @@ -1,68 +1,68 @@ -package org.pitest.mutationtest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.pitest.mutationtest.LocationMother.aMutationId; -import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; - -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.mutationtest.engine.MutationDetails; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class MutationMetaDataTest { - - @Test - public void shouldPartitionResultsByMutatedClass() { - final MutationResult a = makeResult("Foo", "a"); - final MutationResult b = makeResult("Bar", "a"); - final MutationResult c = makeResult("Foo", "b"); - final MutationResult d = makeResult("Foo", "c"); - - final MutationMetaData testee = new MutationMetaData(Arrays.asList(a, b, c, d)); - final Collection actual = testee.toClassResults(); - - assertThat(actual).hasSize(2); - - final Iterator it = actual.iterator(); - final ClassMutationResults first = it.next(); - final ClassMutationResults second = it.next(); - - assertThat(first.getMutatedClass()).isEqualTo(ClassName.fromString("Bar")); - assertThat(first.getMutations()).hasSize(1); - - assertThat(second.getMutatedClass()).isEqualTo(ClassName.fromString("Foo")); - assertThat(second.getMutations()).hasSize(3); - - } - - @Test - public void shouldNotCreateEmptyClassResultsObjects() { - final MutationMetaData testee = new MutationMetaData( - Collections. emptyList()); - assertThat(testee.toClassResults()).isEmpty(); - } - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(MutationMetaData.class).verify(); - } - - private MutationResult makeResult(String clazz, String method) { - final Location location = Location.location(ClassName.fromString(clazz), - MethodName.fromString(method), "()V"); - final MutationDetails md = aMutationDetail().withId( - aMutationId().withLocation(location)).build(); - final MutationResult mr = new MutationResult(md, - new MutationStatusTestPair(0, DetectionStatus.KILLED)); - return mr; - } - -} +package org.pitest.mutationtest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.pitest.mutationtest.LocationMother.aMutationId; +import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; + +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.mutationtest.engine.MutationDetails; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class MutationMetaDataTest { + + @Test + public void shouldPartitionResultsByMutatedClass() { + final MutationResult a = makeResult("Foo", "a"); + final MutationResult b = makeResult("Bar", "a"); + final MutationResult c = makeResult("Foo", "b"); + final MutationResult d = makeResult("Foo", "c"); + + final MutationMetaData testee = new MutationMetaData(Arrays.asList(a, b, c, d)); + final Collection actual = testee.toClassResults(); + + assertThat(actual).hasSize(2); + + final Iterator it = actual.iterator(); + final ClassMutationResults first = it.next(); + final ClassMutationResults second = it.next(); + + assertThat(first.getMutatedClass()).isEqualTo(ClassName.fromString("Bar")); + assertThat(first.getMutations()).hasSize(1); + + assertThat(second.getMutatedClass()).isEqualTo(ClassName.fromString("Foo")); + assertThat(second.getMutations()).hasSize(3); + + } + + @Test + public void shouldNotCreateEmptyClassResultsObjects() { + final MutationMetaData testee = new MutationMetaData( + Collections. emptyList()); + assertThat(testee.toClassResults()).isEmpty(); + } + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(MutationMetaData.class).verify(); + } + + private MutationResult makeResult(String clazz, String method) { + final Location location = Location.location(ClassName.fromString(clazz), + MethodName.fromString(method), "()V"); + final MutationDetails md = aMutationDetail().withId( + aMutationId().withLocation(location)).build(); + final MutationResult mr = new MutationResult(md, + new MutationStatusTestPair(0, DetectionStatus.KILLED)); + return mr; + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/MutationResultTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/MutationResultTest.java index 9707ef63f..ff1f480e6 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/MutationResultTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/MutationResultTest.java @@ -1,53 +1,53 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class MutationResultTest { - - private MutationResult testee; - - @Test - public void shouldReturnNameOfKillingTestWhenKnown() { - this.testee = new MutationResult(null, new MutationStatusTestPair(1, - DetectionStatus.KILLED, "good test")); - assertEquals("good test", this.testee.getKillingTestDescription()); - } - - @Test - public void shouldNoneWhenNoKillingTest() { - this.testee = new MutationResult(null, new MutationStatusTestPair(1, - DetectionStatus.TIMED_OUT)); - assertEquals("none", this.testee.getKillingTestDescription()); - } - - @Test - public void shouldReturnStatusDescription() { - this.testee = new MutationResult(null, new MutationStatusTestPair(1, - DetectionStatus.TIMED_OUT)); - assertEquals("TIMED_OUT", this.testee.getStatusDescription()); - } - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(MutationResult.class).verify(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class MutationResultTest { + + private MutationResult testee; + + @Test + public void shouldReturnNameOfKillingTestWhenKnown() { + this.testee = new MutationResult(null, new MutationStatusTestPair(1, + DetectionStatus.KILLED, "good test")); + assertEquals("good test", this.testee.getKillingTestDescription()); + } + + @Test + public void shouldNoneWhenNoKillingTest() { + this.testee = new MutationResult(null, new MutationStatusTestPair(1, + DetectionStatus.TIMED_OUT)); + assertEquals("none", this.testee.getKillingTestDescription()); + } + + @Test + public void shouldReturnStatusDescription() { + this.testee = new MutationResult(null, new MutationStatusTestPair(1, + DetectionStatus.TIMED_OUT)); + assertEquals("TIMED_OUT", this.testee.getStatusDescription()); + } + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(MutationResult.class).verify(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/MutationStatusMapTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/MutationStatusMapTest.java index 876089cac..395eee981 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/MutationStatusMapTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/MutationStatusMapTest.java @@ -1,119 +1,119 @@ -package org.pitest.mutationtest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.pitest.mutationtest.LocationMother.aMutationId; -import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.LocationMother.MutationIdentifierBuilder; -import org.pitest.mutationtest.engine.MutationDetails; - -public class MutationStatusMapTest { - - private MutationStatusMap testee; - - private MutationDetails details; - - private MutationDetails detailsTwo; - - @Before - public void setUp() { - this.testee = new MutationStatusMap(); - final MutationIdentifierBuilder id = aMutationId().withIndex(1); - this.details = aMutationDetail().withId(id.withIndex(1)).build(); - this.detailsTwo = aMutationDetail().withId(id.withIndex(2)).build(); - } - - @Test - public void shouldDetectWhenHasUnrunMutations() { - this.testee.setStatusForMutation(this.details, DetectionStatus.NOT_STARTED); - assertTrue(this.testee.hasUnrunMutations()); - } - - @Test - public void shouldDetectWhenDoesNotHaveUnrunMutations() { - this.testee.setStatusForMutation(this.details, DetectionStatus.KILLED); - assertFalse(this.testee.hasUnrunMutations()); - } - - @Test - public void shouldReturnUnRunMutationsWhenSomePresent() { - this.testee.setStatusForMutations( - Arrays.asList(this.details, this.detailsTwo), - DetectionStatus.NOT_STARTED); - assertThat(this.testee.getUnrunMutations()).contains(this.details, - this.detailsTwo); - } - - @Test - public void shouldReturnEmptyListMutationsWhenNoUnrunMutationsPresent() { - this.testee.setStatusForMutations( - Arrays.asList(this.details, this.detailsTwo), DetectionStatus.STARTED); - assertEquals(Collections.emptyList(), this.testee.getUnrunMutations()); - } - - @Test - public void shouldReturnUnfinishedMutationsWhenSomePresent() { - this.testee.setStatusForMutations( - Arrays.asList(this.details, this.detailsTwo), DetectionStatus.STARTED); - assertThat(this.testee.getUnfinishedRuns()).contains(this.details, - this.detailsTwo); - } - - @Test - public void shouldReturnEmptyListMutationsWhenNoUnfinishedMutationsPresent() { - this.testee.setStatusForMutations( - Arrays.asList(this.details, this.detailsTwo), DetectionStatus.KILLED); - assertEquals(Collections.emptyList(), this.testee.getUnrunMutations()); - } - - @Test - public void shouldCreateResultsForAllMutations() { - final MutationStatusTestPair statusPairOne = new MutationStatusTestPair(42, - DetectionStatus.KILLED, "foo"); - final MutationResult resultOne = new MutationResult(this.details, - statusPairOne); - this.testee.setStatusForMutation(this.details, statusPairOne); - - final MutationStatusTestPair statusPairTwo = new MutationStatusTestPair(42, - DetectionStatus.RUN_ERROR, "bar"); - final MutationResult resultTwo = new MutationResult(this.detailsTwo, - statusPairTwo); - this.testee.setStatusForMutation(this.detailsTwo, statusPairTwo); - - assertThat(this.testee.createMutationResults()).contains(resultOne, - resultTwo); - } - - @Test - public void shouldSetStatusToUncoveredWhenMutationHasNoTests() { - this.testee.setStatusForMutations( - Arrays.asList(this.details, this.detailsTwo), - DetectionStatus.NOT_STARTED); - this.testee.markUncoveredMutations(); - assertEquals(Collections.emptyList(), this.testee.getUnrunMutations()); - - final MutationStatusTestPair statusPairOne = new MutationStatusTestPair(42, - DetectionStatus.NO_COVERAGE, "foo"); - final MutationResult resultOne = new MutationResult(this.details, - statusPairOne); - this.testee.setStatusForMutation(this.details, statusPairOne); - - final MutationStatusTestPair statusPairTwo = new MutationStatusTestPair(42, - DetectionStatus.NO_COVERAGE, "bar"); - final MutationResult resultTwo = new MutationResult(this.detailsTwo, - statusPairTwo); - this.testee.setStatusForMutation(this.detailsTwo, statusPairTwo); - - assertThat(this.testee.createMutationResults()).contains(resultOne, - resultTwo); - } - -} +package org.pitest.mutationtest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.pitest.mutationtest.LocationMother.aMutationId; +import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.LocationMother.MutationIdentifierBuilder; +import org.pitest.mutationtest.engine.MutationDetails; + +public class MutationStatusMapTest { + + private MutationStatusMap testee; + + private MutationDetails details; + + private MutationDetails detailsTwo; + + @Before + public void setUp() { + this.testee = new MutationStatusMap(); + final MutationIdentifierBuilder id = aMutationId().withIndex(1); + this.details = aMutationDetail().withId(id.withIndex(1)).build(); + this.detailsTwo = aMutationDetail().withId(id.withIndex(2)).build(); + } + + @Test + public void shouldDetectWhenHasUnrunMutations() { + this.testee.setStatusForMutation(this.details, DetectionStatus.NOT_STARTED); + assertTrue(this.testee.hasUnrunMutations()); + } + + @Test + public void shouldDetectWhenDoesNotHaveUnrunMutations() { + this.testee.setStatusForMutation(this.details, DetectionStatus.KILLED); + assertFalse(this.testee.hasUnrunMutations()); + } + + @Test + public void shouldReturnUnRunMutationsWhenSomePresent() { + this.testee.setStatusForMutations( + Arrays.asList(this.details, this.detailsTwo), + DetectionStatus.NOT_STARTED); + assertThat(this.testee.getUnrunMutations()).contains(this.details, + this.detailsTwo); + } + + @Test + public void shouldReturnEmptyListMutationsWhenNoUnrunMutationsPresent() { + this.testee.setStatusForMutations( + Arrays.asList(this.details, this.detailsTwo), DetectionStatus.STARTED); + assertEquals(Collections.emptyList(), this.testee.getUnrunMutations()); + } + + @Test + public void shouldReturnUnfinishedMutationsWhenSomePresent() { + this.testee.setStatusForMutations( + Arrays.asList(this.details, this.detailsTwo), DetectionStatus.STARTED); + assertThat(this.testee.getUnfinishedRuns()).contains(this.details, + this.detailsTwo); + } + + @Test + public void shouldReturnEmptyListMutationsWhenNoUnfinishedMutationsPresent() { + this.testee.setStatusForMutations( + Arrays.asList(this.details, this.detailsTwo), DetectionStatus.KILLED); + assertEquals(Collections.emptyList(), this.testee.getUnrunMutations()); + } + + @Test + public void shouldCreateResultsForAllMutations() { + final MutationStatusTestPair statusPairOne = new MutationStatusTestPair(42, + DetectionStatus.KILLED, "foo"); + final MutationResult resultOne = new MutationResult(this.details, + statusPairOne); + this.testee.setStatusForMutation(this.details, statusPairOne); + + final MutationStatusTestPair statusPairTwo = new MutationStatusTestPair(42, + DetectionStatus.RUN_ERROR, "bar"); + final MutationResult resultTwo = new MutationResult(this.detailsTwo, + statusPairTwo); + this.testee.setStatusForMutation(this.detailsTwo, statusPairTwo); + + assertThat(this.testee.createMutationResults()).contains(resultOne, + resultTwo); + } + + @Test + public void shouldSetStatusToUncoveredWhenMutationHasNoTests() { + this.testee.setStatusForMutations( + Arrays.asList(this.details, this.detailsTwo), + DetectionStatus.NOT_STARTED); + this.testee.markUncoveredMutations(); + assertEquals(Collections.emptyList(), this.testee.getUnrunMutations()); + + final MutationStatusTestPair statusPairOne = new MutationStatusTestPair(42, + DetectionStatus.NO_COVERAGE, "foo"); + final MutationResult resultOne = new MutationResult(this.details, + statusPairOne); + this.testee.setStatusForMutation(this.details, statusPairOne); + + final MutationStatusTestPair statusPairTwo = new MutationStatusTestPair(42, + DetectionStatus.NO_COVERAGE, "bar"); + final MutationResult resultTwo = new MutationResult(this.detailsTwo, + statusPairTwo); + this.testee.setStatusForMutation(this.detailsTwo, statusPairTwo); + + assertThat(this.testee.createMutationResults()).contains(resultOne, + resultTwo); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/NullAnalyser.java b/pitest-entry/src/test/java/org/pitest/mutationtest/NullAnalyser.java index b27063789..82617ea00 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/NullAnalyser.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/NullAnalyser.java @@ -1,26 +1,26 @@ -package org.pitest.mutationtest; - -import java.util.Collection; -import java.util.function.Function; - -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.MutationDetails; - -/** - * Always selects the start status for a mutation - * - */ -public class NullAnalyser implements MutationAnalyser { - - @Override - public Collection analyse( - final Collection mutationsForClasses) { - return FCollection.map(mutationsForClasses, mutationToResult()); - } - - private Function mutationToResult() { - return a -> new MutationResult(a, new MutationStatusTestPair(0, - DetectionStatus.NOT_STARTED)); - } - -} +package org.pitest.mutationtest; + +import java.util.Collection; +import java.util.function.Function; + +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.MutationDetails; + +/** + * Always selects the start status for a mutation + * + */ +public class NullAnalyser implements MutationAnalyser { + + @Override + public Collection analyse( + final Collection mutationsForClasses) { + return FCollection.map(mutationsForClasses, mutationToResult()); + } + + private Function mutationToResult() { + return a -> new MutationResult(a, new MutationStatusTestPair(0, + DetectionStatus.NOT_STARTED)); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/ReportTestBase.java b/pitest-entry/src/test/java/org/pitest/mutationtest/ReportTestBase.java index 3457b6b15..7bd3be68b 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/ReportTestBase.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/ReportTestBase.java @@ -1,150 +1,150 @@ -package org.pitest.mutationtest; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.function.Predicate; - -import org.junit.Before; -import org.pitest.classpath.CodeSource; -import org.pitest.classpath.PathFilter; -import org.pitest.classpath.ProjectClassPaths; -import org.pitest.coverage.CoverageGenerator; -import org.pitest.coverage.execute.CoverageOptions; -import org.pitest.coverage.execute.DefaultCoverageGenerator; -import org.pitest.coverage.export.NullCoverageExporter; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.config.SettingsFactory; -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; -import org.pitest.mutationtest.incremental.NullHistoryStore; -import org.pitest.mutationtest.tooling.JarCreatingJarFinder; -import org.pitest.mutationtest.tooling.MutationCoverage; -import org.pitest.mutationtest.tooling.MutationStrategies; -import org.pitest.process.DefaultJavaExecutableLocator; -import org.pitest.process.JavaAgent; -import org.pitest.process.LaunchOptions; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.util.Glob; -import org.pitest.util.Timings; -import org.pitest.util.Unchecked; - -public abstract class ReportTestBase { - - protected MetaDataExtractor metaDataExtractor; - protected ReportOptions data; - - private PluginServices plugins; - - @Before - public void setUp() { - this.metaDataExtractor = new MetaDataExtractor(); - this.plugins = PluginServices.makeForContextLoader(); - this.data = new ReportOptions(); - this.data.setSourceDirs(Collections. emptyList()); - this.data.setGroupConfig(new TestGroupConfig()); - this.data.setTestPlugin("junit"); - } - - protected MutationResultListenerFactory listenerFactory() { - return new MutationResultListenerFactory() { - @Override - public MutationResultListener getListener(Properties props, - ListenerArguments args) { - return ReportTestBase.this.metaDataExtractor; - } - - @Override - public String name() { - return null; - } - - @Override - public String description() { - return null; - } - - }; - } - - protected void verifyResults(final DetectionStatus... detectionStatus) { - final List expected = Arrays.asList(detectionStatus); - final List actual = this.metaDataExtractor - .getDetectionStatus(); - - Collections.sort(expected); - Collections.sort(actual); - - assertEquals(expected, actual); - } - - protected Collection> predicateFor(final String... glob) { - return Glob.toGlobPredicates(Arrays.asList(glob)); - } - - protected Collection> predicateFor(final Class clazz) { - return predicateFor(clazz.getName()); - } - - protected void createAndRun() { - final SettingsFactory settings = new SettingsFactory(this.data, this.plugins); - createAndRun(settings); - } - - protected void createAndRun(SettingsFactory settings) { - final JavaAgent agent = new JarCreatingJarFinder(); - try { - - final CoverageOptions coverageOptions = createCoverageOptions(settings.createCoverageOptions().getPitConfig()); - final LaunchOptions launchOptions = new LaunchOptions(agent, - new DefaultJavaExecutableLocator(), this.data.getJvmArgs(), - new HashMap()); - - final PathFilter pf = new PathFilter(p -> true, p -> true); - final ProjectClassPaths cps = new ProjectClassPaths( - this.data.getClassPath(), this.data.createClassesFilter(), pf); - - final Timings timings = new Timings(); - final CodeSource code = new CodeSource(cps); - - final CoverageGenerator coverageDatabase = new DefaultCoverageGenerator( - null, coverageOptions, launchOptions, code, - new NullCoverageExporter(), timings, false); - - final HistoryStore history = new NullHistoryStore(); - - final MutationStrategies strategies = new MutationStrategies( - new GregorEngineFactory(), history, coverageDatabase, - listenerFactory(), null); - - final MutationCoverage testee = new MutationCoverage(strategies, null, - code, this.data, new SettingsFactory(this.data, this.plugins), - timings); - - testee.runReport(); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } finally { - agent.close(); - } - } - - private CoverageOptions createCoverageOptions(TestPluginArguments configuration) { - return new CoverageOptions(this.data.getTargetClasses(),this.data.getExcludedClasses(), - configuration, this.data.isVerbose(), - this.data.getDependencyAnalysisMaxDistance()); - } - - protected void setMutators(final String mutator) { - this.data.setMutators(Arrays.asList(mutator)); - } - -} +package org.pitest.mutationtest; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.function.Predicate; + +import org.junit.Before; +import org.pitest.classpath.CodeSource; +import org.pitest.classpath.PathFilter; +import org.pitest.classpath.ProjectClassPaths; +import org.pitest.coverage.CoverageGenerator; +import org.pitest.coverage.execute.CoverageOptions; +import org.pitest.coverage.execute.DefaultCoverageGenerator; +import org.pitest.coverage.export.NullCoverageExporter; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.config.SettingsFactory; +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; +import org.pitest.mutationtest.incremental.NullHistoryStore; +import org.pitest.mutationtest.tooling.JarCreatingJarFinder; +import org.pitest.mutationtest.tooling.MutationCoverage; +import org.pitest.mutationtest.tooling.MutationStrategies; +import org.pitest.process.DefaultJavaExecutableLocator; +import org.pitest.process.JavaAgent; +import org.pitest.process.LaunchOptions; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.util.Glob; +import org.pitest.util.Timings; +import org.pitest.util.Unchecked; + +public abstract class ReportTestBase { + + protected MetaDataExtractor metaDataExtractor; + protected ReportOptions data; + + private PluginServices plugins; + + @Before + public void setUp() { + this.metaDataExtractor = new MetaDataExtractor(); + this.plugins = PluginServices.makeForContextLoader(); + this.data = new ReportOptions(); + this.data.setSourceDirs(Collections. emptyList()); + this.data.setGroupConfig(new TestGroupConfig()); + this.data.setTestPlugin("junit"); + } + + protected MutationResultListenerFactory listenerFactory() { + return new MutationResultListenerFactory() { + @Override + public MutationResultListener getListener(Properties props, + ListenerArguments args) { + return ReportTestBase.this.metaDataExtractor; + } + + @Override + public String name() { + return null; + } + + @Override + public String description() { + return null; + } + + }; + } + + protected void verifyResults(final DetectionStatus... detectionStatus) { + final List expected = Arrays.asList(detectionStatus); + final List actual = this.metaDataExtractor + .getDetectionStatus(); + + Collections.sort(expected); + Collections.sort(actual); + + assertEquals(expected, actual); + } + + protected Collection> predicateFor(final String... glob) { + return Glob.toGlobPredicates(Arrays.asList(glob)); + } + + protected Collection> predicateFor(final Class clazz) { + return predicateFor(clazz.getName()); + } + + protected void createAndRun() { + final SettingsFactory settings = new SettingsFactory(this.data, this.plugins); + createAndRun(settings); + } + + protected void createAndRun(SettingsFactory settings) { + final JavaAgent agent = new JarCreatingJarFinder(); + try { + + final CoverageOptions coverageOptions = createCoverageOptions(settings.createCoverageOptions().getPitConfig()); + final LaunchOptions launchOptions = new LaunchOptions(agent, + new DefaultJavaExecutableLocator(), this.data.getJvmArgs(), + new HashMap()); + + final PathFilter pf = new PathFilter(p -> true, p -> true); + final ProjectClassPaths cps = new ProjectClassPaths( + this.data.getClassPath(), this.data.createClassesFilter(), pf); + + final Timings timings = new Timings(); + final CodeSource code = new CodeSource(cps); + + final CoverageGenerator coverageDatabase = new DefaultCoverageGenerator( + null, coverageOptions, launchOptions, code, + new NullCoverageExporter(), timings, false); + + final HistoryStore history = new NullHistoryStore(); + + final MutationStrategies strategies = new MutationStrategies( + new GregorEngineFactory(), history, coverageDatabase, + listenerFactory(), null); + + final MutationCoverage testee = new MutationCoverage(strategies, null, + code, this.data, new SettingsFactory(this.data, this.plugins), + timings); + + testee.runReport(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } finally { + agent.close(); + } + } + + private CoverageOptions createCoverageOptions(TestPluginArguments configuration) { + return new CoverageOptions(this.data.getTargetClasses(),this.data.getExcludedClasses(), + configuration, this.data.isVerbose(), + this.data.getDependencyAnalysisMaxDistance()); + } + + protected void setMutators(final String mutator) { + this.data.setMutators(Arrays.asList(mutator)); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/TestMutationTesting.java b/pitest-entry/src/test/java/org/pitest/mutationtest/TestMutationTesting.java index 182102c17..7aa42f2e8 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/TestMutationTesting.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/TestMutationTesting.java @@ -1,424 +1,424 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import static org.junit.Assert.assertEquals; -import static org.pitest.mutationtest.DetectionStatus.KILLED; -import static org.pitest.mutationtest.DetectionStatus.MEMORY_ERROR; -import static org.pitest.mutationtest.DetectionStatus.NON_VIABLE; -import static org.pitest.mutationtest.DetectionStatus.NO_COVERAGE; -import static org.pitest.mutationtest.DetectionStatus.SURVIVED; -import static org.pitest.mutationtest.DetectionStatus.TIMED_OUT; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.mockito.MockitoAnnotations; -import org.pitest.SystemTest; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.classpath.CodeSource; -import org.pitest.classpath.PathFilter; -import org.pitest.classpath.ProjectClassPaths; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.coverage.CoverageGenerator; -import org.pitest.coverage.execute.CoverageOptions; -import org.pitest.coverage.execute.DefaultCoverageGenerator; -import org.pitest.coverage.export.NullCoverageExporter; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.build.CompoundMutationInterceptor; -import org.pitest.mutationtest.build.DefaultGrouper; -import org.pitest.mutationtest.build.DefaultTestPrioritiser; -import org.pitest.mutationtest.build.MutationAnalysisUnit; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.MutationSource; -import org.pitest.mutationtest.build.MutationTestBuilder; -import org.pitest.mutationtest.build.PercentAndConstantTimeoutStrategy; -import org.pitest.mutationtest.build.WorkerFactory; -import org.pitest.mutationtest.config.DefaultDependencyPathPredicate; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; -import org.pitest.mutationtest.execute.MutationAnalysisExecutor; -import org.pitest.mutationtest.tooling.JarCreatingJarFinder; -import org.pitest.process.DefaultJavaExecutableLocator; -import org.pitest.process.JavaAgent; -import org.pitest.process.LaunchOptions; -import org.pitest.simpletest.SimpleTestPlugin; -import org.pitest.simpletest.TestAnnotationForTesting; -import org.pitest.util.IsolationUtils; -import org.pitest.util.Timings; - -import com.example.MutationsInNestedClasses; -import com.example.MutationsInNestedClassesTest; - -@Category(SystemTest.class) -public class TestMutationTesting { - - private MutationAnalysisExecutor mae; - private TestPluginArguments config; - - private MetaDataExtractor metaDataExtractor; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.config = TestPluginArguments.defaults().withTestPlugin(SimpleTestPlugin.NAME); - this.metaDataExtractor = new MetaDataExtractor(); - this.mae = new MutationAnalysisExecutor(1, - Collections - . singletonList(this.metaDataExtractor)); - } - - public static class NoMutations { - - } - - public static class OneMutationOnly { - public static int returnOne() { - return 1; - } - } - - public static class ThreeMutations { - public static int returnOne() { - return 1; - } - - public static int returnTwo() { - return 2; - } - - public static int returnThree() { - return 3; - } - } - - public static class OneMutationFullTest { - @TestAnnotationForTesting - public void testReturnOne() { - assertEquals(1, OneMutationOnly.returnOne()); - } - } - - @Test - public void shouldKillAllCoveredMutations() { - run(OneMutationOnly.class, OneMutationFullTest.class, - "RETURN_VALS"); - verifyResults(KILLED); - } - - public static class ThreeMutationsTwoMeaningfullTests { - @TestAnnotationForTesting - public void testReturnOne() { - assertEquals(1, ThreeMutations.returnOne()); - } - - @TestAnnotationForTesting - public void testReturnTwo() { - assertEquals(2, ThreeMutations.returnTwo()); - } - - @TestAnnotationForTesting - public void coverButDoNotTestReturnThree() { - ThreeMutations.returnThree(); - } - } - - @Test - public void shouldDetectedMixOfSurvivingAndKilledMutations() { - run(ThreeMutations.class, ThreeMutationsTwoMeaningfullTests.class, - "RETURN_VALS"); - verifyResults(SURVIVED, KILLED, KILLED); - } - - public static class FailingTest { - @TestAnnotationForTesting - public void fail() { - assertEquals(1, 2); - } - } - - public static class NoMutationsTest { - @TestAnnotationForTesting - public void pass() { - - } - } - - @Test - public void shouldReportNoResultsIfNoMutationsPossible() { - run(NoMutations.class, NoMutationsTest.class, "RETURN_VALS"); - verifyResults(); - } - - public static class NoTests { - - } - - @Test - public void shouldReportStatusOfNoCoverageWhenNoTestsAvailable() { - run(ThreeMutations.class, NoTests.class, "RETURN_VALS"); - verifyResults(NO_COVERAGE, NO_COVERAGE, NO_COVERAGE); - } - - public static class OneMutationTest { - - } - - public static class InfiniteLoop { - public static int loop() { - int i = 1; - do { - i++; - try { - Thread.sleep(1); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - } while (i < 1); - i++; - return i; - } - } - - public static class InfiniteLoopTest { - @TestAnnotationForTesting() - public void pass() { - assertEquals(3, InfiniteLoop.loop()); - } - } - - @Test(timeout = 30000) - public void shouldDetectAndEscapeFromInfiniteLoopsCausedByMutations() { - run(InfiniteLoop.class, InfiniteLoopTest.class, - "INCREMENTS"); - verifyResults(KILLED, TIMED_OUT); - } - - public static class OneMutationFullTestWithSystemPropertyDependency { - @TestAnnotationForTesting - public void testReturnOne() { - if (System.getProperty("foo").equals("foo")) { - assertEquals(1, OneMutationOnly.returnOne()); - } - } - } - - @Test - public void shouldExportSystemPropertiesToMinionProcess() { - // System.setProperty("foo", "foo"); - // note surefire is configured to launch this test with -Dfoo=foo - run(OneMutationOnly.class, - OneMutationFullTestWithSystemPropertyDependency.class, - "RETURN_VALS"); - verifyResults(KILLED); - } - - public static class UnviableMutationsTest { - @TestAnnotationForTesting - public void test() { - new OneMutationOnly(); - OneMutationOnly.returnOne(); - } - } - - @Test - @Ignore("no longer possible to serialize arbritrary mutators to child") - public void shouldDetectUnviableMutations() { - run(OneMutationOnly.class, UnviableMutationsTest.class, - "UNVIABLE_CLASS_MUTATOR"); - verifyResults(NON_VIABLE, NON_VIABLE); - - } - - public static class EatsMemoryWhenMutated { - public static int loop() throws InterruptedException { - int i = 1; - final List vals = new ArrayList<>(); - Thread.sleep(1500); - do { - i++; - vals.add(new String[9999999]); - vals.add(new String[9999999]); - vals.add(new String[9999999]); - vals.add(new String[9999999]); - } while (i < 1); - i++; - return i; - } - } - - public static class EatsMemoryTest { - @TestAnnotationForTesting() - public void pass() throws InterruptedException { - assertEquals(3, EatsMemoryWhenMutated.loop()); - } - } - - @Ignore("flakey") - @Test(timeout = 30000) - public void shouldRecoverFromOutOfMemoryError() { - run(EatsMemoryWhenMutated.class, EatsMemoryTest.class, - "INCREMENTS"); - verifyResults(KILLED, MEMORY_ERROR); - } - - @Test - public void shouldIsolateMutationsFromNestedClasses() { - // see http://code.google.com/p/pitestrunner/issues/detail?id=17 for full - // description of this issue - run(MutationsInNestedClasses.class, MutationsInNestedClassesTest.class, - "RETURN_VALS"); - verifyResults(SURVIVED, SURVIVED); - } - - @Test - @Ignore("too brittle") - public void shouldRecordCorrectLineNumberForMutations() { - run(OneMutationOnly.class, OneMutationFullTest.class, - "RETURN_VALS"); - verifyLineNumbers(111); - } - - private void run(final Class clazz, final Class test, - final String ... mutators) { - - final ReportOptions data = new ReportOptions(); - - final Set> tests = Collections.singleton(Prelude - .isEqualTo(test.getName())); - data.setTargetTests(tests); - data.setDependencyAnalysisMaxDistance(-1); - - final Set mutees = Collections.singleton(clazz.getName() + "*"); - data.setTargetClasses(mutees); - - data.setTimeoutConstant(PercentAndConstantTimeoutStrategy.DEFAULT_CONSTANT); - data.setTimeoutFactor(PercentAndConstantTimeoutStrategy.DEFAULT_FACTOR); - - final JavaAgent agent = new JarCreatingJarFinder(); - - try { - createEngineAndRun(data, agent, Arrays.asList(mutators)); - } finally { - agent.close(); - } - } - - private void createEngineAndRun(final ReportOptions data, - final JavaAgent agent, - final Collection mutators) { - - // data.setConfiguration(this.config); - final CoverageOptions coverageOptions = createCoverageOptions(data); - - final LaunchOptions launchOptions = new LaunchOptions(agent, - new DefaultJavaExecutableLocator(), data.getJvmArgs(), - new HashMap()); - - final PathFilter pf = new PathFilter( - Prelude.not(new DefaultDependencyPathPredicate()), - Prelude.not(new DefaultDependencyPathPredicate())); - final ProjectClassPaths cps = new ProjectClassPaths(data.getClassPath(), - data.createClassesFilter(), pf); - - final Timings timings = new Timings(); - final CodeSource code = new CodeSource(cps); - - final CoverageGenerator coverageGenerator = new DefaultCoverageGenerator( - null, coverageOptions, launchOptions, code, new NullCoverageExporter(), - timings, false); - - final CoverageDatabase coverageData = coverageGenerator.calculateCoverage(); - - final Collection codeClasses = FCollection.map(code.getCode(), - ClassInfo.toClassName()); - - final EngineArguments arguments = EngineArguments.arguments() - .withMutators(mutators); - - final MutationEngine engine = new GregorEngineFactory().createEngine(arguments); - - final MutationConfig mutationConfig = new MutationConfig(engine, - launchOptions); - - final ClassloaderByteArraySource bas = new ClassloaderByteArraySource( - IsolationUtils.getContextClassLoader()); - - final MutationInterceptor emptyIntercpetor = CompoundMutationInterceptor.nullInterceptor(); - - final MutationSource source = new MutationSource(mutationConfig, new DefaultTestPrioritiser( - coverageData), bas, emptyIntercpetor); - - - final WorkerFactory wf = new WorkerFactory(null, - coverageOptions.getPitConfig(), mutationConfig, arguments, - new PercentAndConstantTimeoutStrategy(data.getTimeoutFactor(), - data.getTimeoutConstant()), data.isVerbose(), data.getClassPath() - .getLocalClassPath()); - - - - - final MutationTestBuilder builder = new MutationTestBuilder(wf, - new NullAnalyser(), source, new DefaultGrouper(0)); - - final List tus = builder - .createMutationTestUnits(codeClasses); - - this.mae.run(tus); - } - - private CoverageOptions createCoverageOptions(ReportOptions data) { - return new CoverageOptions(data.getTargetClasses(),data.getExcludedClasses(), this.config, - data.isVerbose(), data.getDependencyAnalysisMaxDistance()); - } - - protected void verifyResults(final DetectionStatus... detectionStatus) { - final List expected = Arrays.asList(detectionStatus); - final List actual = this.metaDataExtractor - .getDetectionStatus(); - - Collections.sort(expected); - Collections.sort(actual); - - assertEquals(expected, actual); - } - - protected void verifyLineNumbers(final Integer... lineNumbers) { - final List expected = Arrays.asList(lineNumbers); - final List actual = this.metaDataExtractor.getLineNumbers(); - - Collections.sort(expected); - Collections.sort(actual); - - assertEquals(expected, actual); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import static org.junit.Assert.assertEquals; +import static org.pitest.mutationtest.DetectionStatus.KILLED; +import static org.pitest.mutationtest.DetectionStatus.MEMORY_ERROR; +import static org.pitest.mutationtest.DetectionStatus.NON_VIABLE; +import static org.pitest.mutationtest.DetectionStatus.NO_COVERAGE; +import static org.pitest.mutationtest.DetectionStatus.SURVIVED; +import static org.pitest.mutationtest.DetectionStatus.TIMED_OUT; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.mockito.MockitoAnnotations; +import org.pitest.SystemTest; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.classpath.CodeSource; +import org.pitest.classpath.PathFilter; +import org.pitest.classpath.ProjectClassPaths; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.coverage.CoverageGenerator; +import org.pitest.coverage.execute.CoverageOptions; +import org.pitest.coverage.execute.DefaultCoverageGenerator; +import org.pitest.coverage.export.NullCoverageExporter; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.build.CompoundMutationInterceptor; +import org.pitest.mutationtest.build.DefaultGrouper; +import org.pitest.mutationtest.build.DefaultTestPrioritiser; +import org.pitest.mutationtest.build.MutationAnalysisUnit; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.MutationSource; +import org.pitest.mutationtest.build.MutationTestBuilder; +import org.pitest.mutationtest.build.PercentAndConstantTimeoutStrategy; +import org.pitest.mutationtest.build.WorkerFactory; +import org.pitest.mutationtest.config.DefaultDependencyPathPredicate; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; +import org.pitest.mutationtest.execute.MutationAnalysisExecutor; +import org.pitest.mutationtest.tooling.JarCreatingJarFinder; +import org.pitest.process.DefaultJavaExecutableLocator; +import org.pitest.process.JavaAgent; +import org.pitest.process.LaunchOptions; +import org.pitest.simpletest.SimpleTestPlugin; +import org.pitest.simpletest.TestAnnotationForTesting; +import org.pitest.util.IsolationUtils; +import org.pitest.util.Timings; + +import com.example.MutationsInNestedClasses; +import com.example.MutationsInNestedClassesTest; + +@Category(SystemTest.class) +public class TestMutationTesting { + + private MutationAnalysisExecutor mae; + private TestPluginArguments config; + + private MetaDataExtractor metaDataExtractor; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.config = TestPluginArguments.defaults().withTestPlugin(SimpleTestPlugin.NAME); + this.metaDataExtractor = new MetaDataExtractor(); + this.mae = new MutationAnalysisExecutor(1, + Collections + . singletonList(this.metaDataExtractor)); + } + + public static class NoMutations { + + } + + public static class OneMutationOnly { + public static int returnOne() { + return 1; + } + } + + public static class ThreeMutations { + public static int returnOne() { + return 1; + } + + public static int returnTwo() { + return 2; + } + + public static int returnThree() { + return 3; + } + } + + public static class OneMutationFullTest { + @TestAnnotationForTesting + public void testReturnOne() { + assertEquals(1, OneMutationOnly.returnOne()); + } + } + + @Test + public void shouldKillAllCoveredMutations() { + run(OneMutationOnly.class, OneMutationFullTest.class, + "RETURN_VALS"); + verifyResults(KILLED); + } + + public static class ThreeMutationsTwoMeaningfullTests { + @TestAnnotationForTesting + public void testReturnOne() { + assertEquals(1, ThreeMutations.returnOne()); + } + + @TestAnnotationForTesting + public void testReturnTwo() { + assertEquals(2, ThreeMutations.returnTwo()); + } + + @TestAnnotationForTesting + public void coverButDoNotTestReturnThree() { + ThreeMutations.returnThree(); + } + } + + @Test + public void shouldDetectedMixOfSurvivingAndKilledMutations() { + run(ThreeMutations.class, ThreeMutationsTwoMeaningfullTests.class, + "RETURN_VALS"); + verifyResults(SURVIVED, KILLED, KILLED); + } + + public static class FailingTest { + @TestAnnotationForTesting + public void fail() { + assertEquals(1, 2); + } + } + + public static class NoMutationsTest { + @TestAnnotationForTesting + public void pass() { + + } + } + + @Test + public void shouldReportNoResultsIfNoMutationsPossible() { + run(NoMutations.class, NoMutationsTest.class, "RETURN_VALS"); + verifyResults(); + } + + public static class NoTests { + + } + + @Test + public void shouldReportStatusOfNoCoverageWhenNoTestsAvailable() { + run(ThreeMutations.class, NoTests.class, "RETURN_VALS"); + verifyResults(NO_COVERAGE, NO_COVERAGE, NO_COVERAGE); + } + + public static class OneMutationTest { + + } + + public static class InfiniteLoop { + public static int loop() { + int i = 1; + do { + i++; + try { + Thread.sleep(1); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + } while (i < 1); + i++; + return i; + } + } + + public static class InfiniteLoopTest { + @TestAnnotationForTesting() + public void pass() { + assertEquals(3, InfiniteLoop.loop()); + } + } + + @Test(timeout = 30000) + public void shouldDetectAndEscapeFromInfiniteLoopsCausedByMutations() { + run(InfiniteLoop.class, InfiniteLoopTest.class, + "INCREMENTS"); + verifyResults(KILLED, TIMED_OUT); + } + + public static class OneMutationFullTestWithSystemPropertyDependency { + @TestAnnotationForTesting + public void testReturnOne() { + if (System.getProperty("foo").equals("foo")) { + assertEquals(1, OneMutationOnly.returnOne()); + } + } + } + + @Test + public void shouldExportSystemPropertiesToMinionProcess() { + // System.setProperty("foo", "foo"); + // note surefire is configured to launch this test with -Dfoo=foo + run(OneMutationOnly.class, + OneMutationFullTestWithSystemPropertyDependency.class, + "RETURN_VALS"); + verifyResults(KILLED); + } + + public static class UnviableMutationsTest { + @TestAnnotationForTesting + public void test() { + new OneMutationOnly(); + OneMutationOnly.returnOne(); + } + } + + @Test + @Ignore("no longer possible to serialize arbritrary mutators to child") + public void shouldDetectUnviableMutations() { + run(OneMutationOnly.class, UnviableMutationsTest.class, + "UNVIABLE_CLASS_MUTATOR"); + verifyResults(NON_VIABLE, NON_VIABLE); + + } + + public static class EatsMemoryWhenMutated { + public static int loop() throws InterruptedException { + int i = 1; + final List vals = new ArrayList<>(); + Thread.sleep(1500); + do { + i++; + vals.add(new String[9999999]); + vals.add(new String[9999999]); + vals.add(new String[9999999]); + vals.add(new String[9999999]); + } while (i < 1); + i++; + return i; + } + } + + public static class EatsMemoryTest { + @TestAnnotationForTesting() + public void pass() throws InterruptedException { + assertEquals(3, EatsMemoryWhenMutated.loop()); + } + } + + @Ignore("flakey") + @Test(timeout = 30000) + public void shouldRecoverFromOutOfMemoryError() { + run(EatsMemoryWhenMutated.class, EatsMemoryTest.class, + "INCREMENTS"); + verifyResults(KILLED, MEMORY_ERROR); + } + + @Test + public void shouldIsolateMutationsFromNestedClasses() { + // see http://code.google.com/p/pitestrunner/issues/detail?id=17 for full + // description of this issue + run(MutationsInNestedClasses.class, MutationsInNestedClassesTest.class, + "RETURN_VALS"); + verifyResults(SURVIVED, SURVIVED); + } + + @Test + @Ignore("too brittle") + public void shouldRecordCorrectLineNumberForMutations() { + run(OneMutationOnly.class, OneMutationFullTest.class, + "RETURN_VALS"); + verifyLineNumbers(111); + } + + private void run(final Class clazz, final Class test, + final String ... mutators) { + + final ReportOptions data = new ReportOptions(); + + final Set> tests = Collections.singleton(Prelude + .isEqualTo(test.getName())); + data.setTargetTests(tests); + data.setDependencyAnalysisMaxDistance(-1); + + final Set mutees = Collections.singleton(clazz.getName() + "*"); + data.setTargetClasses(mutees); + + data.setTimeoutConstant(PercentAndConstantTimeoutStrategy.DEFAULT_CONSTANT); + data.setTimeoutFactor(PercentAndConstantTimeoutStrategy.DEFAULT_FACTOR); + + final JavaAgent agent = new JarCreatingJarFinder(); + + try { + createEngineAndRun(data, agent, Arrays.asList(mutators)); + } finally { + agent.close(); + } + } + + private void createEngineAndRun(final ReportOptions data, + final JavaAgent agent, + final Collection mutators) { + + // data.setConfiguration(this.config); + final CoverageOptions coverageOptions = createCoverageOptions(data); + + final LaunchOptions launchOptions = new LaunchOptions(agent, + new DefaultJavaExecutableLocator(), data.getJvmArgs(), + new HashMap()); + + final PathFilter pf = new PathFilter( + Prelude.not(new DefaultDependencyPathPredicate()), + Prelude.not(new DefaultDependencyPathPredicate())); + final ProjectClassPaths cps = new ProjectClassPaths(data.getClassPath(), + data.createClassesFilter(), pf); + + final Timings timings = new Timings(); + final CodeSource code = new CodeSource(cps); + + final CoverageGenerator coverageGenerator = new DefaultCoverageGenerator( + null, coverageOptions, launchOptions, code, new NullCoverageExporter(), + timings, false); + + final CoverageDatabase coverageData = coverageGenerator.calculateCoverage(); + + final Collection codeClasses = FCollection.map(code.getCode(), + ClassInfo.toClassName()); + + final EngineArguments arguments = EngineArguments.arguments() + .withMutators(mutators); + + final MutationEngine engine = new GregorEngineFactory().createEngine(arguments); + + final MutationConfig mutationConfig = new MutationConfig(engine, + launchOptions); + + final ClassloaderByteArraySource bas = new ClassloaderByteArraySource( + IsolationUtils.getContextClassLoader()); + + final MutationInterceptor emptyIntercpetor = CompoundMutationInterceptor.nullInterceptor(); + + final MutationSource source = new MutationSource(mutationConfig, new DefaultTestPrioritiser( + coverageData), bas, emptyIntercpetor); + + + final WorkerFactory wf = new WorkerFactory(null, + coverageOptions.getPitConfig(), mutationConfig, arguments, + new PercentAndConstantTimeoutStrategy(data.getTimeoutFactor(), + data.getTimeoutConstant()), data.isVerbose(), data.getClassPath() + .getLocalClassPath()); + + + + + final MutationTestBuilder builder = new MutationTestBuilder(wf, + new NullAnalyser(), source, new DefaultGrouper(0)); + + final List tus = builder + .createMutationTestUnits(codeClasses); + + this.mae.run(tus); + } + + private CoverageOptions createCoverageOptions(ReportOptions data) { + return new CoverageOptions(data.getTargetClasses(),data.getExcludedClasses(), this.config, + data.isVerbose(), data.getDependencyAnalysisMaxDistance()); + } + + protected void verifyResults(final DetectionStatus... detectionStatus) { + final List expected = Arrays.asList(detectionStatus); + final List actual = this.metaDataExtractor + .getDetectionStatus(); + + Collections.sort(expected); + Collections.sort(actual); + + assertEquals(expected, actual); + } + + protected void verifyLineNumbers(final Integer... lineNumbers) { + final List expected = Arrays.asList(lineNumbers); + final List actual = this.metaDataExtractor.getLineNumbers(); + + Collections.sort(expected); + Collections.sort(actual); + + assertEquals(expected, actual); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/AnalyisPriorityComparatorTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/AnalyisPriorityComparatorTest.java index 069dd5121..2fb9afbe3 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/AnalyisPriorityComparatorTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/AnalyisPriorityComparatorTest.java @@ -1,57 +1,57 @@ -package org.pitest.mutationtest.build; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; -import org.pitest.mutationtest.MutationMetaData; - -public class AnalyisPriorityComparatorTest { - - private final AnalysisPriorityComparator testee = new AnalysisPriorityComparator(); - - @Test - public void shouldPrioritiseLargestFirst() { - final MutationAnalysisUnit a = unit(1); - final MutationAnalysisUnit b = unit(2); - final MutationAnalysisUnit c = unit(3); - final List actual = Arrays.asList(a, b, c); - Collections.sort(actual, this.testee); - assertEquals(Arrays.asList(c, b, a), actual); - } - - @Test - public void shouldPreserveCorrectOrder() { - final MutationAnalysisUnit a = unit(3); - final MutationAnalysisUnit b = unit(2); - final MutationAnalysisUnit c = unit(1); - final List actual = Arrays.asList(a, b, c); - Collections.sort(actual, this.testee); - assertEquals(Arrays.asList(a, b, c), actual); - } - - private MutationAnalysisUnit unit(final int count) { - return new MutationAnalysisUnit() { - - @Override - public int priority() { - return count; - } - - @Override - public String toString() { - return "" + count; - } - - @Override - public MutationMetaData call() throws Exception { - return null; - } - - }; - } - -} +package org.pitest.mutationtest.build; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; +import org.pitest.mutationtest.MutationMetaData; + +public class AnalyisPriorityComparatorTest { + + private final AnalysisPriorityComparator testee = new AnalysisPriorityComparator(); + + @Test + public void shouldPrioritiseLargestFirst() { + final MutationAnalysisUnit a = unit(1); + final MutationAnalysisUnit b = unit(2); + final MutationAnalysisUnit c = unit(3); + final List actual = Arrays.asList(a, b, c); + Collections.sort(actual, this.testee); + assertEquals(Arrays.asList(c, b, a), actual); + } + + @Test + public void shouldPreserveCorrectOrder() { + final MutationAnalysisUnit a = unit(3); + final MutationAnalysisUnit b = unit(2); + final MutationAnalysisUnit c = unit(1); + final List actual = Arrays.asList(a, b, c); + Collections.sort(actual, this.testee); + assertEquals(Arrays.asList(a, b, c), actual); + } + + private MutationAnalysisUnit unit(final int count) { + return new MutationAnalysisUnit() { + + @Override + public int priority() { + return count; + } + + @Override + public String toString() { + return "" + count; + } + + @Override + public MutationMetaData call() throws Exception { + return null; + } + + }; + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/CompoundMutationInterceptorTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/CompoundMutationInterceptorTest.java index 29b00db3e..3c041fdb8 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/CompoundMutationInterceptorTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/CompoundMutationInterceptorTest.java @@ -1,102 +1,102 @@ -package org.pitest.mutationtest.build; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; - -@RunWith(MockitoJUnitRunner.class) -public class CompoundMutationInterceptorTest { - - @Mock - MutationInterceptor modifyChild; - - @Mock - MutationInterceptor filterChild; - - @Mock - MutationInterceptor otherChild; - - @Mock - MutationInterceptor reportChild; - - @Mock - MutationInterceptor cosmeticChild; - - @Mock - Mutater mutater; - - CompoundMutationInterceptor testee; - - @Before - public void setUp() { - when(this.modifyChild.type()).thenReturn(InterceptorType.MODIFY); - when(this.filterChild.type()).thenReturn(InterceptorType.FILTER); - when(this.otherChild.type()).thenReturn(InterceptorType.OTHER); - when(this.cosmeticChild.type()).thenReturn(InterceptorType.MODIFY_COSMETIC); - when(this.reportChild.type()).thenReturn(InterceptorType.REPORT); - } - - @Test - public void shouldNotifyAllChildrenOfNewClass() { - this.testee = new CompoundMutationInterceptor(Arrays.asList(this.modifyChild,this.filterChild)); - final ClassTree aClass = new ClassTree(null); - - this.testee.begin(aClass); - verify(this.modifyChild).begin(aClass); - verify(this.filterChild).begin(aClass); - } - - @Test - public void shouldChainModifiedMutantListsThroughChildrenInCorrectOrder() { - - // add out of order - this.testee = new CompoundMutationInterceptor(Arrays.asList(this.cosmeticChild, this.otherChild, this.modifyChild, this.reportChild, this.filterChild)); - - final Collection original = aMutationDetail().build(1); - final Collection modifyResult = aMutationDetail().build(2); - final Collection filterResult = aMutationDetail().build(3); - final Collection reportResult = aMutationDetail().build(3); - final Collection cosmeticResult = aMutationDetail().build(3); - final Collection otherResult = aMutationDetail().build(3); - - when(this.modifyChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(modifyResult); - when(this.filterChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(filterResult); - when(this.reportChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(reportResult); - when(this.cosmeticChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(cosmeticResult); - when(this.otherChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(otherResult); - - final Collection actual = this.testee.intercept(original, this.mutater); - - assertThat(actual).isEqualTo(reportResult); - - verify(this.otherChild).intercept(original,this.mutater); - verify(this.modifyChild).intercept(otherResult,this.mutater); - verify(this.filterChild).intercept(modifyResult,this.mutater); - verify(this.cosmeticChild).intercept(cosmeticResult,this.mutater); - verify(this.reportChild).intercept(cosmeticResult,this.mutater); - } - - @Test - public void shouldNotifyAllChildrenOfEnd() { - this.testee = new CompoundMutationInterceptor(Arrays.asList(this.modifyChild,this.filterChild)); - this.testee.end(); - - verify(this.modifyChild).end(); - verify(this.filterChild).end(); - } - -} +package org.pitest.mutationtest.build; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; + +@RunWith(MockitoJUnitRunner.class) +public class CompoundMutationInterceptorTest { + + @Mock + MutationInterceptor modifyChild; + + @Mock + MutationInterceptor filterChild; + + @Mock + MutationInterceptor otherChild; + + @Mock + MutationInterceptor reportChild; + + @Mock + MutationInterceptor cosmeticChild; + + @Mock + Mutater mutater; + + CompoundMutationInterceptor testee; + + @Before + public void setUp() { + when(this.modifyChild.type()).thenReturn(InterceptorType.MODIFY); + when(this.filterChild.type()).thenReturn(InterceptorType.FILTER); + when(this.otherChild.type()).thenReturn(InterceptorType.OTHER); + when(this.cosmeticChild.type()).thenReturn(InterceptorType.MODIFY_COSMETIC); + when(this.reportChild.type()).thenReturn(InterceptorType.REPORT); + } + + @Test + public void shouldNotifyAllChildrenOfNewClass() { + this.testee = new CompoundMutationInterceptor(Arrays.asList(this.modifyChild,this.filterChild)); + final ClassTree aClass = new ClassTree(null); + + this.testee.begin(aClass); + verify(this.modifyChild).begin(aClass); + verify(this.filterChild).begin(aClass); + } + + @Test + public void shouldChainModifiedMutantListsThroughChildrenInCorrectOrder() { + + // add out of order + this.testee = new CompoundMutationInterceptor(Arrays.asList(this.cosmeticChild, this.otherChild, this.modifyChild, this.reportChild, this.filterChild)); + + final Collection original = aMutationDetail().build(1); + final Collection modifyResult = aMutationDetail().build(2); + final Collection filterResult = aMutationDetail().build(3); + final Collection reportResult = aMutationDetail().build(3); + final Collection cosmeticResult = aMutationDetail().build(3); + final Collection otherResult = aMutationDetail().build(3); + + when(this.modifyChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(modifyResult); + when(this.filterChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(filterResult); + when(this.reportChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(reportResult); + when(this.cosmeticChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(cosmeticResult); + when(this.otherChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(otherResult); + + final Collection actual = this.testee.intercept(original, this.mutater); + + assertThat(actual).isEqualTo(reportResult); + + verify(this.otherChild).intercept(original,this.mutater); + verify(this.modifyChild).intercept(otherResult,this.mutater); + verify(this.filterChild).intercept(modifyResult,this.mutater); + verify(this.cosmeticChild).intercept(cosmeticResult,this.mutater); + verify(this.reportChild).intercept(cosmeticResult,this.mutater); + } + + @Test + public void shouldNotifyAllChildrenOfEnd() { + this.testee = new CompoundMutationInterceptor(Arrays.asList(this.modifyChild,this.filterChild)); + this.testee.end(); + + verify(this.modifyChild).end(); + verify(this.filterChild).end(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/DefaultGrouperTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/DefaultGrouperTest.java index ea13a342d..9ddad87db 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/DefaultGrouperTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/DefaultGrouperTest.java @@ -1,60 +1,60 @@ -package org.pitest.mutationtest.build; - -import static org.junit.Assert.assertEquals; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.LocationMother; -import org.pitest.mutationtest.LocationMother.LocationBuilder; -import org.pitest.mutationtest.engine.MutationDetails; - -public class DefaultGrouperTest { - - private DefaultGrouper testee; - - @Test - public void shouldCreateSingleUnitPerClassWhenUnitSizeIsZero() { - makeTesteeWithUnitSizeOf(0); - assertCreatesOneUnitForTwoMutations(); - } - - @Test - public void shouldCreateSingleUnitPerClassWhenUnitSizeIsLessThanZero() { - makeTesteeWithUnitSizeOf(-1); - assertCreatesOneUnitForTwoMutations(); - } - - @Test - public void shouldCreateMultipleTestUnitsWhenUnitSizeIsLessThanNumberOfMutations() { - makeTesteeWithUnitSizeOf(1); - final List> actual = this.testee.groupMutations( - Arrays.asList(ClassName.fromString("foo")), Arrays.asList( - createDetails("foo"), createDetails("foo"), createDetails("foo"))); - - assertEquals(3, actual.size()); - } - - private void assertCreatesOneUnitForTwoMutations() { - final MutationDetails mutation1 = createDetails("foo"); - final MutationDetails mutation2 = createDetails("foo"); - final List> actual = this.testee.groupMutations(null, - Arrays.asList(mutation1, mutation2)); - assertEquals(1, actual.size()); - } - - private void makeTesteeWithUnitSizeOf(final int i) { - this.testee = new DefaultGrouper(i); - } - - public static MutationDetails createDetails(final String clazz) { - final LocationBuilder lb = LocationMother.aLocation().withClass( - ClassName.fromString(clazz)); - return new MutationDetails(aMutationId().withLocation(lb).build(), "", - "desc", 42, 0); - } - -} +package org.pitest.mutationtest.build; + +import static org.junit.Assert.assertEquals; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.LocationMother; +import org.pitest.mutationtest.LocationMother.LocationBuilder; +import org.pitest.mutationtest.engine.MutationDetails; + +public class DefaultGrouperTest { + + private DefaultGrouper testee; + + @Test + public void shouldCreateSingleUnitPerClassWhenUnitSizeIsZero() { + makeTesteeWithUnitSizeOf(0); + assertCreatesOneUnitForTwoMutations(); + } + + @Test + public void shouldCreateSingleUnitPerClassWhenUnitSizeIsLessThanZero() { + makeTesteeWithUnitSizeOf(-1); + assertCreatesOneUnitForTwoMutations(); + } + + @Test + public void shouldCreateMultipleTestUnitsWhenUnitSizeIsLessThanNumberOfMutations() { + makeTesteeWithUnitSizeOf(1); + final List> actual = this.testee.groupMutations( + Arrays.asList(ClassName.fromString("foo")), Arrays.asList( + createDetails("foo"), createDetails("foo"), createDetails("foo"))); + + assertEquals(3, actual.size()); + } + + private void assertCreatesOneUnitForTwoMutations() { + final MutationDetails mutation1 = createDetails("foo"); + final MutationDetails mutation2 = createDetails("foo"); + final List> actual = this.testee.groupMutations(null, + Arrays.asList(mutation1, mutation2)); + assertEquals(1, actual.size()); + } + + private void makeTesteeWithUnitSizeOf(final int i) { + this.testee = new DefaultGrouper(i); + } + + public static MutationDetails createDetails(final String clazz) { + final LocationBuilder lb = LocationMother.aLocation().withClass( + ClassName.fromString(clazz)); + return new MutationDetails(aMutationId().withLocation(lb).build(), "", + "desc", 42, 0); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/DefaultTestPrioritiserTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/DefaultTestPrioritiserTest.java index 715d5e4e1..c4f56c076 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/DefaultTestPrioritiserTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/DefaultTestPrioritiserTest.java @@ -1,95 +1,95 @@ -package org.pitest.mutationtest.build; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; -import static org.pitest.mutationtest.LocationMother.aLocation; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.function.Function; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.ClassLine; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.coverage.TestInfo; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.mutationtest.engine.PoisonStatus; - -public class DefaultTestPrioritiserTest { - - private DefaultTestPrioritiser testee; - - @Mock - private CoverageDatabase coverage; - - @Mock - private ClassByteArraySource source; - - private final ClassName foo = ClassName.fromString("foo"); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new DefaultTestPrioritiser(this.coverage); - } - - @Test - public void shouldAssignTestsForRelevantLineToGeneratedMutations() { - final List expected = makeTestInfos(0); - when(this.coverage.getTestsForClassLine(any(ClassLine.class))).thenReturn( - expected); - final List actual = this.testee.assignTests(makeMutation("foo")); - assertEquals(expected, actual); - } - - @Test - public void shouldAssignAllTestsForClassWhenMutationInStaticInitialiser() { - final List expected = makeTestInfos(0); - when(this.coverage.getTestsForClass(this.foo)).thenReturn(expected); - final List actual = this.testee - .assignTests(makeMutation("") - .withPoisonStatus(PoisonStatus.IS_STATIC_INITIALIZER_CODE)); - assertEquals(expected, actual); - } - - @Test - public void shouldPrioritiseTestsByExecutionTime() { - final List unorderedTests = makeTestInfos(10000, 100, 1000, 1); - when(this.coverage.getTestsForClassLine(any(ClassLine.class))).thenReturn( - unorderedTests); - final List actual = this.testee.assignTests(makeMutation("foo")); - - assertEquals(Arrays.asList(1, 100, 1000, 10000), - FCollection.map(actual, toTime())); - } - - private Function toTime() { - return a -> a.getTime(); - } - - private List makeTestInfos(final Integer... times) { - return new ArrayList<>(FCollection.map(Arrays.asList(times), - timeToTestInfo())); - } - - private Function timeToTestInfo() { - return a -> new TestInfo("foo", "bar", a, Optional. empty(), 0); - } - - private MutationDetails makeMutation(final String method) { - final MutationIdentifier id = new MutationIdentifier(aLocation() - .withClass(this.foo).withMethod(method).build(), 0, "mutator"); - return new MutationDetails(id, "file", "desc", 1, 2); - } - -} +package org.pitest.mutationtest.build; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +import static org.pitest.mutationtest.LocationMother.aLocation; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.ClassLine; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.coverage.TestInfo; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.mutationtest.engine.PoisonStatus; + +public class DefaultTestPrioritiserTest { + + private DefaultTestPrioritiser testee; + + @Mock + private CoverageDatabase coverage; + + @Mock + private ClassByteArraySource source; + + private final ClassName foo = ClassName.fromString("foo"); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new DefaultTestPrioritiser(this.coverage); + } + + @Test + public void shouldAssignTestsForRelevantLineToGeneratedMutations() { + final List expected = makeTestInfos(0); + when(this.coverage.getTestsForClassLine(any(ClassLine.class))).thenReturn( + expected); + final List actual = this.testee.assignTests(makeMutation("foo")); + assertEquals(expected, actual); + } + + @Test + public void shouldAssignAllTestsForClassWhenMutationInStaticInitialiser() { + final List expected = makeTestInfos(0); + when(this.coverage.getTestsForClass(this.foo)).thenReturn(expected); + final List actual = this.testee + .assignTests(makeMutation("") + .withPoisonStatus(PoisonStatus.IS_STATIC_INITIALIZER_CODE)); + assertEquals(expected, actual); + } + + @Test + public void shouldPrioritiseTestsByExecutionTime() { + final List unorderedTests = makeTestInfos(10000, 100, 1000, 1); + when(this.coverage.getTestsForClassLine(any(ClassLine.class))).thenReturn( + unorderedTests); + final List actual = this.testee.assignTests(makeMutation("foo")); + + assertEquals(Arrays.asList(1, 100, 1000, 10000), + FCollection.map(actual, toTime())); + } + + private Function toTime() { + return a -> a.getTime(); + } + + private List makeTestInfos(final Integer... times) { + return new ArrayList<>(FCollection.map(Arrays.asList(times), + timeToTestInfo())); + } + + private Function timeToTestInfo() { + return a -> new TestInfo("foo", "bar", a, Optional. empty(), 0); + } + + private MutationDetails makeMutation(final String method) { + final MutationIdentifier id = new MutationIdentifier(aLocation() + .withClass(this.foo).withMethod(method).build(), 0, "mutator"); + return new MutationDetails(id, "file", "desc", 1, 2); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/InterceptorParametersTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/InterceptorParametersTest.java index bcc2d0df9..7e683b7b4 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/InterceptorParametersTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/InterceptorParametersTest.java @@ -1,56 +1,56 @@ -package org.pitest.mutationtest.build; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import java.util.Optional; -import org.pitest.plugin.FeatureParameter; -import org.pitest.plugin.FeatureSetting; - -public class InterceptorParametersTest { - - InterceptorParameters testee; - - @Test - public void shouldReturnStringParamsWhenPresent() { - this.testee = makeFor("foo", "bar"); - assertThat(this.testee.getString(FeatureParameter.named("foo"))).isEqualTo(Optional.ofNullable("bar")); - } - - @Test - public void shouldReturnNoneWhenValueAbsent() { - this.testee = makeFor("nomatch", "bar"); - assertThat(this.testee.getString(FeatureParameter.named("foo"))).isEqualTo(Optional.empty()); - } - - @Test - public void shouldReturnNoneWhenFeatureSettingsAbsent() { - this.testee = new InterceptorParameters(null, null, null); - assertThat(this.testee.getString(FeatureParameter.named("foo"))).isEqualTo(Optional.empty()); - } - - @Test - public void shouldReturnIntegerWhenPresent() { - this.testee = makeFor("foo", "11"); - assertThat(this.testee.getInteger(FeatureParameter.named("foo"))).isEqualTo(Optional.ofNullable(11)); - } - - @Test - public void shouldReturnListsOfStringsWhenPresent() { - this.testee = makeFor("foo", "bar", "car"); - assertThat(this.testee.getList(FeatureParameter.named("foo"))).contains("bar", "car"); - } - - private InterceptorParameters makeFor(String key, String ... vals) { - final Map> values = new HashMap<>(); - values.put(key, Arrays.asList(vals)); - final FeatureSetting fs = new FeatureSetting(null, null,values); - return new InterceptorParameters(fs, null, null); - } - -} +package org.pitest.mutationtest.build; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import java.util.Optional; +import org.pitest.plugin.FeatureParameter; +import org.pitest.plugin.FeatureSetting; + +public class InterceptorParametersTest { + + InterceptorParameters testee; + + @Test + public void shouldReturnStringParamsWhenPresent() { + this.testee = makeFor("foo", "bar"); + assertThat(this.testee.getString(FeatureParameter.named("foo"))).isEqualTo(Optional.ofNullable("bar")); + } + + @Test + public void shouldReturnNoneWhenValueAbsent() { + this.testee = makeFor("nomatch", "bar"); + assertThat(this.testee.getString(FeatureParameter.named("foo"))).isEqualTo(Optional.empty()); + } + + @Test + public void shouldReturnNoneWhenFeatureSettingsAbsent() { + this.testee = new InterceptorParameters(null, null, null); + assertThat(this.testee.getString(FeatureParameter.named("foo"))).isEqualTo(Optional.empty()); + } + + @Test + public void shouldReturnIntegerWhenPresent() { + this.testee = makeFor("foo", "11"); + assertThat(this.testee.getInteger(FeatureParameter.named("foo"))).isEqualTo(Optional.ofNullable(11)); + } + + @Test + public void shouldReturnListsOfStringsWhenPresent() { + this.testee = makeFor("foo", "bar", "car"); + assertThat(this.testee.getList(FeatureParameter.named("foo"))).contains("bar", "car"); + } + + private InterceptorParameters makeFor(String key, String ... vals) { + final Map> values = new HashMap<>(); + values.put(key, Arrays.asList(vals)); + final FeatureSetting fs = new FeatureSetting(null, null,values); + return new InterceptorParameters(fs, null, null); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/KnownStatusMutationTestUnitTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/KnownStatusMutationTestUnitTest.java index 5be3aa8ea..a4e36c3e7 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/KnownStatusMutationTestUnitTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/KnownStatusMutationTestUnitTest.java @@ -1,49 +1,49 @@ -package org.pitest.mutationtest.build; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.MockitoAnnotations; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationMetaData; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.report.MutationTestResultMother; - -public class KnownStatusMutationTestUnitTest { - - private KnownStatusMutationTestUnit testee; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - } - - @Test - public void shouldCreateMutationMetaDataForSuppliedResults() throws Exception { - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails(), new MutationStatusTestPair(1, - DetectionStatus.KILLED, "foo")); - final List mutations = Arrays.asList(mr); - this.testee = new KnownStatusMutationTestUnit(mutations); - final MutationMetaData actual = this.testee.call(); - - final MutationMetaData expected = new MutationMetaData(mutations); - assertThat(actual).isEqualTo(expected); - } - - @Test - public void shouldHaveHighPriorityToAnalyse() { - this.testee = new KnownStatusMutationTestUnit( - Collections. emptyList()); - assertEquals(Integer.MAX_VALUE, this.testee.priority()); - } - -} +package org.pitest.mutationtest.build; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockitoAnnotations; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationMetaData; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.report.MutationTestResultMother; + +public class KnownStatusMutationTestUnitTest { + + private KnownStatusMutationTestUnit testee; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + } + + @Test + public void shouldCreateMutationMetaDataForSuppliedResults() throws Exception { + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails(), new MutationStatusTestPair(1, + DetectionStatus.KILLED, "foo")); + final List mutations = Arrays.asList(mr); + this.testee = new KnownStatusMutationTestUnit(mutations); + final MutationMetaData actual = this.testee.call(); + + final MutationMetaData expected = new MutationMetaData(mutations); + assertThat(actual).isEqualTo(expected); + } + + @Test + public void shouldHaveHighPriorityToAnalyse() { + this.testee = new KnownStatusMutationTestUnit( + Collections. emptyList()); + assertEquals(Integer.MAX_VALUE, this.testee.priority()); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationDiscoveryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationDiscoveryTest.java index 098350cb1..612984489 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationDiscoveryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationDiscoveryTest.java @@ -1,268 +1,268 @@ -package org.pitest.mutationtest.build; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; - -import java.util.Collection; -import java.util.Collections; -import java.util.logging.Logger; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.mutationtest.EngineArguments; -import org.pitest.mutationtest.MutationConfig; -import org.pitest.mutationtest.build.intercept.javafeatures.ForEachFilterTest.HasForEachLoop; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.config.SettingsFactory; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.mutationtest.engine.gregor.CoverageIgnore; -import org.pitest.mutationtest.engine.gregor.DoNotMutate; -import org.pitest.mutationtest.engine.gregor.Generated; -import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; -import org.pitest.util.ResourceFolderByteArraySource; - -/** - * Tests discovery of mutants - including the full default interceptor chain - */ -public class MutationDiscoveryTest { - - ReportOptions data = new ReportOptions(); - ClassByteArraySource cbas = new ResourceFolderByteArraySource(); - - - @Before - public void setUp() { - this.data.setTargetClasses(Collections.singleton("com.example.*")); - } - - @Test - public void shouldFilterMutantsInTryCatchFinallyCompiledWithJavaC() { - this.data.setDetectInlinedCode(true); - - final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_javac"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(3); - } - - @Test - public void shouldFilterMutantsInTryCatchFinallyCompiledWithEcj() { - this.data.setDetectInlinedCode(true); - - final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_ecj"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(3); - } - - @Test - public void shouldFilterMutantsInTryCatchFinallyCompiledWithAspectJ() { - this.data.setDetectInlinedCode(true); - - final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_aspectj"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(3); - } - - @Test - public void shouldFilterMutantsInTryFinallyCompiledWithJavaC() { - this.data.setDetectInlinedCode(true); - - final ClassName clazz = ClassName.fromString("trywithresources/TryFinallyExample_javac"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(2); - } - - @Test - public void shouldFilterMutantsInTryFinallyCompiledWithEcj() { - this.data.setDetectInlinedCode(true); - - final ClassName clazz = ClassName.fromString("trywithresources/TryFinallyExample_ecj"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(2); - } - - @Test - public void shouldFilterMutantsInTryFinallyCompiledWithAspectJ() { - this.data.setDetectInlinedCode(true); - - final ClassName clazz = ClassName.fromString("trywithresources/TryFinallyExample_aspectj"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(2); - } - - @Test - public void shouldNotFilterInlinedFinallyBlocksWhenFlagNotSet() { - final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_javac"); - - this.data.setDetectInlinedCode(true); - final Collection filtered = findMutants(clazz); - - this.data.setDetectInlinedCode(false); - final Collection unfiltered = findMutants(clazz); - - assertThat(filtered.size()).isLessThan(unfiltered.size()); - } - - @Test - public void shouldFilterMutantsInTryWithResourcesClosableCompiledWithJavac() { - final ClassName clazz = ClassName.fromString("trywithresources/TryWithTwoCloseableExample_javac"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(1); - } - - @Test - public void shouldFilterMutantsInTryWithResourcesClosableCompiledWithEcj() { - final ClassName clazz = ClassName.fromString("trywithresources/TryWithTwoCloseableExample_ecj"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(1); - } - - @Test - public void shouldFilterMutantsInTryWithResourcesClosableCompiledWithApectj() { - final ClassName clazz = ClassName.fromString("trywithresources/TryWithTwoCloseableExample_aspectj"); - final Collection actual = findMutants(clazz); - assertThat(actual).hasSize(1); - } - - @Test - public void shouldFilterMutationsInLoggingCalls() { - this.data.setLoggingClasses(Collections.singleton("java.util.logging")); - final Collection actual = findMutants(HasLogger.class); - assertThat(actual).isEmpty(); - } - - - @Test - public void shouldNotMutateMethodsAnnotatedWithGenerated() { - final Collection actualDetails = findMutants(AnnotatedToAvoidMethod.class); - // all but two methods are annotated to ignore - assertEquals(2, actualDetails.size()); - } - - @Test - public void shouldFilterImplicitNullChecksInLambdas() { - final ClassName clazz = ClassName.fromString("implicitnullcheck/RemovedCallBug_javac"); - - this.data.setMutators(Collections.singletonList("ALL")); - - final Collection foundByDefault = findMutants(clazz); - - this.data.setFeatures(Collections.singletonList("-FINULL")); - - final Collection foundWhenDisabled = findMutants(clazz); - - assertThat(foundWhenDisabled.size()).isGreaterThan(foundByDefault.size()); - } - - @Test - public void shouldFilterMutationsToForLoopIncrements() { - final Collection actual = findMutants(HasForLoop.class); - - this.data.setFeatures(Collections.singletonList("-FFLOOP")); - final Collection actualWithoutFilter = findMutants(HasForLoop.class); - - assertThat(actual.size()).isLessThan(actualWithoutFilter.size()); - } - - @Test - public void shouldFilterMutationsToForEachLoops() { - final Collection actual = findMutants(HasForEachLoop.class); - - this.data.setFeatures(Collections.singletonList("-FFEACH")); - final Collection actualWithoutFilter = findMutants(HasForEachLoop.class); - - assertThat(actual.size()).isLessThan(actualWithoutFilter.size()); - } - - - @Test - public void filtersEquivalentReturnValsMutants() { - this.data.setMutators(Collections.singletonList("PRIMITIVE_RETURNS")); - final Collection actual = findMutants(AlreadyReturnsConstZero.class); - assertThat(actual).isEmpty(); - } - - public static class AnnotatedToAvoidMethod { - public int a() { - return 1; - } - - @Generated - public int b() { - return 1; - } - - @DoNotMutate - public int c() { - return 1; - } - - @CoverageIgnore - public int d() { - return 1; - } - - public int e() { - return 1; - } - } - - private static class HasLogger { - private static Logger log = Logger.getLogger(HasLogger.class.getName()); - - @SuppressWarnings("unused") - public void call(int i) { - log.info("foo " + i); - } - } - - - private Collection findMutants(Class clazz) { - this.data.setTargetClasses(Collections.singleton(clazz.getName())); - this.cbas = ClassloaderByteArraySource.fromContext(); - return findMutants(ClassName.fromClass(clazz)); - } - - private Collection findMutants(ClassName clazz) { - final MutationSource source = createSource(this.cbas); - return source.createMutations(clazz); - } - - MutationSource createSource(ClassByteArraySource source) { - final SettingsFactory settings = new SettingsFactory(this.data, - PluginServices.makeForContextLoader()); - final MutationInterceptor interceptor = settings.getInterceptor() - .createInterceptor(this.data, source); - - final MutationEngine engine = new GregorEngineFactory().createEngine( - EngineArguments.arguments().withExcludedMethods(this.data.getExcludedMethods()) - .withMutators(this.data.getMutators())); - - final MutationConfig config = new MutationConfig(engine, null); - - return new MutationSource(config, noTestPrioritisation(), source, - interceptor); - } - - private TestPrioritiser noTestPrioritisation() { - return mutation -> Collections.emptyList(); - } - - static class HasForLoop { - public void foo() { - for (int i = 0; i != 10; i++) { - System.out.println(i); - } - } - } - - class AlreadyReturnsConstZero { - public int a() { - return 0; - } - } -} +package org.pitest.mutationtest.build; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +import java.util.Collection; +import java.util.Collections; +import java.util.logging.Logger; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.mutationtest.EngineArguments; +import org.pitest.mutationtest.MutationConfig; +import org.pitest.mutationtest.build.intercept.javafeatures.ForEachFilterTest.HasForEachLoop; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.config.SettingsFactory; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.mutationtest.engine.gregor.CoverageIgnore; +import org.pitest.mutationtest.engine.gregor.DoNotMutate; +import org.pitest.mutationtest.engine.gregor.Generated; +import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; +import org.pitest.util.ResourceFolderByteArraySource; + +/** + * Tests discovery of mutants - including the full default interceptor chain + */ +public class MutationDiscoveryTest { + + ReportOptions data = new ReportOptions(); + ClassByteArraySource cbas = new ResourceFolderByteArraySource(); + + + @Before + public void setUp() { + this.data.setTargetClasses(Collections.singleton("com.example.*")); + } + + @Test + public void shouldFilterMutantsInTryCatchFinallyCompiledWithJavaC() { + this.data.setDetectInlinedCode(true); + + final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_javac"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(3); + } + + @Test + public void shouldFilterMutantsInTryCatchFinallyCompiledWithEcj() { + this.data.setDetectInlinedCode(true); + + final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_ecj"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(3); + } + + @Test + public void shouldFilterMutantsInTryCatchFinallyCompiledWithAspectJ() { + this.data.setDetectInlinedCode(true); + + final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_aspectj"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(3); + } + + @Test + public void shouldFilterMutantsInTryFinallyCompiledWithJavaC() { + this.data.setDetectInlinedCode(true); + + final ClassName clazz = ClassName.fromString("trywithresources/TryFinallyExample_javac"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(2); + } + + @Test + public void shouldFilterMutantsInTryFinallyCompiledWithEcj() { + this.data.setDetectInlinedCode(true); + + final ClassName clazz = ClassName.fromString("trywithresources/TryFinallyExample_ecj"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(2); + } + + @Test + public void shouldFilterMutantsInTryFinallyCompiledWithAspectJ() { + this.data.setDetectInlinedCode(true); + + final ClassName clazz = ClassName.fromString("trywithresources/TryFinallyExample_aspectj"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(2); + } + + @Test + public void shouldNotFilterInlinedFinallyBlocksWhenFlagNotSet() { + final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_javac"); + + this.data.setDetectInlinedCode(true); + final Collection filtered = findMutants(clazz); + + this.data.setDetectInlinedCode(false); + final Collection unfiltered = findMutants(clazz); + + assertThat(filtered.size()).isLessThan(unfiltered.size()); + } + + @Test + public void shouldFilterMutantsInTryWithResourcesClosableCompiledWithJavac() { + final ClassName clazz = ClassName.fromString("trywithresources/TryWithTwoCloseableExample_javac"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(1); + } + + @Test + public void shouldFilterMutantsInTryWithResourcesClosableCompiledWithEcj() { + final ClassName clazz = ClassName.fromString("trywithresources/TryWithTwoCloseableExample_ecj"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(1); + } + + @Test + public void shouldFilterMutantsInTryWithResourcesClosableCompiledWithApectj() { + final ClassName clazz = ClassName.fromString("trywithresources/TryWithTwoCloseableExample_aspectj"); + final Collection actual = findMutants(clazz); + assertThat(actual).hasSize(1); + } + + @Test + public void shouldFilterMutationsInLoggingCalls() { + this.data.setLoggingClasses(Collections.singleton("java.util.logging")); + final Collection actual = findMutants(HasLogger.class); + assertThat(actual).isEmpty(); + } + + + @Test + public void shouldNotMutateMethodsAnnotatedWithGenerated() { + final Collection actualDetails = findMutants(AnnotatedToAvoidMethod.class); + // all but two methods are annotated to ignore + assertEquals(2, actualDetails.size()); + } + + @Test + public void shouldFilterImplicitNullChecksInLambdas() { + final ClassName clazz = ClassName.fromString("implicitnullcheck/RemovedCallBug_javac"); + + this.data.setMutators(Collections.singletonList("ALL")); + + final Collection foundByDefault = findMutants(clazz); + + this.data.setFeatures(Collections.singletonList("-FINULL")); + + final Collection foundWhenDisabled = findMutants(clazz); + + assertThat(foundWhenDisabled.size()).isGreaterThan(foundByDefault.size()); + } + + @Test + public void shouldFilterMutationsToForLoopIncrements() { + final Collection actual = findMutants(HasForLoop.class); + + this.data.setFeatures(Collections.singletonList("-FFLOOP")); + final Collection actualWithoutFilter = findMutants(HasForLoop.class); + + assertThat(actual.size()).isLessThan(actualWithoutFilter.size()); + } + + @Test + public void shouldFilterMutationsToForEachLoops() { + final Collection actual = findMutants(HasForEachLoop.class); + + this.data.setFeatures(Collections.singletonList("-FFEACH")); + final Collection actualWithoutFilter = findMutants(HasForEachLoop.class); + + assertThat(actual.size()).isLessThan(actualWithoutFilter.size()); + } + + + @Test + public void filtersEquivalentReturnValsMutants() { + this.data.setMutators(Collections.singletonList("PRIMITIVE_RETURNS")); + final Collection actual = findMutants(AlreadyReturnsConstZero.class); + assertThat(actual).isEmpty(); + } + + public static class AnnotatedToAvoidMethod { + public int a() { + return 1; + } + + @Generated + public int b() { + return 1; + } + + @DoNotMutate + public int c() { + return 1; + } + + @CoverageIgnore + public int d() { + return 1; + } + + public int e() { + return 1; + } + } + + private static class HasLogger { + private static Logger log = Logger.getLogger(HasLogger.class.getName()); + + @SuppressWarnings("unused") + public void call(int i) { + log.info("foo " + i); + } + } + + + private Collection findMutants(Class clazz) { + this.data.setTargetClasses(Collections.singleton(clazz.getName())); + this.cbas = ClassloaderByteArraySource.fromContext(); + return findMutants(ClassName.fromClass(clazz)); + } + + private Collection findMutants(ClassName clazz) { + final MutationSource source = createSource(this.cbas); + return source.createMutations(clazz); + } + + MutationSource createSource(ClassByteArraySource source) { + final SettingsFactory settings = new SettingsFactory(this.data, + PluginServices.makeForContextLoader()); + final MutationInterceptor interceptor = settings.getInterceptor() + .createInterceptor(this.data, source); + + final MutationEngine engine = new GregorEngineFactory().createEngine( + EngineArguments.arguments().withExcludedMethods(this.data.getExcludedMethods()) + .withMutators(this.data.getMutators())); + + final MutationConfig config = new MutationConfig(engine, null); + + return new MutationSource(config, noTestPrioritisation(), source, + interceptor); + } + + private TestPrioritiser noTestPrioritisation() { + return mutation -> Collections.emptyList(); + } + + static class HasForLoop { + public void foo() { + for (int i = 0; i != 10; i++) { + System.out.println(i); + } + } + } + + class AlreadyReturnsConstZero { + public int a() { + return 0; + } + } +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationSourceTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationSourceTest.java index 0f98d3d20..5b84173e1 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationSourceTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationSourceTest.java @@ -1,103 +1,103 @@ -package org.pitest.mutationtest.build; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; -import static org.pitest.mutationtest.LocationMother.aLocation; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.coverage.TestInfo; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.MutationConfig; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.process.LaunchOptions; - -@RunWith(MockitoJUnitRunner.class) -public class MutationSourceTest { - - private MutationSource testee; - - private MutationConfig config; - - private final ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); - - @Mock - private Mutater mutater; - - @Mock - private MutationEngine engine; - - @Mock - private TestPrioritiser prioritiser; - - private final ClassName foo = ClassName.fromClass(Foo.class); - - @Before - public void setUp() { - when(this.engine.createMutator(any(ClassByteArraySource.class))).thenReturn(this.mutater); - this.config = new MutationConfig(this.engine, new LaunchOptions(null)); - this.testee = new MutationSource(this.config, this.prioritiser - , this.source, CompoundMutationInterceptor.nullInterceptor()); - } - - @Test - public void shouldReturnNoMuationsWhenNoneFound() { - assertEquals(Collections.emptyList(), this.testee.createMutations(this.foo)); - } - - @Test - public void shouldAssignTestsFromPrioritiserToMutant() { - final List expected = makeTestInfos(0); - final List mutations = makeMutations("foo"); - - when(this.prioritiser.assignTests(any(MutationDetails.class))).thenReturn( - expected); - when(this.mutater.findMutations(any(ClassName.class))) - .thenReturn(mutations); - final MutationDetails actual = this.testee.createMutations(this.foo) - .iterator().next(); - assertEquals(expected, actual.getTestsInOrder()); - } - - private List makeTestInfos(final Integer... times) { - return new ArrayList<>(FCollection.map(Arrays.asList(times), - timeToTestInfo())); - } - - private Function timeToTestInfo() { - return a -> new TestInfo("foo", "bar", a, Optional. empty(), 0); - } - - private List makeMutations(final String method) { - final List mutations = Arrays.asList(makeMutation(method)); - return mutations; - } - - private MutationDetails makeMutation(final String method) { - final MutationIdentifier id = new MutationIdentifier(aLocation() - .withClass(this.foo).withMethod(method).build(), 0, "mutator"); - return new MutationDetails(id, "file", "desc", 1, 2); - } - -} - -class Foo { - -} +package org.pitest.mutationtest.build; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +import static org.pitest.mutationtest.LocationMother.aLocation; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.coverage.TestInfo; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.MutationConfig; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.process.LaunchOptions; + +@RunWith(MockitoJUnitRunner.class) +public class MutationSourceTest { + + private MutationSource testee; + + private MutationConfig config; + + private final ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); + + @Mock + private Mutater mutater; + + @Mock + private MutationEngine engine; + + @Mock + private TestPrioritiser prioritiser; + + private final ClassName foo = ClassName.fromClass(Foo.class); + + @Before + public void setUp() { + when(this.engine.createMutator(any(ClassByteArraySource.class))).thenReturn(this.mutater); + this.config = new MutationConfig(this.engine, new LaunchOptions(null)); + this.testee = new MutationSource(this.config, this.prioritiser + , this.source, CompoundMutationInterceptor.nullInterceptor()); + } + + @Test + public void shouldReturnNoMuationsWhenNoneFound() { + assertEquals(Collections.emptyList(), this.testee.createMutations(this.foo)); + } + + @Test + public void shouldAssignTestsFromPrioritiserToMutant() { + final List expected = makeTestInfos(0); + final List mutations = makeMutations("foo"); + + when(this.prioritiser.assignTests(any(MutationDetails.class))).thenReturn( + expected); + when(this.mutater.findMutations(any(ClassName.class))) + .thenReturn(mutations); + final MutationDetails actual = this.testee.createMutations(this.foo) + .iterator().next(); + assertEquals(expected, actual.getTestsInOrder()); + } + + private List makeTestInfos(final Integer... times) { + return new ArrayList<>(FCollection.map(Arrays.asList(times), + timeToTestInfo())); + } + + private Function timeToTestInfo() { + return a -> new TestInfo("foo", "bar", a, Optional. empty(), 0); + } + + private List makeMutations(final String method) { + final List mutations = Arrays.asList(makeMutation(method)); + return mutations; + } + + private MutationDetails makeMutation(final String method) { + final MutationIdentifier id = new MutationIdentifier(aLocation() + .withClass(this.foo).withMethod(method).build(), 0, "mutator"); + return new MutationDetails(id, "file", "desc", 1, 2); + } + +} + +class Foo { + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationTestBuilderTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationTestBuilderTest.java index fb5f2af03..c4f10ce9e 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationTestBuilderTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationTestBuilderTest.java @@ -1,103 +1,103 @@ -package org.pitest.mutationtest.build; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; -import static org.pitest.mutationtest.LocationMother.aLocation; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.NullAnalyser; -import org.pitest.mutationtest.engine.MutationDetails; - -public class MutationTestBuilderTest { - - private MutationTestBuilder testee; - - @Mock - private MutationSource source; - - @Mock - private WorkerFactory wf; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - makeTesteeWithUnitSizeOf(0); - } - - @Test - public void shouldCreateSingleUnitPerClassWhenUnitSizeIsZero() { - makeTesteeWithUnitSizeOf(0); - assertCreatesOneTestUnitForTwoMutations(); - } - - @Test - public void shouldCreateSingleUnitPerClassWhenUnitSizeIsLessThanZero() { - makeTesteeWithUnitSizeOf(-1); - assertCreatesOneTestUnitForTwoMutations(); - } - - @Test - public void shouldCreateMultipleTestUnitsWhenUnitSizeIsLessThanNumberOfMutations() { - makeTesteeWithUnitSizeOf(1); - when(this.source.createMutations(any(ClassName.class))).thenReturn( - Arrays.asList(createDetails("foo"), createDetails("foo"), - createDetails("foo"))); - final List actual = this.testee - .createMutationTestUnits(Arrays.asList(ClassName.fromString("foo"))); - assertEquals(3, actual.size()); - } - - @Test - public void shouldCreateNoUnitsWhenNoMutationsFound() { - when(this.source.createMutations(any(ClassName.class))).thenReturn( - Collections. emptyList()); - assertTrue(this.testee.createMutationTestUnits( - Arrays.asList(ClassName.fromString("foo"))).isEmpty()); - } - - @Test - public void shouldOrderLargestUnitFirst() { - final MutationDetails mutation1 = createDetails("foo"); - final MutationDetails mutation2 = createDetails("bar"); - final ClassName foo = ClassName.fromString("foo"); - final ClassName bar = ClassName.fromString("bar"); - when(this.source.createMutations(foo)).thenReturn(Arrays.asList(mutation1)); - when(this.source.createMutations(bar)).thenReturn( - Arrays.asList(mutation2, mutation2)); - final List actual = this.testee - .createMutationTestUnits(Arrays.asList(foo, bar)); - assertTrue(actual.get(0).priority() > actual.get(1).priority()); - } - - private void assertCreatesOneTestUnitForTwoMutations() { - final MutationDetails mutation1 = createDetails("foo"); - final MutationDetails mutation2 = createDetails("foo"); - when(this.source.createMutations(any(ClassName.class))).thenReturn( - Arrays.asList(mutation1, mutation2)); - final List actual = this.testee - .createMutationTestUnits(Arrays.asList(ClassName.fromString("foo"))); - assertEquals(1, actual.size()); - } - - private void makeTesteeWithUnitSizeOf(int unitSize) { - this.testee = new MutationTestBuilder(this.wf, new NullAnalyser(), - this.source, new DefaultGrouper(unitSize)); - } - - public static MutationDetails createDetails(String clazz) { - return new MutationDetails(aMutationId().withLocation(aLocation(clazz)) - .build(), "", "desc", 42, 0); - } - -} +package org.pitest.mutationtest.build; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +import static org.pitest.mutationtest.LocationMother.aLocation; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.NullAnalyser; +import org.pitest.mutationtest.engine.MutationDetails; + +public class MutationTestBuilderTest { + + private MutationTestBuilder testee; + + @Mock + private MutationSource source; + + @Mock + private WorkerFactory wf; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + makeTesteeWithUnitSizeOf(0); + } + + @Test + public void shouldCreateSingleUnitPerClassWhenUnitSizeIsZero() { + makeTesteeWithUnitSizeOf(0); + assertCreatesOneTestUnitForTwoMutations(); + } + + @Test + public void shouldCreateSingleUnitPerClassWhenUnitSizeIsLessThanZero() { + makeTesteeWithUnitSizeOf(-1); + assertCreatesOneTestUnitForTwoMutations(); + } + + @Test + public void shouldCreateMultipleTestUnitsWhenUnitSizeIsLessThanNumberOfMutations() { + makeTesteeWithUnitSizeOf(1); + when(this.source.createMutations(any(ClassName.class))).thenReturn( + Arrays.asList(createDetails("foo"), createDetails("foo"), + createDetails("foo"))); + final List actual = this.testee + .createMutationTestUnits(Arrays.asList(ClassName.fromString("foo"))); + assertEquals(3, actual.size()); + } + + @Test + public void shouldCreateNoUnitsWhenNoMutationsFound() { + when(this.source.createMutations(any(ClassName.class))).thenReturn( + Collections. emptyList()); + assertTrue(this.testee.createMutationTestUnits( + Arrays.asList(ClassName.fromString("foo"))).isEmpty()); + } + + @Test + public void shouldOrderLargestUnitFirst() { + final MutationDetails mutation1 = createDetails("foo"); + final MutationDetails mutation2 = createDetails("bar"); + final ClassName foo = ClassName.fromString("foo"); + final ClassName bar = ClassName.fromString("bar"); + when(this.source.createMutations(foo)).thenReturn(Arrays.asList(mutation1)); + when(this.source.createMutations(bar)).thenReturn( + Arrays.asList(mutation2, mutation2)); + final List actual = this.testee + .createMutationTestUnits(Arrays.asList(foo, bar)); + assertTrue(actual.get(0).priority() > actual.get(1).priority()); + } + + private void assertCreatesOneTestUnitForTwoMutations() { + final MutationDetails mutation1 = createDetails("foo"); + final MutationDetails mutation2 = createDetails("foo"); + when(this.source.createMutations(any(ClassName.class))).thenReturn( + Arrays.asList(mutation1, mutation2)); + final List actual = this.testee + .createMutationTestUnits(Arrays.asList(ClassName.fromString("foo"))); + assertEquals(1, actual.size()); + } + + private void makeTesteeWithUnitSizeOf(int unitSize) { + this.testee = new MutationTestBuilder(this.wf, new NullAnalyser(), + this.source, new DefaultGrouper(unitSize)); + } + + public static MutationDetails createDetails(String clazz) { + return new MutationDetails(aMutationId().withLocation(aLocation(clazz)) + .build(), "", "desc", 42, 0); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationTestUnitTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationTestUnitTest.java index 81ae0ceaf..bdf677089 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationTestUnitTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/MutationTestUnitTest.java @@ -1,86 +1,86 @@ -package org.pitest.mutationtest.build; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.EngineArguments; -import org.pitest.mutationtest.MutationConfig; -import org.pitest.mutationtest.MutationMetaData; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.TimeoutLengthStrategy; -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationDetailsMother; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.process.JavaAgent; -import org.pitest.process.LaunchOptions; -import org.pitest.testapi.Configuration; - -public class MutationTestUnitTest { - - private MutationTestUnit testee; - private List mutations; - private Collection tests; - - @Mock - private Configuration config; - - private MutationConfig mutationConfig; - - @Mock - private TimeoutLengthStrategy timeout; - - @Mock - private JavaAgent javaAgent; - - @Mock - private MutationEngine engine; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.mutationConfig = new MutationConfig(this.engine, new LaunchOptions( - this.javaAgent)); - this.mutations = new ArrayList<>(); - this.tests = new ArrayList<>(); - this.testee = new MutationTestUnit(this.mutations, this.tests, - new WorkerFactory(null, TestPluginArguments.defaults(), this.mutationConfig, EngineArguments.arguments(), this.timeout, - false, null)); - - } - - @Test - public void shouldReportWhenMutationsNotCoveredByAnyTest() throws Exception { - addMutation(); - this.tests.add(ClassName.fromString("foo")); - final MutationMetaData actual = this.testee.call(); - final MutationResult expected = new MutationResult(this.mutations.get(0), - new MutationStatusTestPair(0, DetectionStatus.NO_COVERAGE)); - assertThat(actual.getMutations()).contains(expected); - } - - @Test - public void shouldReportPriorityBasedOnNumberOfMutations() { - this.mutations.add(MutationDetailsMother.aMutationDetail().build()); - this.testee = new MutationTestUnit(MutationDetailsMother.aMutationDetail() - .build(42), this.tests, null); - assertThat(this.testee.priority()).isEqualTo(42); - } - - private void addMutation() { - this.mutations.add(new MutationDetails(aMutationId().build(), "file", "desc", - 0, 0)); - } - -} +package org.pitest.mutationtest.build; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.EngineArguments; +import org.pitest.mutationtest.MutationConfig; +import org.pitest.mutationtest.MutationMetaData; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.TimeoutLengthStrategy; +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationDetailsMother; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.process.JavaAgent; +import org.pitest.process.LaunchOptions; +import org.pitest.testapi.Configuration; + +public class MutationTestUnitTest { + + private MutationTestUnit testee; + private List mutations; + private Collection tests; + + @Mock + private Configuration config; + + private MutationConfig mutationConfig; + + @Mock + private TimeoutLengthStrategy timeout; + + @Mock + private JavaAgent javaAgent; + + @Mock + private MutationEngine engine; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.mutationConfig = new MutationConfig(this.engine, new LaunchOptions( + this.javaAgent)); + this.mutations = new ArrayList<>(); + this.tests = new ArrayList<>(); + this.testee = new MutationTestUnit(this.mutations, this.tests, + new WorkerFactory(null, TestPluginArguments.defaults(), this.mutationConfig, EngineArguments.arguments(), this.timeout, + false, null)); + + } + + @Test + public void shouldReportWhenMutationsNotCoveredByAnyTest() throws Exception { + addMutation(); + this.tests.add(ClassName.fromString("foo")); + final MutationMetaData actual = this.testee.call(); + final MutationResult expected = new MutationResult(this.mutations.get(0), + new MutationStatusTestPair(0, DetectionStatus.NO_COVERAGE)); + assertThat(actual.getMutations()).contains(expected); + } + + @Test + public void shouldReportPriorityBasedOnNumberOfMutations() { + this.mutations.add(MutationDetailsMother.aMutationDetail().build()); + this.testee = new MutationTestUnit(MutationDetailsMother.aMutationDetail() + .build(42), this.tests, null); + assertThat(this.testee.priority()).isEqualTo(42); + } + + private void addMutation() { + this.mutations.add(new MutationDetails(aMutationId().build(), "file", "desc", + 0, 0)); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/TestInfoPriorisationComparatorTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/TestInfoPriorisationComparatorTest.java index 7ec793933..df11b6fef 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/TestInfoPriorisationComparatorTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/TestInfoPriorisationComparatorTest.java @@ -1,99 +1,99 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.build; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.TestInfo; -import java.util.Optional; - -public class TestInfoPriorisationComparatorTest { - - private static final String TARGET = "target"; - private static final int TIME_WEIGHTING = 1000; - - private TestInfoPriorisationComparator testee; - - @Before - public void setUp() { - this.testee = new TestInfoPriorisationComparator(ClassName.fromString(TARGET), - TIME_WEIGHTING); - } - - @Test - public void shouldPrioritiseFasterTestsThatDirectlyTestTargetBeforeSlowerTestsThatDirectlyTestTarget() { - - final TestInfo reallySlow = testInfo(2000, TARGET); - final TestInfo slow = testInfo(2, TARGET); - final TestInfo fast = testInfo(1, TARGET); - final List actual = sortWithTestee(slow, reallySlow, fast); - - assertThat(actual, is(Arrays.asList(fast, slow, reallySlow))); - } - - @Test - public void shouldFavourTestsThatDirectlyTestTargetOverFasterTestsThatDontByApplyingATimeWeighting() { - - final TestInfo slowButClose = testInfo(TIME_WEIGHTING, TARGET); - final TestInfo fastButDistant = testInfo(1, "notTarget"); - final TestInfo verySlowButClose = testInfo( - TIME_WEIGHTING + fastButDistant.getTime() + 1, TARGET); - - final List actual = sortWithTestee(verySlowButClose, - slowButClose, fastButDistant); - - assertThat(actual, - is(Arrays.asList(slowButClose, fastButDistant, verySlowButClose))); - } - - @Test - public void shouldFavourTestsThatCoverFewerLinesInTheSameAmountOfTime() { - final TestInfo fastButWide = testInfo(1, TARGET, 100); - final TestInfo fastAndTargetted = testInfo(1, TARGET, 1); - final TestInfo fastAndSlightlyTargetted = testInfo(1, TARGET, 50); - - final List actual = sortWithTestee(fastButWide, - fastAndSlightlyTargetted, fastAndTargetted); - - assertThat(actual, is(Arrays.asList(fastAndTargetted, - fastAndSlightlyTargetted, fastButWide))); - - } - - private List sortWithTestee(final TestInfo... testInfos) { - final List list = Arrays.asList(testInfos); - Collections.sort(list, this.testee); - return list; - } - - private TestInfo testInfo(final int time, final String target) { - return testInfo(time, target, 0); - } - - private TestInfo testInfo(final int time, final String target, - final int linesCovered) { - return new TestInfo("", time + target + linesCovered, time, - Optional.ofNullable(ClassName.fromString(target)), linesCovered); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.build; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.TestInfo; +import java.util.Optional; + +public class TestInfoPriorisationComparatorTest { + + private static final String TARGET = "target"; + private static final int TIME_WEIGHTING = 1000; + + private TestInfoPriorisationComparator testee; + + @Before + public void setUp() { + this.testee = new TestInfoPriorisationComparator(ClassName.fromString(TARGET), + TIME_WEIGHTING); + } + + @Test + public void shouldPrioritiseFasterTestsThatDirectlyTestTargetBeforeSlowerTestsThatDirectlyTestTarget() { + + final TestInfo reallySlow = testInfo(2000, TARGET); + final TestInfo slow = testInfo(2, TARGET); + final TestInfo fast = testInfo(1, TARGET); + final List actual = sortWithTestee(slow, reallySlow, fast); + + assertThat(actual, is(Arrays.asList(fast, slow, reallySlow))); + } + + @Test + public void shouldFavourTestsThatDirectlyTestTargetOverFasterTestsThatDontByApplyingATimeWeighting() { + + final TestInfo slowButClose = testInfo(TIME_WEIGHTING, TARGET); + final TestInfo fastButDistant = testInfo(1, "notTarget"); + final TestInfo verySlowButClose = testInfo( + TIME_WEIGHTING + fastButDistant.getTime() + 1, TARGET); + + final List actual = sortWithTestee(verySlowButClose, + slowButClose, fastButDistant); + + assertThat(actual, + is(Arrays.asList(slowButClose, fastButDistant, verySlowButClose))); + } + + @Test + public void shouldFavourTestsThatCoverFewerLinesInTheSameAmountOfTime() { + final TestInfo fastButWide = testInfo(1, TARGET, 100); + final TestInfo fastAndTargetted = testInfo(1, TARGET, 1); + final TestInfo fastAndSlightlyTargetted = testInfo(1, TARGET, 50); + + final List actual = sortWithTestee(fastButWide, + fastAndSlightlyTargetted, fastAndTargetted); + + assertThat(actual, is(Arrays.asList(fastAndTargetted, + fastAndSlightlyTargetted, fastButWide))); + + } + + private List sortWithTestee(final TestInfo... testInfos) { + final List list = Arrays.asList(testInfos); + Collections.sort(list, this.testee); + return list; + } + + private TestInfo testInfo(final int time, final String target) { + return testInfo(time, target, 0); + } + + private TestInfo testInfo(final int time, final String target, + final int linesCovered) { + return new TestInfo("", time + target + linesCovered, time, + Optional.ofNullable(ClassName.fromString(target)), linesCovered); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptorTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptorTest.java index 5abbd74c6..412290743 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptorTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/annotations/ExcludedAnnotationInterceptorTest.java @@ -1,124 +1,124 @@ -package org.pitest.mutationtest.build.intercept.annotations; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator; - -public class ExcludedAnnotationInterceptorTest { - - ExcludedAnnotationInterceptor testee = new ExcludedAnnotationInterceptor(Arrays.asList("TestGeneratedAnnotation", "AnotherTestAnnotation")); - Mutater mutator; - - @Before - public void setUp() { - final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - final Collection mutators = Collections.singleton((MethodMutatorFactory)VoidMethodCallMutator.VOID_METHOD_CALL_MUTATOR); - this.mutator = new GregorMutater(source, m -> true, mutators); - } - - - @Test - public void shouldDeclareSelfAsFilter() { - assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); - } - - @Test - public void shouldNotFilterMutationsWhenNoAnnotations() { - final Collection input = someMutations(); - final Collection actual = runWithTestee(input, UnAnnotated.class); - assertThat(actual).containsExactlyElementsOf(input); - } - - @Test - public void shouldFilterAllMutationsForClassesWithGeneratedAnnotation() { - final Collection actual = runWithTestee(someMutations(), AnnotatedWithGenerated.class); - assertThat(actual).isEmpty(); - } - - @Test - public void shouldFilterAllMutationsForClassesWithDoNoMutateAnnotation() { - final Collection actual = runWithTestee(someMutations(), AnnotatedWithDoNotMutate.class); - assertThat(actual).isEmpty(); - } - - @Test - public void shouldFilterMethodsWithGeneratedAnnotation() { - final List mutations = this.mutator.findMutations(ClassName.fromClass(MethodAnnotatedWithGenerated.class)); - final Collection actual = runWithTestee(mutations, MethodAnnotatedWithGenerated.class); - assertThat(actual).hasSize(1); - assertThat(actual.iterator().next().getId().getLocation().getMethodName().name()).isEqualTo("bar"); - } - - private Collection runWithTestee( - Collection input, Class clazz) { - this.testee.begin(treeFor(clazz)); - final Collection actual = this.testee.intercept(input, this.mutator); - return actual; - } - - private Collection someMutations() { - return aMutationDetail().build(2); - } - - ClassTree treeFor(Class clazz) { - final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - return ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); - } - - -} - -class UnAnnotated { - -} - -@TestGeneratedAnnotation -class AnnotatedWithGenerated { - -} - -@AnotherTestAnnotation -class AnnotatedWithDoNotMutate { - -} - -class MethodAnnotatedWithGenerated { - @TestGeneratedAnnotation - public void foo() { - System.out.println("don't mutate me"); - } - - public void bar() { - System.out.println("mutate me"); - } -} - -@Retention(value=RetentionPolicy.RUNTIME) -@interface TestGeneratedAnnotation { - -} - -@Retention(value=RetentionPolicy.CLASS) -@interface AnotherTestAnnotation { - -} - - +package org.pitest.mutationtest.build.intercept.annotations; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator; + +public class ExcludedAnnotationInterceptorTest { + + ExcludedAnnotationInterceptor testee = new ExcludedAnnotationInterceptor(Arrays.asList("TestGeneratedAnnotation", "AnotherTestAnnotation")); + Mutater mutator; + + @Before + public void setUp() { + final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + final Collection mutators = Collections.singleton((MethodMutatorFactory)VoidMethodCallMutator.VOID_METHOD_CALL_MUTATOR); + this.mutator = new GregorMutater(source, m -> true, mutators); + } + + + @Test + public void shouldDeclareSelfAsFilter() { + assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); + } + + @Test + public void shouldNotFilterMutationsWhenNoAnnotations() { + final Collection input = someMutations(); + final Collection actual = runWithTestee(input, UnAnnotated.class); + assertThat(actual).containsExactlyElementsOf(input); + } + + @Test + public void shouldFilterAllMutationsForClassesWithGeneratedAnnotation() { + final Collection actual = runWithTestee(someMutations(), AnnotatedWithGenerated.class); + assertThat(actual).isEmpty(); + } + + @Test + public void shouldFilterAllMutationsForClassesWithDoNoMutateAnnotation() { + final Collection actual = runWithTestee(someMutations(), AnnotatedWithDoNotMutate.class); + assertThat(actual).isEmpty(); + } + + @Test + public void shouldFilterMethodsWithGeneratedAnnotation() { + final List mutations = this.mutator.findMutations(ClassName.fromClass(MethodAnnotatedWithGenerated.class)); + final Collection actual = runWithTestee(mutations, MethodAnnotatedWithGenerated.class); + assertThat(actual).hasSize(1); + assertThat(actual.iterator().next().getId().getLocation().getMethodName().name()).isEqualTo("bar"); + } + + private Collection runWithTestee( + Collection input, Class clazz) { + this.testee.begin(treeFor(clazz)); + final Collection actual = this.testee.intercept(input, this.mutator); + return actual; + } + + private Collection someMutations() { + return aMutationDetail().build(2); + } + + ClassTree treeFor(Class clazz) { + final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + return ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); + } + + +} + +class UnAnnotated { + +} + +@TestGeneratedAnnotation +class AnnotatedWithGenerated { + +} + +@AnotherTestAnnotation +class AnnotatedWithDoNotMutate { + +} + +class MethodAnnotatedWithGenerated { + @TestGeneratedAnnotation + public void foo() { + System.out.println("don't mutate me"); + } + + public void bar() { + System.out.println("mutate me"); + } +} + +@Retention(value=RetentionPolicy.RUNTIME) +@interface TestGeneratedAnnotation { + +} + +@Retention(value=RetentionPolicy.CLASS) +@interface AnotherTestAnnotation { + +} + + diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilterTest.java index 9c69413bf..8fbfa0024 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/equivalent/EqualsPerformanceShortcutFilterTest.java @@ -1,176 +1,176 @@ -package org.pitest.mutationtest.build.intercept.equivalent; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import org.junit.Test; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.mutationtest.engine.gregor.config.Mutator; -import org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator; - -public class EqualsPerformanceShortcutFilterTest { - - ClassByteArraySource source = ClassloaderByteArraySource - .fromContext(); - EqualsPerformanceShortcutFilter testee = new EqualsPerformanceShortcutFilter(); - - final GregorMutater mutator = createMutator( - Mutator.byName("REMOVE_CONDITIONALS")); - - @Test - public void shouldDeclareTypeAsFilter() { - assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); - } - - @Test - public void shouldNotFilterShortCutMutantsNotInEqualsMethods() { - assertFiltersNMutations(HasNonOveridingEquals.class, 0); - } - - @Test - public void shouldNotFilterGeneralMutantsInEqualMethods() { - final GregorMutater mutator = createMutator( - ReturnValsMutator.RETURN_VALS_MUTATOR); - final List mutations = mutator - .findMutations(ClassName.fromClass(HasNonShortCutEquals.class)); - assertThat(mutations).hasSize(1); - - this.testee.begin(forClass(HasNonShortCutEquals.class)); - final Collection actual = this.testee.intercept(mutations, - mutator); - this.testee.end(); - - assertThat(actual).hasSize(1); - } - - @Test - public void shouldFilterShortCutEqualsMutantsInEqualMethods() { - assertFiltersNMutations(HasShortCutEquals.class, 1); - } - - @Test - public void shouldNotFilterShortCutMutantsNotInGeneralMethods() { - assertFiltersNMutations(HasShortcutInGeneralMethod.class, 0); - } - - @Test - public void shouldFilterShortCutEqualsInGenericisedClasses() { - assertFiltersNMutations(BrokenEqualsAndGenerics.class, 1); - } - - private void assertFiltersNMutations(Class muteee, int n) { - final List mutations = this.mutator - .findMutations(ClassName.fromClass(muteee)); - - this.testee.begin(forClass(muteee)); - final Collection actual = this.testee.intercept(mutations, - this.mutator); - this.testee.end(); - - assertThat(actual).hasSize(mutations.size() - n); - } - - GregorMutater createMutator(MethodMutatorFactory... factories) { - final Collection mutators = Arrays.asList(factories); - return createMutator(mutators); - } - - GregorMutater createMutator(Collection factories) { - return new GregorMutater(this.source, m -> true, factories); - } - - ClassTree forClass(Class clazz) { - final byte[] bs = this.source.getBytes(clazz.getName()).get(); - return ClassTree.fromBytes(bs); - } -} - -class HasNonShortCutEquals { - @Override - public boolean equals(Object other) { - return other.getClass().isAssignableFrom(this.getClass()); - } -} - -class HasNonOveridingEquals { - public boolean equals(HasNonOveridingEquals obj) { - if (this == obj) { - return true; - } - return false; - } -} - -class HasShortcutInGeneralMethod { - public boolean compare(Object obj) { - if (this == obj) { - return true; - } - return false; - } -} - - -class HasShortCutEquals { - private String s; - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final HasShortCutEquals other = (HasShortCutEquals) obj; - if (this.s == null) { - if (other.s != null) { - return false; - } - } else if (!this.s.equals(other.s)) { - return false; - } - return true; - } - -} - - -final class BrokenEqualsAndGenerics { - public final A _1; - public final B _2; - - private BrokenEqualsAndGenerics(A _1, B _2) { - this._1 = _1; - this._2 = _2; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - return false; - } -} - +package org.pitest.mutationtest.build.intercept.equivalent; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.junit.Test; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.mutationtest.engine.gregor.config.Mutator; +import org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator; + +public class EqualsPerformanceShortcutFilterTest { + + ClassByteArraySource source = ClassloaderByteArraySource + .fromContext(); + EqualsPerformanceShortcutFilter testee = new EqualsPerformanceShortcutFilter(); + + final GregorMutater mutator = createMutator( + Mutator.byName("REMOVE_CONDITIONALS")); + + @Test + public void shouldDeclareTypeAsFilter() { + assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); + } + + @Test + public void shouldNotFilterShortCutMutantsNotInEqualsMethods() { + assertFiltersNMutations(HasNonOveridingEquals.class, 0); + } + + @Test + public void shouldNotFilterGeneralMutantsInEqualMethods() { + final GregorMutater mutator = createMutator( + ReturnValsMutator.RETURN_VALS_MUTATOR); + final List mutations = mutator + .findMutations(ClassName.fromClass(HasNonShortCutEquals.class)); + assertThat(mutations).hasSize(1); + + this.testee.begin(forClass(HasNonShortCutEquals.class)); + final Collection actual = this.testee.intercept(mutations, + mutator); + this.testee.end(); + + assertThat(actual).hasSize(1); + } + + @Test + public void shouldFilterShortCutEqualsMutantsInEqualMethods() { + assertFiltersNMutations(HasShortCutEquals.class, 1); + } + + @Test + public void shouldNotFilterShortCutMutantsNotInGeneralMethods() { + assertFiltersNMutations(HasShortcutInGeneralMethod.class, 0); + } + + @Test + public void shouldFilterShortCutEqualsInGenericisedClasses() { + assertFiltersNMutations(BrokenEqualsAndGenerics.class, 1); + } + + private void assertFiltersNMutations(Class muteee, int n) { + final List mutations = this.mutator + .findMutations(ClassName.fromClass(muteee)); + + this.testee.begin(forClass(muteee)); + final Collection actual = this.testee.intercept(mutations, + this.mutator); + this.testee.end(); + + assertThat(actual).hasSize(mutations.size() - n); + } + + GregorMutater createMutator(MethodMutatorFactory... factories) { + final Collection mutators = Arrays.asList(factories); + return createMutator(mutators); + } + + GregorMutater createMutator(Collection factories) { + return new GregorMutater(this.source, m -> true, factories); + } + + ClassTree forClass(Class clazz) { + final byte[] bs = this.source.getBytes(clazz.getName()).get(); + return ClassTree.fromBytes(bs); + } +} + +class HasNonShortCutEquals { + @Override + public boolean equals(Object other) { + return other.getClass().isAssignableFrom(this.getClass()); + } +} + +class HasNonOveridingEquals { + public boolean equals(HasNonOveridingEquals obj) { + if (this == obj) { + return true; + } + return false; + } +} + +class HasShortcutInGeneralMethod { + public boolean compare(Object obj) { + if (this == obj) { + return true; + } + return false; + } +} + + +class HasShortCutEquals { + private String s; + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final HasShortCutEquals other = (HasShortCutEquals) obj; + if (this.s == null) { + if (other.s != null) { + return false; + } + } else if (!this.s.equals(other.s)) { + return false; + } + return true; + } + +} + + +final class BrokenEqualsAndGenerics { + public final A _1; + public final B _2; + + private BrokenEqualsAndGenerics(A _1, B _2) { + this._1 = _1; + this._2 = _2; + } + + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + return false; + } +} + diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/equivalent/EquivalentReturnMutationFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/equivalent/EquivalentReturnMutationFilterTest.java index 3c683763e..3be2af35d 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/equivalent/EquivalentReturnMutationFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/equivalent/EquivalentReturnMutationFilterTest.java @@ -1,277 +1,277 @@ -package org.pitest.mutationtest.build.intercept.equivalent; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.pitest.mutationtest.engine.gregor.mutators.BooleanFalseReturnValsMutator.BOOLEAN_FALSE_RETURN; -import static org.pitest.mutationtest.engine.gregor.mutators.BooleanTrueReturnValsMutator.BOOLEAN_TRUE_RETURN; - -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.junit.Test; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.build.intercept.javafeatures.FilterTester; -import org.pitest.mutationtest.engine.gregor.mutators.EmptyObjectReturnValsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.NullReturnValsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.PrimitiveReturnsMutator; - -public class EquivalentReturnMutationFilterTest { - - MutationInterceptor testee = new EquivalentReturnMutationFilter().createInterceptor(null); - - FilterTester verifier = new FilterTester("", this.testee, PrimitiveReturnsMutator.PRIMITIVE_RETURN_VALS_MUTATOR - , EmptyObjectReturnValsMutator.EMPTY_RETURN_VALUES - , NullReturnValsMutator.NULL_RETURN_VALUES - , BOOLEAN_FALSE_RETURN - , BOOLEAN_TRUE_RETURN); - - @Test - public void shouldDeclareTypeAsFilter() { - assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); - } - - @Test - public void doesNotFilterNonEquivalents() { - this.verifier.assertFiltersNMutationFromClass(0, ReturnsWidget.class); - } - - @Test - public void filtersNullEquivalentMutants() { - this.verifier.assertFiltersNMutationFromClass(1, ReturnsNull.class); - } - - @Test - public void filtersEquivalentPrimitiveIntMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsConstZero.class); - } - - @Test - public void filtersEquivalentPrimitiveBooleanMutants() { - this.verifier.assertFiltersMutationsFromMutator(BOOLEAN_FALSE_RETURN.getGloballyUniqueId() - , AlreadyReturnsFalse.class); - } - - @Test - public void filtersEquivalentPrimitiveBooleanTrueMutants() { - this.verifier.assertFiltersMutationsFromMutator(BOOLEAN_TRUE_RETURN.getGloballyUniqueId() - , ReturnsTrue.class); - } - - @Test - public void filtersEquivalentPrimitiveLongMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsLong0.class); - } - - @Test - public void filtersEquivalentPrimitiveFloatMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsFloat0.class); - } - - @Test - public void filtersEquivalentPrimitiveDoubleMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsDouble0.class); - } - - @Test - public void filtersEquivalentBoxedBooleanMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedFalse.class); - } - - @Test - public void filtersEquivalentBoxedBooleanTrueMutants() { - this.verifier.assertFiltersMutationsFromMutator(BOOLEAN_TRUE_RETURN.getGloballyUniqueId() - , AlreadyReturnsBoxedTrue.class); - } - - @Test - public void filtersEquivalentBoxedIntegerMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroInteger.class); - } - - @Test - public void filtersEquivalentBoxedShortMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroShort.class); - } - - @Test - public void filtersEquivalentBoxedLongMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroLong.class); - } - - @Test - public void filtersEquivalentBoxedFloatMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroFloat.class); - } - - @Test - public void filtersEquivalentBoxedDoubleMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroDouble.class); - } - - @Test - public void doesNotFilterOtherSingleParamStaticMethodCalls() { - this.verifier.assertFiltersNMutationFromClass(0, CallsAnIntegerReturningStaticWith0.class); - } - - @Test - public void filtersEquivalentStringMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptyString.class); - } - - @Test - public void filtersEquivalentStringMutantsWhenEmptyStringHeldAsField() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptyStringFromField.class); - } - - @Test - public void filtersEquivalentListMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptyList.class); - } - - @Test - public void filtersEquivalentSetMutants() { - this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptySet.class); - } - -// can't include test as must build on java 7 -// @Test -// public void filtersEquivalentOptionalMutants() { -// verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptyOptional.class); -// } -} - -class Widget{} - -class ReturnsWidget { - public Widget a() { - return new Widget(); - } -} - -class ReturnsNull { - public Widget a() { - return null; - } -} - -class ReturnsTrue { - public boolean a() { - return true; - } -} - -class AlreadyReturnsConstZero { - public int a() { - return 0; - } -} - -class AlreadyReturnsBoxedFalse { - public Boolean a() { - return false; - } -} - -class AlreadyReturnsBoxedTrue { - public Boolean a() { - return true; - } -} - -class AlreadyReturnsFalse { - public boolean a() { - return false; - } -} - -class AlreadyReturnsBoxedZeroInteger { - public Integer a() { - return 0; - } -} - -class CallsAnIntegerReturningStaticWith0 { - - static Integer foo(int a) { - return 42; - } - - public Integer a() { - return foo(0); - } -} - -class AlreadyReturnsBoxedZeroShort { - public Short a() { - return 0; - } -} - -class AlreadyReturnsLong0 { - public long a() { - return 0; - } -} - -class AlreadyReturnsBoxedZeroLong { - public Long a() { - return 0l; - } -} - -class AlreadyReturnsFloat0 { - public float a() { - return 0; - } -} - -class AlreadyReturnsDouble0 { - public double a() { - return 0; - } -} - - -class AlreadyReturnsBoxedZeroFloat { - public Float a() { - return 0f; - } -} - -class AlreadyReturnsBoxedZeroDouble { - public Double a() { - return 0d; - } -} - -class AlreadyReturnsEmptyString { - public String a() { - return ""; - } -} - -class AlreadyReturnsEmptyStringFromField { - static final String EMPTY = ""; - public String a() { - return EMPTY; - } -} - -class AlreadyReturnsEmptyList { - public List a() { - return Collections.emptyList(); - } -} - -class AlreadyReturnsEmptySet { - public Set a() { - return Collections.emptySet(); - } -} - -//class AlreadyReturnsEmptyOptional { -// public Optional a() { -// return Optional.empty(); -// } -//} +package org.pitest.mutationtest.build.intercept.equivalent; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.pitest.mutationtest.engine.gregor.mutators.BooleanFalseReturnValsMutator.BOOLEAN_FALSE_RETURN; +import static org.pitest.mutationtest.engine.gregor.mutators.BooleanTrueReturnValsMutator.BOOLEAN_TRUE_RETURN; + +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.Test; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.build.intercept.javafeatures.FilterTester; +import org.pitest.mutationtest.engine.gregor.mutators.EmptyObjectReturnValsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.NullReturnValsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.PrimitiveReturnsMutator; + +public class EquivalentReturnMutationFilterTest { + + MutationInterceptor testee = new EquivalentReturnMutationFilter().createInterceptor(null); + + FilterTester verifier = new FilterTester("", this.testee, PrimitiveReturnsMutator.PRIMITIVE_RETURN_VALS_MUTATOR + , EmptyObjectReturnValsMutator.EMPTY_RETURN_VALUES + , NullReturnValsMutator.NULL_RETURN_VALUES + , BOOLEAN_FALSE_RETURN + , BOOLEAN_TRUE_RETURN); + + @Test + public void shouldDeclareTypeAsFilter() { + assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); + } + + @Test + public void doesNotFilterNonEquivalents() { + this.verifier.assertFiltersNMutationFromClass(0, ReturnsWidget.class); + } + + @Test + public void filtersNullEquivalentMutants() { + this.verifier.assertFiltersNMutationFromClass(1, ReturnsNull.class); + } + + @Test + public void filtersEquivalentPrimitiveIntMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsConstZero.class); + } + + @Test + public void filtersEquivalentPrimitiveBooleanMutants() { + this.verifier.assertFiltersMutationsFromMutator(BOOLEAN_FALSE_RETURN.getGloballyUniqueId() + , AlreadyReturnsFalse.class); + } + + @Test + public void filtersEquivalentPrimitiveBooleanTrueMutants() { + this.verifier.assertFiltersMutationsFromMutator(BOOLEAN_TRUE_RETURN.getGloballyUniqueId() + , ReturnsTrue.class); + } + + @Test + public void filtersEquivalentPrimitiveLongMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsLong0.class); + } + + @Test + public void filtersEquivalentPrimitiveFloatMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsFloat0.class); + } + + @Test + public void filtersEquivalentPrimitiveDoubleMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsDouble0.class); + } + + @Test + public void filtersEquivalentBoxedBooleanMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedFalse.class); + } + + @Test + public void filtersEquivalentBoxedBooleanTrueMutants() { + this.verifier.assertFiltersMutationsFromMutator(BOOLEAN_TRUE_RETURN.getGloballyUniqueId() + , AlreadyReturnsBoxedTrue.class); + } + + @Test + public void filtersEquivalentBoxedIntegerMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroInteger.class); + } + + @Test + public void filtersEquivalentBoxedShortMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroShort.class); + } + + @Test + public void filtersEquivalentBoxedLongMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroLong.class); + } + + @Test + public void filtersEquivalentBoxedFloatMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroFloat.class); + } + + @Test + public void filtersEquivalentBoxedDoubleMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsBoxedZeroDouble.class); + } + + @Test + public void doesNotFilterOtherSingleParamStaticMethodCalls() { + this.verifier.assertFiltersNMutationFromClass(0, CallsAnIntegerReturningStaticWith0.class); + } + + @Test + public void filtersEquivalentStringMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptyString.class); + } + + @Test + public void filtersEquivalentStringMutantsWhenEmptyStringHeldAsField() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptyStringFromField.class); + } + + @Test + public void filtersEquivalentListMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptyList.class); + } + + @Test + public void filtersEquivalentSetMutants() { + this.verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptySet.class); + } + +// can't include test as must build on java 7 +// @Test +// public void filtersEquivalentOptionalMutants() { +// verifier.assertFiltersNMutationFromClass(1, AlreadyReturnsEmptyOptional.class); +// } +} + +class Widget{} + +class ReturnsWidget { + public Widget a() { + return new Widget(); + } +} + +class ReturnsNull { + public Widget a() { + return null; + } +} + +class ReturnsTrue { + public boolean a() { + return true; + } +} + +class AlreadyReturnsConstZero { + public int a() { + return 0; + } +} + +class AlreadyReturnsBoxedFalse { + public Boolean a() { + return false; + } +} + +class AlreadyReturnsBoxedTrue { + public Boolean a() { + return true; + } +} + +class AlreadyReturnsFalse { + public boolean a() { + return false; + } +} + +class AlreadyReturnsBoxedZeroInteger { + public Integer a() { + return 0; + } +} + +class CallsAnIntegerReturningStaticWith0 { + + static Integer foo(int a) { + return 42; + } + + public Integer a() { + return foo(0); + } +} + +class AlreadyReturnsBoxedZeroShort { + public Short a() { + return 0; + } +} + +class AlreadyReturnsLong0 { + public long a() { + return 0; + } +} + +class AlreadyReturnsBoxedZeroLong { + public Long a() { + return 0l; + } +} + +class AlreadyReturnsFloat0 { + public float a() { + return 0; + } +} + +class AlreadyReturnsDouble0 { + public double a() { + return 0; + } +} + + +class AlreadyReturnsBoxedZeroFloat { + public Float a() { + return 0f; + } +} + +class AlreadyReturnsBoxedZeroDouble { + public Double a() { + return 0d; + } +} + +class AlreadyReturnsEmptyString { + public String a() { + return ""; + } +} + +class AlreadyReturnsEmptyStringFromField { + static final String EMPTY = ""; + public String a() { + return EMPTY; + } +} + +class AlreadyReturnsEmptyList { + public List a() { + return Collections.emptyList(); + } +} + +class AlreadyReturnsEmptySet { + public Set a() { + return Collections.emptySet(); + } +} + +//class AlreadyReturnsEmptyOptional { +// public Optional a() { +// return Optional.empty(); +// } +//} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/FilterTester.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/FilterTester.java index fab85ef27..89dc0fb4d 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/FilterTester.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/FilterTester.java @@ -1,256 +1,256 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.assertj.core.api.Condition; -import org.assertj.core.api.SoftAssertions; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.build.MutationInterceptor; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.util.ResourceFolderByteArraySource; - -public class FilterTester { - - private static final Collection COMPILERS = Arrays.asList("javac", - "ecj", "aspectj"); - - private final String path; - private final ClassByteArraySource source = new ResourceFolderByteArraySource(); - private final MutationInterceptor testee; - private final Collection mutators; - - public FilterTester(String path, MutationInterceptor testee, MethodMutatorFactory ... mutators) { - this(path, testee, Arrays.asList(mutators)); - } - - public FilterTester(String path, MutationInterceptor testee, Collection mutators) { - this.mutators = mutators; - this.testee = testee; - this.path = path; - } - - - public void assertFiltersMutationAtNLocations(int n, Class clazz) { - final Sample s = makeSampleForCurrentCompiler(clazz); - assertFiltersMutationAtNLocations(n, s, mutateFromClassLoader()); - } - - public void assertFiltersMutationAtNLocations(int n, Sample s, GregorMutater mutator) { - final List mutations = mutator.findMutations(s.className); - final Collection actual = filter(s.clazz, mutations, mutator); - - final Set originalLocations = new LinkedHashSet<>(); - FCollection.mapTo(mutations, toLocation(s.clazz), originalLocations); - - final Set filteredLocations = new LinkedHashSet<>(); - FCollection.mapTo(actual, toLocation(s.clazz), filteredLocations); - - assertThat(filteredLocations) - .describedAs("Expected to filter %d locations from the %d in %s", n, originalLocations.size(), s.clazz.toString()) - .hasSize(originalLocations.size() - n); - - } - - private Function toLocation(final ClassTree tree) { - return a -> { - final MethodTree method = tree.method(a.getId().getLocation()).get(); - final Loc l = new Loc(); - l.index = a.getInstructionIndex(); - l.node = method.instructions().get(a.getInstructionIndex()); - return l; - }; - } - - public void assertLeavesNMutants(int n, String sample) { - final GregorMutater mutator = mutateFromResourceDir(); - atLeastOneSampleExists(sample); - - final SoftAssertions softly = new SoftAssertions(); - - for (final Sample s : samples(sample)) { - final List mutations = mutator.findMutations(s.className); - final Collection actual = filter(s.clazz, mutations, mutator); - - softly.assertThat(actual) - .describedAs("Wrong number of mutants with " + s.compiler) - .hasSize(n); - } - - softly.assertAll(); - } - - public void assertFiltersNMutationFromSample(int n, String sample) { - final GregorMutater mutator = mutateFromResourceDir(); - atLeastOneSampleExists(sample); - - final SoftAssertions softly = new SoftAssertions(); - - for (final Sample s : samples(sample)) { - assertFiltersNMutants(n, mutator, s, softly); - } - - softly.assertAll(); - } - - public void assertFiltersNMutationFromClass(int n, Class clazz) { - final Sample s = makeSampleForCurrentCompiler(clazz); - - final SoftAssertions softly = new SoftAssertions(); - - assertFiltersNMutants(n, mutateFromClassLoader(), s, softly); - - softly.assertAll(); - } - - private Sample makeSampleForCurrentCompiler(Class clazz) { - final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - final Sample s = new Sample(); - s.className = ClassName.fromClass(clazz); - s.clazz = ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); - s.compiler = "current"; - return s; - } - - public void assertFiltersMutationsFromMutator(String id, Class clazz) { - final Sample s = sampleForClass(clazz); - final GregorMutater mutator = mutateFromClassLoader(); - final List mutations = mutator.findMutations(s.className); - final Collection actual = filter(s.clazz, mutations, mutator); - - final SoftAssertions softly = new SoftAssertions(); - checkHasNMutants(1, s, softly, mutations); - - final List filteredOut = FCollection.filter(mutations, notIn(actual)); - - softly.assertThat(filteredOut).describedAs("No mutants filtered").isNotEmpty(); - softly.assertThat(filteredOut).have(mutatedBy(id)); - softly.assertAll(); - - } - - private Condition mutatedBy(final String id) { - return new Condition() { - @Override - public boolean matches(MutationDetails value) { - return value.getId().getMutator().equals(id); - } - - }; - } - - private Predicate notIn( - final Collection actual) { - return a -> !actual.contains(a); - } - - private void assertFiltersNMutants(int n, GregorMutater mutator, Sample s, SoftAssertions softly) { - final List mutations = mutator.findMutations(s.className); - final Collection actual = filter(s.clazz, mutations, mutator); - - checkHasNMutants(n, s, softly, mutations); - - softly.assertThat((mutations.size() == 0) && (n == 0)) - .describedAs("Expecting no mutations to be filtered, but none were produced") - .isFalse(); - - - softly.assertThat(actual) - .describedAs("Expected to filter out " + n + " mutants but filtered " - + (mutations.size() - actual.size()) + " for compiler " + s.compiler - + " " + s.clazz) - .hasSize(mutations.size() - n); - } - - private void checkHasNMutants(int n, Sample s, SoftAssertions softly, - List mutations) { - softly.assertThat(mutations.size()) - .describedAs("Fewer mutations produced than expected with " + s.compiler + ". This test has a bug in it.\n" + s.clazz) - .isGreaterThanOrEqualTo(n); - } - - private GregorMutater mutateFromResourceDir() { - return new GregorMutater(this.source, m -> true, this.mutators); - } - - private GregorMutater mutateFromClassLoader() { - return new GregorMutater( ClassloaderByteArraySource.fromContext(), m -> true, this.mutators); - } - - - private String makeClassName(String sample, String compiler) { - final String clazz = MessageFormat.format(this.path, sample, compiler); - return clazz; - } - - - private List samples(final String sample) { - final Function> toPair = compiler -> { - final String clazz = makeClassName(sample, compiler); - final Optional bs = FilterTester.this.source.getBytes(clazz); - if (bs.isPresent()) { - final Sample p = new Sample(); - p.className = ClassName.fromString(clazz); - p.clazz = ClassTree.fromBytes(bs.get()); - p.compiler = compiler; - return Stream.of(p); - } - return Stream.empty(); - - }; - return COMPILERS.stream().flatMap(toPair).collect(Collectors.toList()); - } - - private boolean atLeastOneSampleExists(String sample) { - for (final String compiler : COMPILERS) { - final String clazz = makeClassName(sample, compiler); - if (this.source.getBytes(clazz).isPresent()) { - return true; - } - } - throw new RuntimeException("No samples found for any compiler for " + sample); - } - - private Collection filter(ClassTree clazz, - List mutations, Mutater mutator) { - this.testee.begin(clazz); - final Collection actual = this.testee.intercept(mutations, mutator); - this.testee.end(); - return actual; - } - - - private Sample sampleForClass(Class clazz) { - final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - final Sample s = new Sample(); - s.className = ClassName.fromClass(clazz); - s.clazz = ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); - s.compiler = "current"; - return s; - } -} - -class Sample { - ClassName className; - String compiler; - ClassTree clazz; -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.assertj.core.api.Condition; +import org.assertj.core.api.SoftAssertions; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.build.MutationInterceptor; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.util.ResourceFolderByteArraySource; + +public class FilterTester { + + private static final Collection COMPILERS = Arrays.asList("javac", + "ecj", "aspectj"); + + private final String path; + private final ClassByteArraySource source = new ResourceFolderByteArraySource(); + private final MutationInterceptor testee; + private final Collection mutators; + + public FilterTester(String path, MutationInterceptor testee, MethodMutatorFactory ... mutators) { + this(path, testee, Arrays.asList(mutators)); + } + + public FilterTester(String path, MutationInterceptor testee, Collection mutators) { + this.mutators = mutators; + this.testee = testee; + this.path = path; + } + + + public void assertFiltersMutationAtNLocations(int n, Class clazz) { + final Sample s = makeSampleForCurrentCompiler(clazz); + assertFiltersMutationAtNLocations(n, s, mutateFromClassLoader()); + } + + public void assertFiltersMutationAtNLocations(int n, Sample s, GregorMutater mutator) { + final List mutations = mutator.findMutations(s.className); + final Collection actual = filter(s.clazz, mutations, mutator); + + final Set originalLocations = new LinkedHashSet<>(); + FCollection.mapTo(mutations, toLocation(s.clazz), originalLocations); + + final Set filteredLocations = new LinkedHashSet<>(); + FCollection.mapTo(actual, toLocation(s.clazz), filteredLocations); + + assertThat(filteredLocations) + .describedAs("Expected to filter %d locations from the %d in %s", n, originalLocations.size(), s.clazz.toString()) + .hasSize(originalLocations.size() - n); + + } + + private Function toLocation(final ClassTree tree) { + return a -> { + final MethodTree method = tree.method(a.getId().getLocation()).get(); + final Loc l = new Loc(); + l.index = a.getInstructionIndex(); + l.node = method.instructions().get(a.getInstructionIndex()); + return l; + }; + } + + public void assertLeavesNMutants(int n, String sample) { + final GregorMutater mutator = mutateFromResourceDir(); + atLeastOneSampleExists(sample); + + final SoftAssertions softly = new SoftAssertions(); + + for (final Sample s : samples(sample)) { + final List mutations = mutator.findMutations(s.className); + final Collection actual = filter(s.clazz, mutations, mutator); + + softly.assertThat(actual) + .describedAs("Wrong number of mutants with " + s.compiler) + .hasSize(n); + } + + softly.assertAll(); + } + + public void assertFiltersNMutationFromSample(int n, String sample) { + final GregorMutater mutator = mutateFromResourceDir(); + atLeastOneSampleExists(sample); + + final SoftAssertions softly = new SoftAssertions(); + + for (final Sample s : samples(sample)) { + assertFiltersNMutants(n, mutator, s, softly); + } + + softly.assertAll(); + } + + public void assertFiltersNMutationFromClass(int n, Class clazz) { + final Sample s = makeSampleForCurrentCompiler(clazz); + + final SoftAssertions softly = new SoftAssertions(); + + assertFiltersNMutants(n, mutateFromClassLoader(), s, softly); + + softly.assertAll(); + } + + private Sample makeSampleForCurrentCompiler(Class clazz) { + final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + final Sample s = new Sample(); + s.className = ClassName.fromClass(clazz); + s.clazz = ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); + s.compiler = "current"; + return s; + } + + public void assertFiltersMutationsFromMutator(String id, Class clazz) { + final Sample s = sampleForClass(clazz); + final GregorMutater mutator = mutateFromClassLoader(); + final List mutations = mutator.findMutations(s.className); + final Collection actual = filter(s.clazz, mutations, mutator); + + final SoftAssertions softly = new SoftAssertions(); + checkHasNMutants(1, s, softly, mutations); + + final List filteredOut = FCollection.filter(mutations, notIn(actual)); + + softly.assertThat(filteredOut).describedAs("No mutants filtered").isNotEmpty(); + softly.assertThat(filteredOut).have(mutatedBy(id)); + softly.assertAll(); + + } + + private Condition mutatedBy(final String id) { + return new Condition() { + @Override + public boolean matches(MutationDetails value) { + return value.getId().getMutator().equals(id); + } + + }; + } + + private Predicate notIn( + final Collection actual) { + return a -> !actual.contains(a); + } + + private void assertFiltersNMutants(int n, GregorMutater mutator, Sample s, SoftAssertions softly) { + final List mutations = mutator.findMutations(s.className); + final Collection actual = filter(s.clazz, mutations, mutator); + + checkHasNMutants(n, s, softly, mutations); + + softly.assertThat((mutations.size() == 0) && (n == 0)) + .describedAs("Expecting no mutations to be filtered, but none were produced") + .isFalse(); + + + softly.assertThat(actual) + .describedAs("Expected to filter out " + n + " mutants but filtered " + + (mutations.size() - actual.size()) + " for compiler " + s.compiler + + " " + s.clazz) + .hasSize(mutations.size() - n); + } + + private void checkHasNMutants(int n, Sample s, SoftAssertions softly, + List mutations) { + softly.assertThat(mutations.size()) + .describedAs("Fewer mutations produced than expected with " + s.compiler + ". This test has a bug in it.\n" + s.clazz) + .isGreaterThanOrEqualTo(n); + } + + private GregorMutater mutateFromResourceDir() { + return new GregorMutater(this.source, m -> true, this.mutators); + } + + private GregorMutater mutateFromClassLoader() { + return new GregorMutater( ClassloaderByteArraySource.fromContext(), m -> true, this.mutators); + } + + + private String makeClassName(String sample, String compiler) { + final String clazz = MessageFormat.format(this.path, sample, compiler); + return clazz; + } + + + private List samples(final String sample) { + final Function> toPair = compiler -> { + final String clazz = makeClassName(sample, compiler); + final Optional bs = FilterTester.this.source.getBytes(clazz); + if (bs.isPresent()) { + final Sample p = new Sample(); + p.className = ClassName.fromString(clazz); + p.clazz = ClassTree.fromBytes(bs.get()); + p.compiler = compiler; + return Stream.of(p); + } + return Stream.empty(); + + }; + return COMPILERS.stream().flatMap(toPair).collect(Collectors.toList()); + } + + private boolean atLeastOneSampleExists(String sample) { + for (final String compiler : COMPILERS) { + final String clazz = makeClassName(sample, compiler); + if (this.source.getBytes(clazz).isPresent()) { + return true; + } + } + throw new RuntimeException("No samples found for any compiler for " + sample); + } + + private Collection filter(ClassTree clazz, + List mutations, Mutater mutator) { + this.testee.begin(clazz); + final Collection actual = this.testee.intercept(mutations, mutator); + this.testee.end(); + return actual; + } + + + private Sample sampleForClass(Class clazz) { + final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + final Sample s = new Sample(); + s.className = ClassName.fromClass(clazz); + s.clazz = ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); + s.compiler = "current"; + return s; + } +} + +class Sample { + ClassName className; + String compiler; + ClassTree clazz; +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachFilterTest.java index 7391884b9..c5e12bc8e 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/ForEachFilterTest.java @@ -1,132 +1,132 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.junit.Test; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator; -import org.pitest.mutationtest.engine.gregor.mutators.NullMutateEverything; - -public class ForEachFilterTest { - private static final String PATH = "foreach/{0}_{1}"; - - ForEachLoopFilter testee = new ForEachLoopFilter(); - FilterTester verifier = new FilterTester(PATH, this.testee, NullMutateEverything.asList()); - - @Test - public void declaresTypeAsFilter() { - assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); - } - - @Test - public void filtersMutationsToForEachLoopJumps() { - this.verifier = new FilterTester(PATH, this.testee, NegateConditionalsMutator.NEGATE_CONDITIONALS_MUTATOR); - this.verifier.assertFiltersNMutationFromSample(1, "HasForEachLoop"); - } - - @Test - public void filtersMutationsToHasNextAndNext() { - this.verifier = new FilterTester(PATH, this.testee, NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); - // can mutate calls to iterator, hasNext and next - this.verifier.assertFiltersNMutationFromSample(3, "HasForEachLoop"); - } - - @Test - public void filtersMutationsToForEachOverField() { - this.verifier = new FilterTester(PATH, this.testee, NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); - // can mutate calls to iterator, hasNext and next - this.verifier.assertFiltersNMutationFromClass(3, HasForEachLoopOverField.class); - } - - @Test - public void filtersMutationsToForEachOverMethodReturn() { - this.verifier = new FilterTester(PATH, this.testee, NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); - // can mutate calls to iterator, hasNext and next - this.verifier.assertFiltersNMutationFromClass(3, HasForEachLoopOverMethodReturn.class); - } - - @Test - public void filtersMutationsToForEachOverCollections() { - this.verifier = new FilterTester(PATH, this.testee, NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); - // can mutate calls to iterator, hasNext and next - this.verifier.assertFiltersNMutationFromClass(3, HasForEachLoopOverCollection.class); - } - - @Test - public void filtersMutationsToForEachOverArrays() { - // arrayLength, IConst, Jump, IINC - this.verifier.assertFiltersNMutationFromSample(4, "HasForEachLoopOverArray"); - } - - - @Test - public void doesNotFilterMutationsToIndexedForLoopJumps() { - this.verifier = new FilterTester("forloops/{0}_{1}", this.testee, NegateConditionalsMutator.NEGATE_CONDITIONALS_MUTATOR); - this.verifier.assertFiltersNMutationFromSample(0, "HasAForLoop"); - } - - @Test - public void doesNotFilterMutationsToHandRolledIteratorLoops() { - // additional label nodes seem to be enough to prevent triggering - this.verifier.assertFiltersNMutationFromSample(0, "HandRolledIteratorLoop"); - } - - public static class HasForEachLoop { - void foo(List is) { - for (final int each : is) { - System.out.println(each); - } - } - } - - public static class HasForEachLoopOverField { - List is; - void foo() { - for (final int each : this.is) { - System.out.println(each); - } - } - } - - public static class HasForEachLoopOverMethodReturn { - void foo() { - for (final int each : Collections.singletonList(1)) { - System.out.println(each); - } - } - } - - public static class HasForEachLoopOverCollection { - void foo(Collection c) { - for (final int each : c) { - System.out.println(each); - } - } - } - - public static class HasForEachLoopOverArray { - void foo(int[] is) { - for (final int each : is) { - System.out.println(each); - } - } - } - - - static class HandRolledIteratorLoop { - void foo(List is) { - final Iterator it = is.iterator(); - while (it.hasNext()) { - final Integer each = it.next(); - System.out.println(each); - } - } - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.junit.Test; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator; +import org.pitest.mutationtest.engine.gregor.mutators.NullMutateEverything; + +public class ForEachFilterTest { + private static final String PATH = "foreach/{0}_{1}"; + + ForEachLoopFilter testee = new ForEachLoopFilter(); + FilterTester verifier = new FilterTester(PATH, this.testee, NullMutateEverything.asList()); + + @Test + public void declaresTypeAsFilter() { + assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); + } + + @Test + public void filtersMutationsToForEachLoopJumps() { + this.verifier = new FilterTester(PATH, this.testee, NegateConditionalsMutator.NEGATE_CONDITIONALS_MUTATOR); + this.verifier.assertFiltersNMutationFromSample(1, "HasForEachLoop"); + } + + @Test + public void filtersMutationsToHasNextAndNext() { + this.verifier = new FilterTester(PATH, this.testee, NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); + // can mutate calls to iterator, hasNext and next + this.verifier.assertFiltersNMutationFromSample(3, "HasForEachLoop"); + } + + @Test + public void filtersMutationsToForEachOverField() { + this.verifier = new FilterTester(PATH, this.testee, NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); + // can mutate calls to iterator, hasNext and next + this.verifier.assertFiltersNMutationFromClass(3, HasForEachLoopOverField.class); + } + + @Test + public void filtersMutationsToForEachOverMethodReturn() { + this.verifier = new FilterTester(PATH, this.testee, NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); + // can mutate calls to iterator, hasNext and next + this.verifier.assertFiltersNMutationFromClass(3, HasForEachLoopOverMethodReturn.class); + } + + @Test + public void filtersMutationsToForEachOverCollections() { + this.verifier = new FilterTester(PATH, this.testee, NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); + // can mutate calls to iterator, hasNext and next + this.verifier.assertFiltersNMutationFromClass(3, HasForEachLoopOverCollection.class); + } + + @Test + public void filtersMutationsToForEachOverArrays() { + // arrayLength, IConst, Jump, IINC + this.verifier.assertFiltersNMutationFromSample(4, "HasForEachLoopOverArray"); + } + + + @Test + public void doesNotFilterMutationsToIndexedForLoopJumps() { + this.verifier = new FilterTester("forloops/{0}_{1}", this.testee, NegateConditionalsMutator.NEGATE_CONDITIONALS_MUTATOR); + this.verifier.assertFiltersNMutationFromSample(0, "HasAForLoop"); + } + + @Test + public void doesNotFilterMutationsToHandRolledIteratorLoops() { + // additional label nodes seem to be enough to prevent triggering + this.verifier.assertFiltersNMutationFromSample(0, "HandRolledIteratorLoop"); + } + + public static class HasForEachLoop { + void foo(List is) { + for (final int each : is) { + System.out.println(each); + } + } + } + + public static class HasForEachLoopOverField { + List is; + void foo() { + for (final int each : this.is) { + System.out.println(each); + } + } + } + + public static class HasForEachLoopOverMethodReturn { + void foo() { + for (final int each : Collections.singletonList(1)) { + System.out.println(each); + } + } + } + + public static class HasForEachLoopOverCollection { + void foo(Collection c) { + for (final int each : c) { + System.out.println(each); + } + } + } + + public static class HasForEachLoopOverArray { + void foo(int[] is) { + for (final int each : is) { + System.out.println(each); + } + } + } + + + static class HandRolledIteratorLoop { + void foo(List is) { + final Iterator it = is.iterator(); + while (it.hasNext()) { + final Integer each = it.next(); + System.out.println(each); + } + } + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilterTest.java index b10da14a0..8794748c0 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/ImplicitNullCheckFilterTest.java @@ -1,43 +1,43 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.engine.gregor.config.Mutator; - -public class ImplicitNullCheckFilterTest { - - private static final String PATH = "implicitnullcheck/{0}_{1}"; - - ImplicitNullCheckFilter testee = new ImplicitNullCheckFilter(); - FilterTester verifier = new FilterTester(PATH, this.testee, Mutator.all()); - - @Test - public void shouldDeclareTypeAsFilter() { - assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); - } - - @Test - public void shouldFilterMutantsThatAlterGetClassCallsInALambda() { - this.verifier.assertFiltersNMutationFromSample(1, "RemovedCallBug"); - } - - @Test - public void flteraMutantsThatAlterGetClassInImplicitNullCheck() { - this.verifier.assertFiltersNMutationFromSample(1, "ImplicitNullCheck"); - } - - @Test - public void shouldNotFilterDeadCallsToGetClassInNonLambdaMethods() { - this.verifier.assertFiltersNMutationFromClass(0, HasDeadCode.class); - } - -} - -class HasDeadCode { - public void foo(Object o) { - o.getClass(); - } -} - +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.engine.gregor.config.Mutator; + +public class ImplicitNullCheckFilterTest { + + private static final String PATH = "implicitnullcheck/{0}_{1}"; + + ImplicitNullCheckFilter testee = new ImplicitNullCheckFilter(); + FilterTester verifier = new FilterTester(PATH, this.testee, Mutator.all()); + + @Test + public void shouldDeclareTypeAsFilter() { + assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); + } + + @Test + public void shouldFilterMutantsThatAlterGetClassCallsInALambda() { + this.verifier.assertFiltersNMutationFromSample(1, "RemovedCallBug"); + } + + @Test + public void flteraMutantsThatAlterGetClassInImplicitNullCheck() { + this.verifier.assertFiltersNMutationFromSample(1, "ImplicitNullCheck"); + } + + @Test + public void shouldNotFilterDeadCallsToGetClassInNonLambdaMethods() { + this.verifier.assertFiltersNMutationFromClass(0, HasDeadCode.class); + } + +} + +class HasDeadCode { + public void foo(Object o) { + o.getClass(); + } +} + diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilterTest.java index bc1ccfda6..6e75f7771 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/InlinedFinallyBlockFilterTest.java @@ -1,105 +1,105 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.junit.Assert.assertEquals; -import static org.pitest.mutationtest.LocationMother.aLocation; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.junit.Test; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.mutationtest.engine.PoisonStatus; - -public class InlinedFinallyBlockFilterTest { - - InlinedFinallyBlockFilter testee = new InlinedFinallyBlockFilter(); - Mutater unused; - - @Test - public void shouldDeclareTypeAsFilter() { - assertEquals(InterceptorType.FILTER, this.testee.type()); - } - - @Test - public void shouldNotCombineMutantsWhenOnSameLineAndDifferentBlocksButFromDifferentMutators() { - final int line = 100; - final int block = 1; - final List mutations = Arrays.asList( - makeMutant(line, block, "Foo", 0), - makeMutant(line, block + 1, "NotFoo", 1)); - assertEquals(mutations, this.testee.intercept(mutations, this.unused)); - } - - @Test - public void shouldNotCombineMutantsWhenOnSameLineAndBlock() { - final int line = 100; - final int block = 1; - final String mutator = "foo"; - final List mutations = Arrays.asList( - makeMutant(line, block, mutator, 0), - makeMutant(line, block, mutator, 1)); - assertEquals(mutations, this.testee.intercept(mutations, this.unused)); - } - - @Test - public void shouldCreateSingleMutantWhenSameMutationCreatedOnSameLineInDifferentBlocksAndOneIsInAHandlerBlock() { - final int line = 100; - final String mutator = "foo"; - final int block = 1000; - final List mutations = Arrays.asList( - makeMutantInHandlerBlock(line, block, mutator, 0), - makeMutant(line, block + 1, mutator, 1)); - assertEquals( - Arrays.asList(makeMutantInHandlerBlock(line, block, mutator, - Arrays.asList(0, 1))), this.testee.intercept(mutations, this.unused)); - } - - @Test - public void shouldNotCombineMutationsWhenMoreThanOneInAHandlerBlock() { - final int line = 100; - final String mutator = "foo"; - final int block = 1000; - final List mutations = Arrays.asList( - makeMutantInHandlerBlock(line, block, mutator, 0), - makeMutantInHandlerBlock(line, block, mutator, 2), - makeMutant(line, block + 1, mutator, 1)); - final Collection actual = this.testee.intercept(mutations, this.unused); - assertEquals(mutations, actual); - } - - private MutationDetails makeMutantInHandlerBlock(final int line, - final int block, final String mutator, final int index) { - return new MutationDetails(makeId(Collections.singleton(index), mutator), - "file", "desc", line, block, true, PoisonStatus.NORMAL); - } - - private MutationDetails makeMutantInHandlerBlock(final int line, - final int block, final String mutator, final Collection indexes) { - return new MutationDetails(makeId(new HashSet<>(indexes), mutator), - "file", "desc", line, block, true, PoisonStatus.NORMAL); - } - - private MutationDetails makeMutant(final int line, final int block, - final String mutator, final Collection indexes) { - return new MutationDetails(makeId(new HashSet<>(indexes), mutator), - "file", "desc", line, block); - } - - private MutationDetails makeMutant(final int line, final int block, - final String mutator, final int index) { - return makeMutant(line, block, mutator, Arrays.asList(index)); - } - - private MutationIdentifier makeId(final Set indexes, - final String mutator) { - return new MutationIdentifier(aLocation().build(), indexes, mutator); - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.junit.Assert.assertEquals; +import static org.pitest.mutationtest.LocationMother.aLocation; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Test; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.mutationtest.engine.PoisonStatus; + +public class InlinedFinallyBlockFilterTest { + + InlinedFinallyBlockFilter testee = new InlinedFinallyBlockFilter(); + Mutater unused; + + @Test + public void shouldDeclareTypeAsFilter() { + assertEquals(InterceptorType.FILTER, this.testee.type()); + } + + @Test + public void shouldNotCombineMutantsWhenOnSameLineAndDifferentBlocksButFromDifferentMutators() { + final int line = 100; + final int block = 1; + final List mutations = Arrays.asList( + makeMutant(line, block, "Foo", 0), + makeMutant(line, block + 1, "NotFoo", 1)); + assertEquals(mutations, this.testee.intercept(mutations, this.unused)); + } + + @Test + public void shouldNotCombineMutantsWhenOnSameLineAndBlock() { + final int line = 100; + final int block = 1; + final String mutator = "foo"; + final List mutations = Arrays.asList( + makeMutant(line, block, mutator, 0), + makeMutant(line, block, mutator, 1)); + assertEquals(mutations, this.testee.intercept(mutations, this.unused)); + } + + @Test + public void shouldCreateSingleMutantWhenSameMutationCreatedOnSameLineInDifferentBlocksAndOneIsInAHandlerBlock() { + final int line = 100; + final String mutator = "foo"; + final int block = 1000; + final List mutations = Arrays.asList( + makeMutantInHandlerBlock(line, block, mutator, 0), + makeMutant(line, block + 1, mutator, 1)); + assertEquals( + Arrays.asList(makeMutantInHandlerBlock(line, block, mutator, + Arrays.asList(0, 1))), this.testee.intercept(mutations, this.unused)); + } + + @Test + public void shouldNotCombineMutationsWhenMoreThanOneInAHandlerBlock() { + final int line = 100; + final String mutator = "foo"; + final int block = 1000; + final List mutations = Arrays.asList( + makeMutantInHandlerBlock(line, block, mutator, 0), + makeMutantInHandlerBlock(line, block, mutator, 2), + makeMutant(line, block + 1, mutator, 1)); + final Collection actual = this.testee.intercept(mutations, this.unused); + assertEquals(mutations, actual); + } + + private MutationDetails makeMutantInHandlerBlock(final int line, + final int block, final String mutator, final int index) { + return new MutationDetails(makeId(Collections.singleton(index), mutator), + "file", "desc", line, block, true, PoisonStatus.NORMAL); + } + + private MutationDetails makeMutantInHandlerBlock(final int line, + final int block, final String mutator, final Collection indexes) { + return new MutationDetails(makeId(new HashSet<>(indexes), mutator), + "file", "desc", line, block, true, PoisonStatus.NORMAL); + } + + private MutationDetails makeMutant(final int line, final int block, + final String mutator, final Collection indexes) { + return new MutationDetails(makeId(new HashSet<>(indexes), mutator), + "file", "desc", line, block); + } + + private MutationDetails makeMutant(final int line, final int block, + final String mutator, final int index) { + return makeMutant(line, block, mutator, Arrays.asList(index)); + } + + private MutationIdentifier makeId(final Set indexes, + final String mutator) { + return new MutationIdentifier(aLocation().build(), indexes, mutator); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/Loc.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/Loc.java index feb5266d9..78ffd7e35 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/Loc.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/Loc.java @@ -1,45 +1,45 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import org.objectweb.asm.tree.AbstractInsnNode; - -class Loc { - int index; - AbstractInsnNode node; - @Override - public String toString() { - return "[" + this.index + "] " + this.node; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + this.index; - result = (prime * result) + ((this.node == null) ? 0 : this.node.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Loc other = (Loc) obj; - if (this.index != other.index) { - return false; - } - if (this.node == null) { - if (other.node != null) { - return false; - } - } else if (!this.node.equals(other.node)) { - return false; - } - return true; - } - +package org.pitest.mutationtest.build.intercept.javafeatures; + +import org.objectweb.asm.tree.AbstractInsnNode; + +class Loc { + int index; + AbstractInsnNode node; + @Override + public String toString() { + return "[" + this.index + "] " + this.node; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + this.index; + result = (prime * result) + ((this.node == null) ? 0 : this.node.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Loc other = (Loc) obj; + if (this.index != other.index) { + return false; + } + if (this.node == null) { + if (other.node != null) { + return false; + } + } else if (!this.node.equals(other.node)) { + return false; + } + return true; + } + } \ No newline at end of file diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilterTest.java index 908566880..e6f16072a 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/javafeatures/TryWithResourcesFilterTest.java @@ -1,47 +1,47 @@ -package org.pitest.mutationtest.build.intercept.javafeatures; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.engine.gregor.config.Mutator; - -public class TryWithResourcesFilterTest { - - private static final String PATH = "trywithresources/{0}_{1}"; - - TryWithResourcesFilter testee = new TryWithResourcesFilter(); - - FilterTester verifier = new FilterTester(PATH, this.testee, Mutator.defaults()); - - @Test - public void shouldDeclareTypeAsFilter() { - assertEquals(InterceptorType.FILTER, this.testee.type()); - } - - @Test - public void shouldWorkWithTry() { - this.verifier.assertLeavesNMutants(1, "TryExample"); - } - - @Test - public void shouldWorkWithTryCatch() { - this.verifier.assertLeavesNMutants(2, "TryCatchExample"); - } - - @Test - public void shouldWorkWithTryWithInterface() { - this.verifier.assertLeavesNMutants(1, "TryWithInterfaceExample"); - } - - @Test - public void shouldWorkWithTryWithNestedTry() { - this.verifier.assertLeavesNMutants(1, "TryWithNestedTryExample"); - } - - @Test - public void shouldWorkWithTwoClosables() { - this.verifier.assertLeavesNMutants(1, "TryWithTwoCloseableExample"); - } - -} +package org.pitest.mutationtest.build.intercept.javafeatures; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.engine.gregor.config.Mutator; + +public class TryWithResourcesFilterTest { + + private static final String PATH = "trywithresources/{0}_{1}"; + + TryWithResourcesFilter testee = new TryWithResourcesFilter(); + + FilterTester verifier = new FilterTester(PATH, this.testee, Mutator.defaults()); + + @Test + public void shouldDeclareTypeAsFilter() { + assertEquals(InterceptorType.FILTER, this.testee.type()); + } + + @Test + public void shouldWorkWithTry() { + this.verifier.assertLeavesNMutants(1, "TryExample"); + } + + @Test + public void shouldWorkWithTryCatch() { + this.verifier.assertLeavesNMutants(2, "TryCatchExample"); + } + + @Test + public void shouldWorkWithTryWithInterface() { + this.verifier.assertLeavesNMutants(1, "TryWithInterfaceExample"); + } + + @Test + public void shouldWorkWithTryWithNestedTry() { + this.verifier.assertLeavesNMutants(1, "TryWithNestedTryExample"); + } + + @Test + public void shouldWorkWithTwoClosables() { + this.verifier.assertLeavesNMutants(1, "TryWithTwoCloseableExample"); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterFactoryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterFactoryTest.java index 8249d97e9..5a83d2a64 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterFactoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterFactoryTest.java @@ -1,16 +1,16 @@ -package org.pitest.mutationtest.build.intercept.kotlin; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -public class KotlinFilterFactoryTest { - - KotlinFilterFactory testee = new KotlinFilterFactory(); - - @Test - public void shouldBeOnByDefault() { - assertThat(this.testee.provides().isOnByDefault()).isTrue(); - } - -} +package org.pitest.mutationtest.build.intercept.kotlin; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class KotlinFilterFactoryTest { + + KotlinFilterFactory testee = new KotlinFilterFactory(); + + @Test + public void shouldBeOnByDefault() { + assertThat(this.testee.provides().isOnByDefault()).isTrue(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterTest.java index e570ad378..608b6f099 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/kotlin/KotlinFilterTest.java @@ -1,59 +1,59 @@ -package org.pitest.mutationtest.build.intercept.kotlin; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - -import org.junit.Test; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationDetailsMother; - -public class KotlinFilterTest { - - KotlinFilter testee = new KotlinFilter(); - private Mutater unused; - - @Test - public void shouldDeclareTypeAsFilter() { - assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); - } - - @Test - public void shouldNotFilterMutationsInLineZeroOfAJavaClass() { - final List mutations = MutationDetailsMother.aMutationDetail() - .withFilename("Foo.java") - .withLineNumber(0) - .build(0); - assertThat(this.testee.intercept(mutations, this.unused)).containsAll(mutations); - } - - @Test - public void shouldFilterMutationsInLineZeroOfAKotlinClass() { - final List mutations = MutationDetailsMother.aMutationDetail() - .withFilename("Foo.kt") - .withLineNumber(0) - .build(0); - assertThat(this.testee.intercept(mutations, this.unused)).isEmpty(); - } - - @Test - public void shouldNotFilterMutationsOhterLinesOfAKotlinClass() { - final List mutations = MutationDetailsMother.aMutationDetail() - .withFilename("Foo.kt") - .withLineNumber(1) - .build(0); - assertThat(this.testee.intercept(mutations, this.unused)).containsAll(mutations); - } - - @Test - public void shouldNotCareAboutCaseOfKotlinfileExtension() { - final List mutations = MutationDetailsMother.aMutationDetail() - .withFilename("Foo.kT") - .withLineNumber(0) - .build(0); - assertThat(this.testee.intercept(mutations, this.unused)).isEmpty(); - } - -} +package org.pitest.mutationtest.build.intercept.kotlin; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.Test; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationDetailsMother; + +public class KotlinFilterTest { + + KotlinFilter testee = new KotlinFilter(); + private Mutater unused; + + @Test + public void shouldDeclareTypeAsFilter() { + assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); + } + + @Test + public void shouldNotFilterMutationsInLineZeroOfAJavaClass() { + final List mutations = MutationDetailsMother.aMutationDetail() + .withFilename("Foo.java") + .withLineNumber(0) + .build(0); + assertThat(this.testee.intercept(mutations, this.unused)).containsAll(mutations); + } + + @Test + public void shouldFilterMutationsInLineZeroOfAKotlinClass() { + final List mutations = MutationDetailsMother.aMutationDetail() + .withFilename("Foo.kt") + .withLineNumber(0) + .build(0); + assertThat(this.testee.intercept(mutations, this.unused)).isEmpty(); + } + + @Test + public void shouldNotFilterMutationsOhterLinesOfAKotlinClass() { + final List mutations = MutationDetailsMother.aMutationDetail() + .withFilename("Foo.kt") + .withLineNumber(1) + .build(0); + assertThat(this.testee.intercept(mutations, this.unused)).containsAll(mutations); + } + + @Test + public void shouldNotCareAboutCaseOfKotlinfileExtension() { + final List mutations = MutationDetailsMother.aMutationDetail() + .withFilename("Foo.kT") + .withLineNumber(0) + .build(0); + assertThat(this.testee.intercept(mutations, this.unused)).isEmpty(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilterTest.java index 7baac3674..2b7298052 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/logging/LoggingCallsFilterTest.java @@ -1,118 +1,118 @@ -package org.pitest.mutationtest.build.intercept.logging; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.assertj.core.api.Condition; -import org.junit.Before; -import org.junit.Test; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.mutationtest.engine.gregor.config.Mutator; - -public class LoggingCallsFilterTest { - - LoggingCallsFilter testee = new LoggingCallsFilter(Collections.singleton("java/util/logging")); - - Mutater mutator; - - @Before - public void setUp() { - final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - final Collection mutators = Mutator.defaults(); - this.mutator = new GregorMutater(source, m -> true, mutators); - } - - @Test - public void shouldDeclareTypeAsFilter() { - assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); - } - - @Test - public void shouldLeaveMutantsNotOnLoggingLinesUntouched() { - final ClassName clazz = ClassName.fromClass(DoesNotLog.class); - final List input = this.mutator.findMutations(clazz); - final Collection actual = analyseWithTestee(DoesNotLog.class); - - assertThat(actual).containsExactlyElementsOf(input); - } - - @Test - public void shouldFilterMutantsOnSameLineAsLoggingCall() { - final Collection actual = analyseWithTestee(Logs.class); - assertThat(actual).isEmpty(); - } - - @Test - public void shouldNotFilterMutantsOnLinesOtherThanLoggingLine() { - final Collection actual = analyseWithTestee(LogsAndDoesNot.class); - assertThat(actual).doNotHave(mutantsIn("logs")); - assertThat(actual).haveAtLeast(1, mutantsIn("noLog")); - assertThat(actual).haveExactly(3, mutantsIn("both")); - } - - private Condition< MutationDetails> mutantsIn(final String name) { - return new Condition< MutationDetails>("mutants in the methed " + name) { - @Override - public boolean matches(MutationDetails value) { - return value.getId().getLocation().getMethodName().name().equals(name); - } - }; - } - - private Collection analyseWithTestee(Class clazz) { - final ClassName name = ClassName.fromClass(clazz); - this.testee.begin(treeFor(clazz)); - final List input = this.mutator.findMutations(name); - return this.testee.intercept(input, this.mutator); - } - - ClassTree treeFor(Class clazz) { - final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - return ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); - } - -} - -class DoesNotLog { - public int foo(int i) { - return i++; - } -} - -class Logs { - private static final Logger LOGGER = Logger.getLogger(Logs.class.getName()); - public void foo(int i) { - LOGGER.log(Level.INFO, "lot " + " of " + "string " + "conact " + i); - } -} - -class LogsAndDoesNot { - private static final Logger LOGGER = Logger.getLogger(Logs.class.getName()); - - public void logs(int i) { - LOGGER.log(Level.INFO, "lot " + " of " + "string " + "conact " + i); - } - - public int noLog(int i) { - return i++; - } - - public int both(int i) { - i = i + 42; - - LOGGER.log(Level.INFO, "lot " + " of " + "string " + "conact " + i); - return i++; - } -} +package org.pitest.mutationtest.build.intercept.logging; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.assertj.core.api.Condition; +import org.junit.Before; +import org.junit.Test; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.mutationtest.engine.gregor.config.Mutator; + +public class LoggingCallsFilterTest { + + LoggingCallsFilter testee = new LoggingCallsFilter(Collections.singleton("java/util/logging")); + + Mutater mutator; + + @Before + public void setUp() { + final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + final Collection mutators = Mutator.defaults(); + this.mutator = new GregorMutater(source, m -> true, mutators); + } + + @Test + public void shouldDeclareTypeAsFilter() { + assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); + } + + @Test + public void shouldLeaveMutantsNotOnLoggingLinesUntouched() { + final ClassName clazz = ClassName.fromClass(DoesNotLog.class); + final List input = this.mutator.findMutations(clazz); + final Collection actual = analyseWithTestee(DoesNotLog.class); + + assertThat(actual).containsExactlyElementsOf(input); + } + + @Test + public void shouldFilterMutantsOnSameLineAsLoggingCall() { + final Collection actual = analyseWithTestee(Logs.class); + assertThat(actual).isEmpty(); + } + + @Test + public void shouldNotFilterMutantsOnLinesOtherThanLoggingLine() { + final Collection actual = analyseWithTestee(LogsAndDoesNot.class); + assertThat(actual).doNotHave(mutantsIn("logs")); + assertThat(actual).haveAtLeast(1, mutantsIn("noLog")); + assertThat(actual).haveExactly(3, mutantsIn("both")); + } + + private Condition< MutationDetails> mutantsIn(final String name) { + return new Condition< MutationDetails>("mutants in the methed " + name) { + @Override + public boolean matches(MutationDetails value) { + return value.getId().getLocation().getMethodName().name().equals(name); + } + }; + } + + private Collection analyseWithTestee(Class clazz) { + final ClassName name = ClassName.fromClass(clazz); + this.testee.begin(treeFor(clazz)); + final List input = this.mutator.findMutations(name); + return this.testee.intercept(input, this.mutator); + } + + ClassTree treeFor(Class clazz) { + final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + return ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); + } + +} + +class DoesNotLog { + public int foo(int i) { + return i++; + } +} + +class Logs { + private static final Logger LOGGER = Logger.getLogger(Logs.class.getName()); + public void foo(int i) { + LOGGER.log(Level.INFO, "lot " + " of " + "string " + "conact " + i); + } +} + +class LogsAndDoesNot { + private static final Logger LOGGER = Logger.getLogger(Logs.class.getName()); + + public void logs(int i) { + LOGGER.log(Level.INFO, "lot " + " of " + "string " + "conact " + i); + } + + public int noLog(int i) { + return i++; + } + + public int both(int i) { + i = i + 42; + + LOGGER.log(Level.INFO, "lot " + " of " + "string " + "conact " + i); + return i++; + } +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilterTest.java index 0984c075a..9925bc096 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerFilterTest.java @@ -1,32 +1,32 @@ -package org.pitest.mutationtest.build.intercept.staticinitializers; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; - -import java.util.Collection; - -import org.junit.Test; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.PoisonStatus; - -public class StaticInitializerFilterTest { - - StaticInitializerFilter testee = new StaticInitializerFilter(); - - @Test - public void shouldRemoveMutationsInStaticInitCode() { - final Collection marked = aMutationDetail() - .withPoison(PoisonStatus.IS_STATIC_INITIALIZER_CODE) - .build(2); - - assertThat(this.testee.intercept(marked, null)).isEmpty(); - } - - @Test - public void shouldNotFilterNotStaticMutants() { - final Collection unmarked = aMutationDetail() - .build(2); - assertThat(this.testee.intercept(unmarked, null)).containsAll(unmarked); - } - -} +package org.pitest.mutationtest.build.intercept.staticinitializers; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; + +import java.util.Collection; + +import org.junit.Test; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.PoisonStatus; + +public class StaticInitializerFilterTest { + + StaticInitializerFilter testee = new StaticInitializerFilter(); + + @Test + public void shouldRemoveMutationsInStaticInitCode() { + final Collection marked = aMutationDetail() + .withPoison(PoisonStatus.IS_STATIC_INITIALIZER_CODE) + .build(2); + + assertThat(this.testee.intercept(marked, null)).isEmpty(); + } + + @Test + public void shouldNotFilterNotStaticMutants() { + final Collection unmarked = aMutationDetail() + .build(2); + assertThat(this.testee.intercept(unmarked, null)).containsAll(unmarked); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptorTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptorTest.java index 4f6d7f105..66335eada 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptorTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/staticinitializers/StaticInitializerInterceptorTest.java @@ -1,190 +1,190 @@ -package org.pitest.mutationtest.build.intercept.staticinitializers; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator; - -public class StaticInitializerInterceptorTest { - - StaticInitializerInterceptor testee; - GregorMutater mutator; - - @Before - public void setup() { - final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - final Collection mutators = Collections.singleton((MethodMutatorFactory)VoidMethodCallMutator.VOID_METHOD_CALL_MUTATOR); - this.mutator = new GregorMutater(source, m -> true, mutators); - this.testee = new StaticInitializerInterceptor(); - } - - @Test - public void shouldNotMarkAnyMutationsInClassWithoutStaticInitializer() { - final Class clazz = NoStaticInializer.class; - final List mutations = findMutationsFor(clazz); - - this.testee.begin(treeFor(clazz)); - final Collection actual = this.testee.intercept(mutations, this.mutator); - this.testee.end(); - - assertThat(actual).isSameAs(mutations); - } - - @Test - public void shouldMarkMutationsInStaticInitializer() { - final Collection actual = processWithTestee(HasStaticInializer.class); - assertAllMarkedAsInStaticInitializers(actual); - } - - @Test - public void shouldMarkMutationsInPrivateMethodsCalledFromStaticInitializer() { - final Collection actual = processWithTestee(HasPrivateCallsFromStaticInializer.class); - assertAllMarkedAsInStaticInitializers(actual); - } - - @Test - public void shouldNotMarkMutationsInPackageDefaultMethodsCalledFromStaticInitializer() { - final Collection actual = processWithTestee(HasDefaultCallsFromStaticInializer.class); - assertOnlyClinitMethodsMarked(actual); - } - - - @Test - public void shouldNotMarkMutationsInPrivateStaticMethodsNotInvolvedInInit() { - final Collection actual = processWithTestee(HasOtherPrivateStaticMethods.class); - assertOnlyClinitMethodsMarked(actual); - } - - @Test - public void shouldNotMarkMutationsInOverriddenMethodsNotInvolvedInStaticInit() { - final Collection actual = processWithTestee(HasOverloadedMethodsThatAreNotUsedInStaticInitialization.class); - assertOnlyClinitMethodsMarked(actual); - } - - Collection processWithTestee(Class clazz) { - this.testee.begin(treeFor(clazz)); - final Collection actual = this.testee.intercept(findMutationsFor(clazz), this.mutator); - this.testee.end(); - return actual; - } - - private List findMutationsFor(Class clazz) { - final List mutations = this.mutator.findMutations(ClassName.fromClass(clazz)); - assertThat(mutations).isNotEmpty(); - return mutations; - } - - - private ClassTree treeFor(Class clazz) { - final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - return ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); - } - - - - private void assertAllMarkedAsInStaticInitializers( - Collection actual) { - for (final MutationDetails each : actual ) { - if (!each.isInStaticInitializer()) { - fail("Expected all mutants to be marked as for static initialization but " + each + " was not"); - } - } - - } - - private void assertOnlyClinitMethodsMarked(Collection actual) { - for (final MutationDetails each : actual ) { - if (each.isInStaticInitializer()) { - if (!each.getId().getLocation().getMethodName().name().equals("")) { - fail("Expected no mutants to be marked as for static initialization but " + each + " was"); - } - } - } - - } - -} - -class NoStaticInializer { - { - System.out.println("NOT static code"); - } -} - -class HasStaticInializer { - static { - System.out.println("static code"); - } -} - -class HasPrivateCallsFromStaticInializer { - static { - a(); - } - - private static void a() { - System.out.println("static code"); - } -} - -class HasDefaultCallsFromStaticInializer { - static { - a(); - } - - static void a() { - System.out.println("NOT guaranteed to be static code"); - } -} - -class HasOtherPrivateStaticMethods { - static { - a(); - } - - private static void a() { - - } - - public static void entryPoint(int i) { - b(i); - } - - - private static void b(int i) { - System.out.println("NOT static code"); - } -} - - -class HasOverloadedMethodsThatAreNotUsedInStaticInitialization { - static { - a(); - } - - private static void a() { - - } - - public static void entryPoint(int i) { - a(i); - } - - // same name, different sig - private static void a(int i) { - System.out.println("NOT static code"); - } -} - +package org.pitest.mutationtest.build.intercept.staticinitializers; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator; + +public class StaticInitializerInterceptorTest { + + StaticInitializerInterceptor testee; + GregorMutater mutator; + + @Before + public void setup() { + final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + final Collection mutators = Collections.singleton((MethodMutatorFactory)VoidMethodCallMutator.VOID_METHOD_CALL_MUTATOR); + this.mutator = new GregorMutater(source, m -> true, mutators); + this.testee = new StaticInitializerInterceptor(); + } + + @Test + public void shouldNotMarkAnyMutationsInClassWithoutStaticInitializer() { + final Class clazz = NoStaticInializer.class; + final List mutations = findMutationsFor(clazz); + + this.testee.begin(treeFor(clazz)); + final Collection actual = this.testee.intercept(mutations, this.mutator); + this.testee.end(); + + assertThat(actual).isSameAs(mutations); + } + + @Test + public void shouldMarkMutationsInStaticInitializer() { + final Collection actual = processWithTestee(HasStaticInializer.class); + assertAllMarkedAsInStaticInitializers(actual); + } + + @Test + public void shouldMarkMutationsInPrivateMethodsCalledFromStaticInitializer() { + final Collection actual = processWithTestee(HasPrivateCallsFromStaticInializer.class); + assertAllMarkedAsInStaticInitializers(actual); + } + + @Test + public void shouldNotMarkMutationsInPackageDefaultMethodsCalledFromStaticInitializer() { + final Collection actual = processWithTestee(HasDefaultCallsFromStaticInializer.class); + assertOnlyClinitMethodsMarked(actual); + } + + + @Test + public void shouldNotMarkMutationsInPrivateStaticMethodsNotInvolvedInInit() { + final Collection actual = processWithTestee(HasOtherPrivateStaticMethods.class); + assertOnlyClinitMethodsMarked(actual); + } + + @Test + public void shouldNotMarkMutationsInOverriddenMethodsNotInvolvedInStaticInit() { + final Collection actual = processWithTestee(HasOverloadedMethodsThatAreNotUsedInStaticInitialization.class); + assertOnlyClinitMethodsMarked(actual); + } + + Collection processWithTestee(Class clazz) { + this.testee.begin(treeFor(clazz)); + final Collection actual = this.testee.intercept(findMutationsFor(clazz), this.mutator); + this.testee.end(); + return actual; + } + + private List findMutationsFor(Class clazz) { + final List mutations = this.mutator.findMutations(ClassName.fromClass(clazz)); + assertThat(mutations).isNotEmpty(); + return mutations; + } + + + private ClassTree treeFor(Class clazz) { + final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + return ClassTree.fromBytes(source.getBytes(clazz.getName()).get()); + } + + + + private void assertAllMarkedAsInStaticInitializers( + Collection actual) { + for (final MutationDetails each : actual ) { + if (!each.isInStaticInitializer()) { + fail("Expected all mutants to be marked as for static initialization but " + each + " was not"); + } + } + + } + + private void assertOnlyClinitMethodsMarked(Collection actual) { + for (final MutationDetails each : actual ) { + if (each.isInStaticInitializer()) { + if (!each.getId().getLocation().getMethodName().name().equals("")) { + fail("Expected no mutants to be marked as for static initialization but " + each + " was"); + } + } + } + + } + +} + +class NoStaticInializer { + { + System.out.println("NOT static code"); + } +} + +class HasStaticInializer { + static { + System.out.println("static code"); + } +} + +class HasPrivateCallsFromStaticInializer { + static { + a(); + } + + private static void a() { + System.out.println("static code"); + } +} + +class HasDefaultCallsFromStaticInializer { + static { + a(); + } + + static void a() { + System.out.println("NOT guaranteed to be static code"); + } +} + +class HasOtherPrivateStaticMethods { + static { + a(); + } + + private static void a() { + + } + + public static void entryPoint(int i) { + b(i); + } + + + private static void b(int i) { + System.out.println("NOT static code"); + } +} + + +class HasOverloadedMethodsThatAreNotUsedInStaticInitialization { + static { + a(); + } + + private static void a() { + + } + + public static void entryPoint(int i) { + a(i); + } + + // same name, different sig + private static void a(int i) { + System.out.println("NOT static code"); + } +} + diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCounterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCounterTest.java index 6cd599179..928a9b5e4 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCounterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/AvoidForLoopCounterTest.java @@ -1,127 +1,127 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - -import org.junit.Test; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.mutationtest.build.InterceptorType; -import org.pitest.mutationtest.build.intercept.javafeatures.FilterTester; -import org.pitest.mutationtest.engine.gregor.config.Mutator; -import org.pitest.mutationtest.engine.gregor.mutators.IncrementsMutator; - -public class AvoidForLoopCounterTest { - ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); - - AvoidForLoopCounterFilter testee = new AvoidForLoopCounterFilter(); - private static final String PATH = "forloops/{0}_{1}"; - FilterTester verifier = new FilterTester(PATH, this.testee, IncrementsMutator.INCREMENTS_MUTATOR); - - - @Test - public void shouldDeclareTypeAsFilter() { - assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); - } - - @Test - public void shouldNotFilterMutantsWhenNoLoopPresent() { - final FilterTester verifier = new FilterTester(PATH, this.testee, Mutator.all()); - verifier.assertFiltersNMutationFromSample(0, "IHaveNoLoops"); - } - - @Test - public void shouldNotFilterIncrementMutantsInConditions() { - final FilterTester verifier = new FilterTester(PATH, this.testee, Mutator.all()); - verifier.assertFiltersNMutationFromClass(0, HasIncrementsInIfs.class); - } - - @Test - public void shouldFilterMutationsThatRemoveForLoopIncrement() { - this.verifier.assertFiltersNMutationFromSample(1, "HasAForLoop"); - } - - @Test - public void shouldNotFilterOtherIncrementMutationsInForLoop() { - this.verifier.assertFiltersNMutationFromSample(1, "HasAForLoopAndOtherIncrements"); - } - - @Test - public void shouldFilterIncrementMutantInListIterationByIndex() { - this.verifier.assertFiltersNMutationFromSample(1, "HasForLoopOverList"); - } - - @Test - public void shouldFilterIncrementMutantsWhenLoopEndRetreivedFromFieldMethodCall() { - this.verifier.assertFiltersNMutationFromSample(1, "HasForLoopOverListStoredAsField"); - } - - @Test - public void shouldFilterIncrementsInArrayLoop() { - this.verifier.assertFiltersNMutationFromSample(1, "HasArrayIteration"); - } - - static class IHaveNoLoops { - void foo(boolean b) { - if ( b ) { - System.out.println("Loop free"); - } - } - } - - static class HasIncrementsInIfs { - void foo(int i) { - i = i ++; - if ( i > 10 ) { - System.out.println("Loop free"); - } - } - } - - static class HasAForLoopAndOtherIncrements { - void foo() { - int j = 0; - for (int i = 0; i != 10; i++) { - j++; - System.out.println("" + j); - } - } - } - - static class HasAForLoop { - void foo() { - for (int i = 0; i != 10; i++) { - System.out.println("" + i); - } - } - } - - static class HasForLoopOverList { - void foo(List is) { - for (int i = 0; i != is.size(); i++) { - System.out.println("" + i); - } - } - } - - static class HasForLoopOverListStoredAsField { - List is; - void foo() { - for (int i = 0; i != this.is.size(); i++) { - System.out.println("" + i); - } - } - } - - static class HasArrayIteration { - void foo(int[] is) { - for (int i = 0; i != is.length; i++) { - System.out.println("" + i); - } - } - } - -} - - +package org.pitest.mutationtest.build.intercept.timeout; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.Test; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.mutationtest.build.InterceptorType; +import org.pitest.mutationtest.build.intercept.javafeatures.FilterTester; +import org.pitest.mutationtest.engine.gregor.config.Mutator; +import org.pitest.mutationtest.engine.gregor.mutators.IncrementsMutator; + +public class AvoidForLoopCounterTest { + ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); + + AvoidForLoopCounterFilter testee = new AvoidForLoopCounterFilter(); + private static final String PATH = "forloops/{0}_{1}"; + FilterTester verifier = new FilterTester(PATH, this.testee, IncrementsMutator.INCREMENTS_MUTATOR); + + + @Test + public void shouldDeclareTypeAsFilter() { + assertThat(this.testee.type()).isEqualTo(InterceptorType.FILTER); + } + + @Test + public void shouldNotFilterMutantsWhenNoLoopPresent() { + final FilterTester verifier = new FilterTester(PATH, this.testee, Mutator.all()); + verifier.assertFiltersNMutationFromSample(0, "IHaveNoLoops"); + } + + @Test + public void shouldNotFilterIncrementMutantsInConditions() { + final FilterTester verifier = new FilterTester(PATH, this.testee, Mutator.all()); + verifier.assertFiltersNMutationFromClass(0, HasIncrementsInIfs.class); + } + + @Test + public void shouldFilterMutationsThatRemoveForLoopIncrement() { + this.verifier.assertFiltersNMutationFromSample(1, "HasAForLoop"); + } + + @Test + public void shouldNotFilterOtherIncrementMutationsInForLoop() { + this.verifier.assertFiltersNMutationFromSample(1, "HasAForLoopAndOtherIncrements"); + } + + @Test + public void shouldFilterIncrementMutantInListIterationByIndex() { + this.verifier.assertFiltersNMutationFromSample(1, "HasForLoopOverList"); + } + + @Test + public void shouldFilterIncrementMutantsWhenLoopEndRetreivedFromFieldMethodCall() { + this.verifier.assertFiltersNMutationFromSample(1, "HasForLoopOverListStoredAsField"); + } + + @Test + public void shouldFilterIncrementsInArrayLoop() { + this.verifier.assertFiltersNMutationFromSample(1, "HasArrayIteration"); + } + + static class IHaveNoLoops { + void foo(boolean b) { + if ( b ) { + System.out.println("Loop free"); + } + } + } + + static class HasIncrementsInIfs { + void foo(int i) { + i = i ++; + if ( i > 10 ) { + System.out.println("Loop free"); + } + } + } + + static class HasAForLoopAndOtherIncrements { + void foo() { + int j = 0; + for (int i = 0; i != 10; i++) { + j++; + System.out.println("" + j); + } + } + } + + static class HasAForLoop { + void foo() { + for (int i = 0; i != 10; i++) { + System.out.println("" + i); + } + } + } + + static class HasForLoopOverList { + void foo(List is) { + for (int i = 0; i != is.size(); i++) { + System.out.println("" + i); + } + } + } + + static class HasForLoopOverListStoredAsField { + List is; + void foo() { + for (int i = 0; i != this.is.size(); i++) { + System.out.println("" + i); + } + } + } + + static class HasArrayIteration { + void foo(int[] is) { + for (int i = 0; i != is.length; i++) { + System.out.println("" + i); + } + } + } + +} + + diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilterFactoryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilterFactoryTest.java index 181bafec0..5e20eb6de 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilterFactoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteForLoopFilterFactoryTest.java @@ -1,317 +1,317 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.pitest.bytecode.analysis.MethodMatchers.forLocation; - -import java.util.Collection; -import java.util.List; - -import org.junit.Ignore; -import org.junit.Test; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveIncrementsMutator; - -public class InfiniteForLoopFilterFactoryTest extends InfiniteLoopBaseTest { - ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); - - InfiniteForLoopFilter testee = new InfiniteForLoopFilter(); - - @Override - InfiniteLoopFilter testee() { - return testee; - } - - @Test - public void shouldFilterMutationsThatRemoveForLoopIncrement() { - GregorMutater mutator = createMutator(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR); - List mutations = mutator.findMutations(ClassName.fromClass(MutateMyForLoop.class)); - assertThat(mutations).hasSize(2); - - testee.begin(forClass(MutateMyForLoop.class)); - Collection actual = testee.intercept(mutations, mutator); - testee.end(); - - assertThat(actual).hasSize(1); - } - - @Test - public void shouldNotFilterMutationsInMethodsThatAppearToAlreadyHaveInfiniteLoops() { - GregorMutater mutator = createMutator(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR); - // our analysis incorrectly identifies some loops as infinite - must skip these - List mutations = mutator.findMutations(ClassName.fromClass(DontFilterMyAlreadyInfiniteLoop.class)); - assertThat(mutations).hasSize(1); - - testee.begin(forClass(DontFilterMyAlreadyInfiniteLoop.class)); - Collection actual = testee.intercept(mutations, mutator); - testee.end(); - - assertThat(actual).hasSize(1); - } - - @Test - public void shouldFindInfiniteLoopsInForLoopWithNoIncrement() { - checkFiltered(HasForLoops.class, "infiniteNoIncrement"); - } - - @Test - @Ignore("not implemented yet") - public void shouldFindInfiniteLoopsInForLoopWithNoConditional() { - checkFiltered(HasForLoops.class, "infiniteNoConditional"); - } - - @Test - public void cannotFindInfiniteLoopsInForWhenCounterDeclaredElsewhere() { - checkNotFiltered(HasForLoops.class, "infiniteDeclarationNotInFor"); - } - - - @Test - public void shouldNotFindInfiniteLoopsInCodeWithNoLoops() { - checkNotFiltered(HasForLoops.class, "noLoop"); - } - - @Test - public void shouldNotFindInfiniteLoopsInValidForLoop() { - checkNotFiltered(HasForLoops.class, "normalLoop"); - } - - @Test - public void shouldNotFindInfiniteLoopsInForLoopWithNonConditionalIncrementInLoop() { - checkNotFiltered(HasForLoops.class, "incrementInsideLoop"); - } - - @Test - @Ignore("depends on compiler") - public void mightTreatLoopsAsInifiniteDespitePotentialBreakByCondtional() { - checkFiltered(HasForLoops.class, "incrementInsideLoopConditionally"); - } - - @Test - @Ignore("need thought") - public void willFindInfiniteLoopsInForLoopWithConditionalReturn() { - // although these loops are likely not infinite, pragmatically it is - // worth avoiding mutating them as they are likely to be long running - checkFiltered(HasForLoops.class, "returnsInLoop"); - } - - @Test - @Ignore - public void shouldNotFindInfiniteLoopsInForLoopWithConditionalBreak() { - // works with javac, but eclipse makes forward jumps that we don't understand - checkNotFiltered(HasForLoops.class, "brokenByBreak"); - } - - @Test - public void shouldFindInfiniteLoopsInForLoopWithNoIncrementAndBranchedContents() { - checkFiltered(HasForLoops.class, "infiniteMoreComplex"); - } - - @Test - public void shouldFindInfiniteForLoopsWhenOtherBranchedCodePresent() { - checkFiltered(HasForLoops.class, "ifForInfiniteNoIncrement"); - } - - @Test - public void shouldNotFindInfiniteLoopsInWhileLoopWithIncrement() { - checkNotFiltered(HasWhileLoops.class, "simpleWhile"); - } - - @Test - public void shouldNotFindInfiniteLoopsInDoWhileLoopWithIncrement() { - checkNotFiltered(HasWhileLoops.class, "simpleDoWhile"); - } - - @Test - public void willNotFindInfiniteLoopsInInfiniteWhileLoop() { - // would prefer it to filter - checkNotFiltered(HasWhileLoops.class, "infiniteWhile"); - } - - @Test - public void shouldNotFindInfiniteLoopInForEach() { - checkNotFiltered(HasIteratorLoops.class, "forEach"); - } - - @Test - public void shouldNotFindInfiniteLoopInHandCodedInteratorLoop() { - checkNotFiltered(HasIteratorLoops.class, "iteratorLoop"); - } - - @Test - public void shouldMatchRealInfiniteLoopFromJodaTimeMutants() { - Location l1 = Location.location(ClassName.fromString("org.joda.time.field.BaseDateTimeField") - , MethodName.fromString("set") - , "(Lorg/joda/time/ReadablePartial;I[II)[I"); - checkFiltered(ClassName.fromString("BaseDateTimeFieldMutated"),forLocation(l1)); - - checkNotFiltered(ClassName.fromString("LocalDate"),"withPeriodAdded"); - checkFiltered(ClassName.fromString("LocalDateMutated"),"withPeriodAdded"); - - checkNotFiltered(ClassName.fromString("MonthDay"),"withPeriodAdded"); - checkFiltered(ClassName.fromString("MonthDayMutated"),"withPeriodAdded"); - - checkFiltered(ClassName.fromString("BaseChronologyMutated"),"validate"); - checkFiltered(ClassName.fromString("BaseChronologyMutated2"),"set"); - - Location l = Location.location(ClassName.fromString("org.joda.time.MonthDay") - , MethodName.fromString("withPeriodAdded") - , "(Lorg/joda/time/ReadablePeriod;I)Lorg/joda/time/MonthDay;"); - checkFiltered(ClassName.fromString("MonthDayMutated2"),forLocation(l)); - } - - -} - -class HasForLoops { - - public void noLoop() { - int i = 0; - if (i++ > 0) { - System.out.println("" + i); - } - } - - public void normalLoop() { - for (int i = 0; i != 10; i++) { - System.out.println("" + i); - } - } - - public void incrementInsideLoop() { - for (int i = 0; i != 10;) { - System.out.println("" + i); - i = i + 4; - } - } - - public void incrementInsideLoopConditionally() { - for (int i = 0; i != 10;) { - System.out.println("" + i); - if ( i != 10 ) { - i = i + 4; - } - } - } - - public void infiniteNoIncrement() { - for (int i = 0; i != 10;) { - System.out.println("" + i); - } - } - - public void infiniteMoreComplex() { - for (int i = 0; i != 10;) { - System.out.println("" + i); - if ( i != 7) { - System.out.println("7 " + i); - } else { - continue; - } - } - } - - public void ifForInfiniteNoIncrement(int j) { - if (j > 11) { - return; - } - - for (int a = 0; a != 10; a++) { - System.out.println("" + a); - } - - for (int i = 0; i != 10;) { - System.out.println("" + i); - } - } - - public void returnsInLoop() { - int j = 0; - for (int i = 0; i != 10;) { - j = j + 1; - if ( j > 10 ) { - return; - } - } - } - - public void brokenByBreak() { - int j = 0; - for (int i = 0; i != 10;) { - if ( j > 10 ) { - break; - } - j = j + 1; - } - } - - public void infiniteNoConditional() { - for (int i = 0; ; i++) { - System.out.println("" + i); - } - } - - public void infiniteAlwaysTrue() { - for (int i = 0;true; i++) { - System.out.println("" + i); - } - } - - public void infiniteDeclarationNotInFor(int size) { - for (; size> 2; ) { - System.out.println("" + size); - } - } -} - -class HasWhileLoops { - public void simpleWhile() { - int i = 0; - while (i != 10) { - System.out.println("" + i); - i = i + 1; - } - } - - public void simpleDoWhile() { - int i = 0; - do { - System.out.println("" + i); - i = i + 2; - } while ( i != 10); - } - - public void infiniteWhile() { - while(true) { - System.out.println(""); - } - } -} - - -class MutateMyForLoop { - public int normalLoop(int j) { - for (int i = 0; i != 10; i++) { - System.out.println("" + i); - } - // but leave my increment alone - return j++; - } -} - - -class DontFilterMyAlreadyInfiniteLoop { - public int normalLoop(int j) { - for (int i = 0; i != 10;) { - System.out.println("" + i); - } - return j++; - } -} - - +package org.pitest.mutationtest.build.intercept.timeout; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.pitest.bytecode.analysis.MethodMatchers.forLocation; + +import java.util.Collection; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveIncrementsMutator; + +public class InfiniteForLoopFilterFactoryTest extends InfiniteLoopBaseTest { + ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); + + InfiniteForLoopFilter testee = new InfiniteForLoopFilter(); + + @Override + InfiniteLoopFilter testee() { + return testee; + } + + @Test + public void shouldFilterMutationsThatRemoveForLoopIncrement() { + GregorMutater mutator = createMutator(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR); + List mutations = mutator.findMutations(ClassName.fromClass(MutateMyForLoop.class)); + assertThat(mutations).hasSize(2); + + testee.begin(forClass(MutateMyForLoop.class)); + Collection actual = testee.intercept(mutations, mutator); + testee.end(); + + assertThat(actual).hasSize(1); + } + + @Test + public void shouldNotFilterMutationsInMethodsThatAppearToAlreadyHaveInfiniteLoops() { + GregorMutater mutator = createMutator(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR); + // our analysis incorrectly identifies some loops as infinite - must skip these + List mutations = mutator.findMutations(ClassName.fromClass(DontFilterMyAlreadyInfiniteLoop.class)); + assertThat(mutations).hasSize(1); + + testee.begin(forClass(DontFilterMyAlreadyInfiniteLoop.class)); + Collection actual = testee.intercept(mutations, mutator); + testee.end(); + + assertThat(actual).hasSize(1); + } + + @Test + public void shouldFindInfiniteLoopsInForLoopWithNoIncrement() { + checkFiltered(HasForLoops.class, "infiniteNoIncrement"); + } + + @Test + @Ignore("not implemented yet") + public void shouldFindInfiniteLoopsInForLoopWithNoConditional() { + checkFiltered(HasForLoops.class, "infiniteNoConditional"); + } + + @Test + public void cannotFindInfiniteLoopsInForWhenCounterDeclaredElsewhere() { + checkNotFiltered(HasForLoops.class, "infiniteDeclarationNotInFor"); + } + + + @Test + public void shouldNotFindInfiniteLoopsInCodeWithNoLoops() { + checkNotFiltered(HasForLoops.class, "noLoop"); + } + + @Test + public void shouldNotFindInfiniteLoopsInValidForLoop() { + checkNotFiltered(HasForLoops.class, "normalLoop"); + } + + @Test + public void shouldNotFindInfiniteLoopsInForLoopWithNonConditionalIncrementInLoop() { + checkNotFiltered(HasForLoops.class, "incrementInsideLoop"); + } + + @Test + @Ignore("depends on compiler") + public void mightTreatLoopsAsInifiniteDespitePotentialBreakByCondtional() { + checkFiltered(HasForLoops.class, "incrementInsideLoopConditionally"); + } + + @Test + @Ignore("need thought") + public void willFindInfiniteLoopsInForLoopWithConditionalReturn() { + // although these loops are likely not infinite, pragmatically it is + // worth avoiding mutating them as they are likely to be long running + checkFiltered(HasForLoops.class, "returnsInLoop"); + } + + @Test + @Ignore + public void shouldNotFindInfiniteLoopsInForLoopWithConditionalBreak() { + // works with javac, but eclipse makes forward jumps that we don't understand + checkNotFiltered(HasForLoops.class, "brokenByBreak"); + } + + @Test + public void shouldFindInfiniteLoopsInForLoopWithNoIncrementAndBranchedContents() { + checkFiltered(HasForLoops.class, "infiniteMoreComplex"); + } + + @Test + public void shouldFindInfiniteForLoopsWhenOtherBranchedCodePresent() { + checkFiltered(HasForLoops.class, "ifForInfiniteNoIncrement"); + } + + @Test + public void shouldNotFindInfiniteLoopsInWhileLoopWithIncrement() { + checkNotFiltered(HasWhileLoops.class, "simpleWhile"); + } + + @Test + public void shouldNotFindInfiniteLoopsInDoWhileLoopWithIncrement() { + checkNotFiltered(HasWhileLoops.class, "simpleDoWhile"); + } + + @Test + public void willNotFindInfiniteLoopsInInfiniteWhileLoop() { + // would prefer it to filter + checkNotFiltered(HasWhileLoops.class, "infiniteWhile"); + } + + @Test + public void shouldNotFindInfiniteLoopInForEach() { + checkNotFiltered(HasIteratorLoops.class, "forEach"); + } + + @Test + public void shouldNotFindInfiniteLoopInHandCodedInteratorLoop() { + checkNotFiltered(HasIteratorLoops.class, "iteratorLoop"); + } + + @Test + public void shouldMatchRealInfiniteLoopFromJodaTimeMutants() { + Location l1 = Location.location(ClassName.fromString("org.joda.time.field.BaseDateTimeField") + , MethodName.fromString("set") + , "(Lorg/joda/time/ReadablePartial;I[II)[I"); + checkFiltered(ClassName.fromString("BaseDateTimeFieldMutated"),forLocation(l1)); + + checkNotFiltered(ClassName.fromString("LocalDate"),"withPeriodAdded"); + checkFiltered(ClassName.fromString("LocalDateMutated"),"withPeriodAdded"); + + checkNotFiltered(ClassName.fromString("MonthDay"),"withPeriodAdded"); + checkFiltered(ClassName.fromString("MonthDayMutated"),"withPeriodAdded"); + + checkFiltered(ClassName.fromString("BaseChronologyMutated"),"validate"); + checkFiltered(ClassName.fromString("BaseChronologyMutated2"),"set"); + + Location l = Location.location(ClassName.fromString("org.joda.time.MonthDay") + , MethodName.fromString("withPeriodAdded") + , "(Lorg/joda/time/ReadablePeriod;I)Lorg/joda/time/MonthDay;"); + checkFiltered(ClassName.fromString("MonthDayMutated2"),forLocation(l)); + } + + +} + +class HasForLoops { + + public void noLoop() { + int i = 0; + if (i++ > 0) { + System.out.println("" + i); + } + } + + public void normalLoop() { + for (int i = 0; i != 10; i++) { + System.out.println("" + i); + } + } + + public void incrementInsideLoop() { + for (int i = 0; i != 10;) { + System.out.println("" + i); + i = i + 4; + } + } + + public void incrementInsideLoopConditionally() { + for (int i = 0; i != 10;) { + System.out.println("" + i); + if ( i != 10 ) { + i = i + 4; + } + } + } + + public void infiniteNoIncrement() { + for (int i = 0; i != 10;) { + System.out.println("" + i); + } + } + + public void infiniteMoreComplex() { + for (int i = 0; i != 10;) { + System.out.println("" + i); + if ( i != 7) { + System.out.println("7 " + i); + } else { + continue; + } + } + } + + public void ifForInfiniteNoIncrement(int j) { + if (j > 11) { + return; + } + + for (int a = 0; a != 10; a++) { + System.out.println("" + a); + } + + for (int i = 0; i != 10;) { + System.out.println("" + i); + } + } + + public void returnsInLoop() { + int j = 0; + for (int i = 0; i != 10;) { + j = j + 1; + if ( j > 10 ) { + return; + } + } + } + + public void brokenByBreak() { + int j = 0; + for (int i = 0; i != 10;) { + if ( j > 10 ) { + break; + } + j = j + 1; + } + } + + public void infiniteNoConditional() { + for (int i = 0; ; i++) { + System.out.println("" + i); + } + } + + public void infiniteAlwaysTrue() { + for (int i = 0;true; i++) { + System.out.println("" + i); + } + } + + public void infiniteDeclarationNotInFor(int size) { + for (; size> 2; ) { + System.out.println("" + size); + } + } +} + +class HasWhileLoops { + public void simpleWhile() { + int i = 0; + while (i != 10) { + System.out.println("" + i); + i = i + 1; + } + } + + public void simpleDoWhile() { + int i = 0; + do { + System.out.println("" + i); + i = i + 2; + } while ( i != 10); + } + + public void infiniteWhile() { + while(true) { + System.out.println(""); + } + } +} + + +class MutateMyForLoop { + public int normalLoop(int j) { + for (int i = 0; i != 10; i++) { + System.out.println("" + i); + } + // but leave my increment alone + return j++; + } +} + + +class DontFilterMyAlreadyInfiniteLoop { + public int normalLoop(int j) { + for (int i = 0; i != 10;) { + System.out.println("" + i); + } + return j++; + } +} + + diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilterTest.java index 41bd3ab1b..7b5be0aca 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteIteratorLoopFilterTest.java @@ -1,99 +1,99 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator; -import org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveIncrementsMutator; - -public class InfiniteIteratorLoopFilterTest extends InfiniteLoopBaseTest { - - InfiniteIteratorLoopFilter testee = new InfiniteIteratorLoopFilter(); - - @Override - InfiniteIteratorLoopFilter testee() { - return this.testee; - } - - @Test - public void shouldNotFilterMutationsInMethodsThatAppearToAlreadyHaveInfiniteLoops() { - final GregorMutater mutator = createMutator(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR); - // our analysis incorrectly identifies some loops as infinite - must skip these - final List mutations = mutator.findMutations(ClassName.fromClass(DontFilterMyAlreadyInfiniteLoop.class)); - assertThat(mutations).hasSize(1); - - this.testee.begin(forClass(DontFilterMyAlreadyInfiniteLoop.class)); - final Collection actual = this.testee.intercept(mutations, mutator); - this.testee.end(); - - assertThat(actual).hasSize(1); - } - - @Test - public void shouldFilterMutationsThatRemoveIteratorNextCalls() { - final GregorMutater mutator = createMutator(NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); - final List mutations = mutator.findMutations(ClassName.fromClass(MutateMyForEachLoop.class)); - assertThat(mutations).hasSize(3); - - this.testee.begin(forClass(MutateMyForEachLoop.class)); - final Collection actual = this.testee.intercept(mutations, mutator); - this.testee.end(); - - assertThat(actual).hasSize(2); - } - - - @Test - public void shouldNotFindInfiniteLoopInForEach() { - checkNotFiltered(HasIteratorLoops.class, "forEach"); - } - - @Test - public void shouldNotFindInfiniteLoopInHandCodedInteratorLoop() { - checkNotFiltered(HasIteratorLoops.class, "iteratorLoop"); - } - - @Test - public void shouldFindInfiniteLoopInIteratorLoopWithoutNext() { - checkFiltered(HasIteratorLoops.class, "infiniteNoNextCall"); - } - -} - -class HasIteratorLoops { - public void forEach(List ss) { - for (final String each : ss) { - System.out.println(each); - } - } - - public void iteratorLoop(List ss) { - for (final String s : ss) { - System.out.println(s); - } - } - - public void infiniteNoNextCall(List ss) { - for(final Iterator it = ss.iterator(); it.hasNext(); ) { - System.out.println(it); - } - } - -} - -class MutateMyForEachLoop { - public void forEach(List ss) { - for (final String each : ss) { - System.out.println(each); - } - } -} - - +package org.pitest.mutationtest.build.intercept.timeout; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator; +import org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveIncrementsMutator; + +public class InfiniteIteratorLoopFilterTest extends InfiniteLoopBaseTest { + + InfiniteIteratorLoopFilter testee = new InfiniteIteratorLoopFilter(); + + @Override + InfiniteIteratorLoopFilter testee() { + return this.testee; + } + + @Test + public void shouldNotFilterMutationsInMethodsThatAppearToAlreadyHaveInfiniteLoops() { + final GregorMutater mutator = createMutator(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR); + // our analysis incorrectly identifies some loops as infinite - must skip these + final List mutations = mutator.findMutations(ClassName.fromClass(DontFilterMyAlreadyInfiniteLoop.class)); + assertThat(mutations).hasSize(1); + + this.testee.begin(forClass(DontFilterMyAlreadyInfiniteLoop.class)); + final Collection actual = this.testee.intercept(mutations, mutator); + this.testee.end(); + + assertThat(actual).hasSize(1); + } + + @Test + public void shouldFilterMutationsThatRemoveIteratorNextCalls() { + final GregorMutater mutator = createMutator(NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); + final List mutations = mutator.findMutations(ClassName.fromClass(MutateMyForEachLoop.class)); + assertThat(mutations).hasSize(3); + + this.testee.begin(forClass(MutateMyForEachLoop.class)); + final Collection actual = this.testee.intercept(mutations, mutator); + this.testee.end(); + + assertThat(actual).hasSize(2); + } + + + @Test + public void shouldNotFindInfiniteLoopInForEach() { + checkNotFiltered(HasIteratorLoops.class, "forEach"); + } + + @Test + public void shouldNotFindInfiniteLoopInHandCodedInteratorLoop() { + checkNotFiltered(HasIteratorLoops.class, "iteratorLoop"); + } + + @Test + public void shouldFindInfiniteLoopInIteratorLoopWithoutNext() { + checkFiltered(HasIteratorLoops.class, "infiniteNoNextCall"); + } + +} + +class HasIteratorLoops { + public void forEach(List ss) { + for (final String each : ss) { + System.out.println(each); + } + } + + public void iteratorLoop(List ss) { + for (final String s : ss) { + System.out.println(s); + } + } + + public void infiniteNoNextCall(List ss) { + for(final Iterator it = ss.iterator(); it.hasNext(); ) { + System.out.println(it); + } + } + +} + +class MutateMyForEachLoop { + public void forEach(List ss) { + for (final String each : ss) { + System.out.println(each); + } + } +} + + diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteLoopBaseTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteLoopBaseTest.java index 3cd7b8903..7060fea07 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteLoopBaseTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/build/intercept/timeout/InfiniteLoopBaseTest.java @@ -1,129 +1,129 @@ -package org.pitest.mutationtest.build.intercept.timeout; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; -import static org.pitest.bytecode.analysis.MethodMatchers.named; - -import java.io.ByteArrayOutputStream; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.function.Predicate; - -import org.objectweb.asm.util.Textifier; -import org.objectweb.asm.util.TraceMethodVisitor; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.bytecode.analysis.MethodTree; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import java.util.Optional; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.util.ResourceFolderByteArraySource; - -public abstract class InfiniteLoopBaseTest { - - ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); - - abstract InfiniteLoopFilter testee(); - - void checkNotFiltered(Class clazz, String method) { - checkNotFiltered(ClassName.fromClass(clazz), method); - } - - void checkFiltered(Class clazz, String method) { - checkFiltered(ClassName.fromClass(clazz), method); - } - - void checkNotFiltered(ClassName clazz, String method) { - checkNotFiltered(clazz, named(method)); - } - - void checkNotFiltered(ClassName clazz, Predicate method) { - boolean testedSomething = false; - for (final Compiler each : Compiler.values()) { - final Optional mt = parseMethodFromCompiledResource(clazz, each, - method); - if (mt.isPresent()) { - assertThat(testee().infiniteLoopMatcher() - .matches(mt.get().instructions())) - .describedAs("With " + each - + " compiler matched when it shouldn't " + toString(mt.get())) - .isFalse(); - testedSomething = true; - } - - } - if (!testedSomething) { - fail("No samples found for test"); - } - } - - void checkFiltered(ClassName clazz, String method) { - checkFiltered(clazz, named(method)); - } - - void checkFiltered(ClassName clazz, Predicate method) { - boolean testedSomething = false; - for (final Compiler each : Compiler.values()) { - final Optional mt = parseMethodFromCompiledResource(clazz, each, - method); - if (mt.isPresent()) { - assertThat(testee().infiniteLoopMatcher() - .matches(mt.get().instructions())) - .describedAs("With " + each - + " compiler did not match as expected " + toString(mt.get())) - .isTrue(); - testedSomething = true; - } - } - if (!testedSomething) { - fail("No samples found for test"); - } - } - - private String toString(MethodTree mt) { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - final TraceMethodVisitor mv = new TraceMethodVisitor(new Textifier()); - - mt.rawNode().accept(mv); - try (PrintWriter pw = new PrintWriter(bos)) { - mv.p.print(pw); - } - - return "Byte code is \n" + new String(bos.toByteArray()); - } - - private Optional parseMethodFromCompiledResource(ClassName clazz, - Compiler compiler, Predicate method) { - final ResourceFolderByteArraySource source = new ResourceFolderByteArraySource(); - final Optional bs = source.getBytes("loops/" + compiler.name() + "/" + clazz.getNameWithoutPackage().asJavaName()); - if (bs.isPresent()) { - final ClassTree tree = ClassTree.fromBytes(bs.get()); - return tree.methods().stream().filter(method).findFirst(); - } - return Optional.empty(); - } - - ClassTree forClass(Class clazz) { - final byte[] bs = this.source.getBytes(clazz.getName()).get(); - return ClassTree.fromBytes(bs); - } - - Collection asList(MethodMutatorFactory ...factories ) { - return Arrays.asList(factories); - } - - - GregorMutater createMutator(MethodMutatorFactory ...factories) { - final Collection mutators = asList(factories); - return new GregorMutater(this.source, m -> true, mutators); - } - -} - -enum Compiler { - eclipse, javac +package org.pitest.mutationtest.build.intercept.timeout; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; +import static org.pitest.bytecode.analysis.MethodMatchers.named; + +import java.io.ByteArrayOutputStream; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.Collection; +import java.util.function.Predicate; + +import org.objectweb.asm.util.Textifier; +import org.objectweb.asm.util.TraceMethodVisitor; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.bytecode.analysis.MethodTree; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import java.util.Optional; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.util.ResourceFolderByteArraySource; + +public abstract class InfiniteLoopBaseTest { + + ClassByteArraySource source = ClassloaderByteArraySource.fromContext(); + + abstract InfiniteLoopFilter testee(); + + void checkNotFiltered(Class clazz, String method) { + checkNotFiltered(ClassName.fromClass(clazz), method); + } + + void checkFiltered(Class clazz, String method) { + checkFiltered(ClassName.fromClass(clazz), method); + } + + void checkNotFiltered(ClassName clazz, String method) { + checkNotFiltered(clazz, named(method)); + } + + void checkNotFiltered(ClassName clazz, Predicate method) { + boolean testedSomething = false; + for (final Compiler each : Compiler.values()) { + final Optional mt = parseMethodFromCompiledResource(clazz, each, + method); + if (mt.isPresent()) { + assertThat(testee().infiniteLoopMatcher() + .matches(mt.get().instructions())) + .describedAs("With " + each + + " compiler matched when it shouldn't " + toString(mt.get())) + .isFalse(); + testedSomething = true; + } + + } + if (!testedSomething) { + fail("No samples found for test"); + } + } + + void checkFiltered(ClassName clazz, String method) { + checkFiltered(clazz, named(method)); + } + + void checkFiltered(ClassName clazz, Predicate method) { + boolean testedSomething = false; + for (final Compiler each : Compiler.values()) { + final Optional mt = parseMethodFromCompiledResource(clazz, each, + method); + if (mt.isPresent()) { + assertThat(testee().infiniteLoopMatcher() + .matches(mt.get().instructions())) + .describedAs("With " + each + + " compiler did not match as expected " + toString(mt.get())) + .isTrue(); + testedSomething = true; + } + } + if (!testedSomething) { + fail("No samples found for test"); + } + } + + private String toString(MethodTree mt) { + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + final TraceMethodVisitor mv = new TraceMethodVisitor(new Textifier()); + + mt.rawNode().accept(mv); + try (PrintWriter pw = new PrintWriter(bos)) { + mv.p.print(pw); + } + + return "Byte code is \n" + new String(bos.toByteArray()); + } + + private Optional parseMethodFromCompiledResource(ClassName clazz, + Compiler compiler, Predicate method) { + final ResourceFolderByteArraySource source = new ResourceFolderByteArraySource(); + final Optional bs = source.getBytes("loops/" + compiler.name() + "/" + clazz.getNameWithoutPackage().asJavaName()); + if (bs.isPresent()) { + final ClassTree tree = ClassTree.fromBytes(bs.get()); + return tree.methods().stream().filter(method).findFirst(); + } + return Optional.empty(); + } + + ClassTree forClass(Class clazz) { + final byte[] bs = this.source.getBytes(clazz.getName()).get(); + return ClassTree.fromBytes(bs); + } + + Collection asList(MethodMutatorFactory ...factories ) { + return Arrays.asList(factories); + } + + + GregorMutater createMutator(MethodMutatorFactory ...factories) { + final Collection mutators = asList(factories); + return new GregorMutater(this.source, m -> true, mutators); + } + +} + +enum Compiler { + eclipse, javac } \ No newline at end of file diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/config/CompoundListenerFactoryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/config/CompoundListenerFactoryTest.java index 7ca3321c4..5dfe9978c 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/config/CompoundListenerFactoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/config/CompoundListenerFactoryTest.java @@ -1,66 +1,66 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.mutationtest.ListenerArguments; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.MutationResultListenerFactory; - -public class CompoundListenerFactoryTest { - - private CompoundListenerFactory testee; - - @Mock - private MutationResultListenerFactory firstChild; - - @Mock - private MutationResultListenerFactory secondChild; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new CompoundListenerFactory(Arrays.asList(this.firstChild, - this.secondChild)); - } - - @Test - public void shouldCreateACombinedListenerForAllChildFactories() { - final MutationResultListener listenerOne = mock(MutationResultListener.class); - final MutationResultListener listenerTwo = mock(MutationResultListener.class); - when( - this.firstChild.getListener(any(Properties.class), - any(ListenerArguments.class))).thenReturn(listenerOne); - when( - this.secondChild.getListener(any(Properties.class), - any(ListenerArguments.class))).thenReturn(listenerTwo); - this.testee.getListener(null, null).runStart(); - verify(listenerOne, times(1)).runStart(); - verify(listenerTwo, times(1)).runStart(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.mutationtest.ListenerArguments; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.MutationResultListenerFactory; + +public class CompoundListenerFactoryTest { + + private CompoundListenerFactory testee; + + @Mock + private MutationResultListenerFactory firstChild; + + @Mock + private MutationResultListenerFactory secondChild; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new CompoundListenerFactory(Arrays.asList(this.firstChild, + this.secondChild)); + } + + @Test + public void shouldCreateACombinedListenerForAllChildFactories() { + final MutationResultListener listenerOne = mock(MutationResultListener.class); + final MutationResultListener listenerTwo = mock(MutationResultListener.class); + when( + this.firstChild.getListener(any(Properties.class), + any(ListenerArguments.class))).thenReturn(listenerOne); + when( + this.secondChild.getListener(any(Properties.class), + any(ListenerArguments.class))).thenReturn(listenerTwo); + this.testee.getListener(null, null).runStart(); + verify(listenerOne, times(1)).runStart(); + verify(listenerTwo, times(1)).runStart(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/config/CompoundTestListenerTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/config/CompoundTestListenerTest.java index 8d14fd54c..e4156af89 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/config/CompoundTestListenerTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/config/CompoundTestListenerTest.java @@ -1,71 +1,71 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationResultListener; - -public class CompoundTestListenerTest { - - private CompoundTestListener testee; - - @Mock - private MutationResultListener firstChild; - - @Mock - private MutationResultListener secondChild; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new CompoundTestListener(Arrays.asList(this.firstChild, - this.secondChild)); - } - - @Test - public void shouldCallOnRunStartForAllChildren() { - this.testee.runStart(); - verify(this.firstChild, times(1)).runStart(); - verify(this.secondChild, times(1)).runStart(); - } - - @Test - public void shouldCallOnRunEndForAllChildren() { - this.testee.runEnd(); - verify(this.firstChild, times(1)).runEnd(); - verify(this.secondChild, times(1)).runEnd(); - } - - @Test - public void shouldCallOnTestErrorForAllChildren() { - final ClassMutationResults metaData = new ClassMutationResults( - Collections. emptyList()); - this.testee.handleMutationResult(metaData); - verify(this.firstChild, times(1)).handleMutationResult(metaData); - verify(this.secondChild, times(1)).handleMutationResult(metaData); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationResultListener; + +public class CompoundTestListenerTest { + + private CompoundTestListener testee; + + @Mock + private MutationResultListener firstChild; + + @Mock + private MutationResultListener secondChild; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new CompoundTestListener(Arrays.asList(this.firstChild, + this.secondChild)); + } + + @Test + public void shouldCallOnRunStartForAllChildren() { + this.testee.runStart(); + verify(this.firstChild, times(1)).runStart(); + verify(this.secondChild, times(1)).runStart(); + } + + @Test + public void shouldCallOnRunEndForAllChildren() { + this.testee.runEnd(); + verify(this.firstChild, times(1)).runEnd(); + verify(this.secondChild, times(1)).runEnd(); + } + + @Test + public void shouldCallOnTestErrorForAllChildren() { + final ClassMutationResults metaData = new ClassMutationResults( + Collections. emptyList()); + this.testee.handleMutationResult(metaData); + verify(this.firstChild, times(1)).handleMutationResult(metaData); + verify(this.secondChild, times(1)).handleMutationResult(metaData); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/config/DefaultCodePathPredicateTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/config/DefaultCodePathPredicateTest.java index e7abee474..806d4c509 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/config/DefaultCodePathPredicateTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/config/DefaultCodePathPredicateTest.java @@ -1,71 +1,71 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classpath.ArchiveClassPathRoot; -import org.pitest.classpath.ClassPathRoot; -import org.pitest.classpath.DirectoryClassPathRoot; - -public class DefaultCodePathPredicateTest { - - private DefaultCodePathPredicate testee; - - @Before - public void seyUp() { - this.testee = new DefaultCodePathPredicate(); - } - - @Test - public void shouldNotTreatJarFilesAsCode() { - final ClassPathRoot archiveRoot = new ArchiveClassPathRoot(new File( - "foo.jar")); - assertFalse(this.testee.test(archiveRoot)); - } - - @Test - public void shouldNotTreatZipFilesAsCode() { - final ClassPathRoot archiveRoot = new ArchiveClassPathRoot(new File( - "foo.zip")); - assertFalse(this.testee.test(archiveRoot)); - } - - @Test - public void shouldNotTreatDirectoriesEndingInTestClassesAsCode() { - final ClassPathRoot archiveRoot = new DirectoryClassPathRoot(new File( - "foo/bar/test-classes")); - assertFalse(this.testee.test(archiveRoot)); - } - - @Test - public void shouldNotTreatDirectoriesEndingInBinTestAsCode() { - final ClassPathRoot archiveRoot = new DirectoryClassPathRoot(new File( - "foo/bar/bin-test")); - assertFalse(this.testee.test(archiveRoot)); - } - - @Test - public void shouldTreatDirectoriesAsCode() { - final ClassPathRoot archiveRoot = new DirectoryClassPathRoot(new File( - "foo/bar/")); - assertTrue(this.testee.test(archiveRoot)); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classpath.ArchiveClassPathRoot; +import org.pitest.classpath.ClassPathRoot; +import org.pitest.classpath.DirectoryClassPathRoot; + +public class DefaultCodePathPredicateTest { + + private DefaultCodePathPredicate testee; + + @Before + public void seyUp() { + this.testee = new DefaultCodePathPredicate(); + } + + @Test + public void shouldNotTreatJarFilesAsCode() { + final ClassPathRoot archiveRoot = new ArchiveClassPathRoot(new File( + "foo.jar")); + assertFalse(this.testee.test(archiveRoot)); + } + + @Test + public void shouldNotTreatZipFilesAsCode() { + final ClassPathRoot archiveRoot = new ArchiveClassPathRoot(new File( + "foo.zip")); + assertFalse(this.testee.test(archiveRoot)); + } + + @Test + public void shouldNotTreatDirectoriesEndingInTestClassesAsCode() { + final ClassPathRoot archiveRoot = new DirectoryClassPathRoot(new File( + "foo/bar/test-classes")); + assertFalse(this.testee.test(archiveRoot)); + } + + @Test + public void shouldNotTreatDirectoriesEndingInBinTestAsCode() { + final ClassPathRoot archiveRoot = new DirectoryClassPathRoot(new File( + "foo/bar/bin-test")); + assertFalse(this.testee.test(archiveRoot)); + } + + @Test + public void shouldTreatDirectoriesAsCode() { + final ClassPathRoot archiveRoot = new DirectoryClassPathRoot(new File( + "foo/bar/")); + assertTrue(this.testee.test(archiveRoot)); + } +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/config/DefaultDependencyPathPredicateTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/config/DefaultDependencyPathPredicateTest.java index 3f7f79f2a..19a40ac55 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/config/DefaultDependencyPathPredicateTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/config/DefaultDependencyPathPredicateTest.java @@ -1,51 +1,51 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classpath.ArchiveClassPathRoot; -import org.pitest.classpath.ClassPathRoot; -import org.pitest.classpath.DirectoryClassPathRoot; - -public class DefaultDependencyPathPredicateTest { - - private DefaultDependencyPathPredicate testee; - - @Before - public void seyUp() { - this.testee = new DefaultDependencyPathPredicate(); - } - - @Test - public void shouldTreatJarFilesAsDependencies() { - final ClassPathRoot archiveRoot = new ArchiveClassPathRoot(new File( - "foo.jar")); - assertTrue(this.testee.test(archiveRoot)); - } - - @Test - public void shouldNotTreatDirectoriesAsDependencies() { - final ClassPathRoot archiveRoot = new DirectoryClassPathRoot(new File( - "foo/bar/")); - assertFalse(this.testee.test(archiveRoot)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classpath.ArchiveClassPathRoot; +import org.pitest.classpath.ClassPathRoot; +import org.pitest.classpath.DirectoryClassPathRoot; + +public class DefaultDependencyPathPredicateTest { + + private DefaultDependencyPathPredicate testee; + + @Before + public void seyUp() { + this.testee = new DefaultDependencyPathPredicate(); + } + + @Test + public void shouldTreatJarFilesAsDependencies() { + final ClassPathRoot archiveRoot = new ArchiveClassPathRoot(new File( + "foo.jar")); + assertTrue(this.testee.test(archiveRoot)); + } + + @Test + public void shouldNotTreatDirectoriesAsDependencies() { + final ClassPathRoot archiveRoot = new DirectoryClassPathRoot(new File( + "foo/bar/")); + assertFalse(this.testee.test(archiveRoot)); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/config/PathNamePredicateTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/config/PathNamePredicateTest.java index 40acb2317..7f28a9774 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/config/PathNamePredicateTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/config/PathNamePredicateTest.java @@ -1,48 +1,48 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import java.io.File; - -import org.junit.Test; -import org.pitest.classpath.ClassPathRoot; -import org.pitest.classpath.DirectoryClassPathRoot; -import org.pitest.functional.prelude.Prelude; - -public class PathNamePredicateTest { - - private PathNamePredicate testee; - - @Test - public void shouldMatchRootsWithMatchingNames() { - final File testFile = new File("/foo/bar"); - final ClassPathRoot root = new DirectoryClassPathRoot(testFile); - this.testee = new PathNamePredicate(Prelude.isEqualTo(testFile - .getAbsolutePath())); - assertThat(this.testee.test(root), is(true)); - } - - @Test - public void shouldNotMatchRootsWithNonMatchingNames() { - final ClassPathRoot root = new DirectoryClassPathRoot(new File("/foo/bar/")); - this.testee = new PathNamePredicate(Prelude.isEqualTo("phoee")); - assertFalse(this.testee.test(root)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import java.io.File; + +import org.junit.Test; +import org.pitest.classpath.ClassPathRoot; +import org.pitest.classpath.DirectoryClassPathRoot; +import org.pitest.functional.prelude.Prelude; + +public class PathNamePredicateTest { + + private PathNamePredicate testee; + + @Test + public void shouldMatchRootsWithMatchingNames() { + final File testFile = new File("/foo/bar"); + final ClassPathRoot root = new DirectoryClassPathRoot(testFile); + this.testee = new PathNamePredicate(Prelude.isEqualTo(testFile + .getAbsolutePath())); + assertThat(this.testee.test(root), is(true)); + } + + @Test + public void shouldNotMatchRootsWithNonMatchingNames() { + final ClassPathRoot root = new DirectoryClassPathRoot(new File("/foo/bar/")); + this.testee = new PathNamePredicate(Prelude.isEqualTo("phoee")); + assertFalse(this.testee.test(root)); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/config/PluginServicesTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/config/PluginServicesTest.java index 469a62178..8e4ea922e 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/config/PluginServicesTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/config/PluginServicesTest.java @@ -1,39 +1,39 @@ -package org.pitest.mutationtest.config; - -import static org.junit.Assert.assertTrue; - -import java.util.function.Predicate; - -import org.junit.Test; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; -import org.pitest.mutationtest.filter.LimitNumberOfMutationsPerClassFilterFactory; -import org.pitest.mutationtest.report.csv.CSVReportFactory; - -public class PluginServicesTest { - - private final PluginServices testee = PluginServices.makeForContextLoader(); - - @Test - public void shouldListDefaultEngineAsClientClasspathPlugin() { - assertTrue(FCollection.contains(this.testee.findClientClasspathPlugins(), - theClass(GregorEngineFactory.class))); - } - - @Test - public void shouldListCSVReportAsToolClasspathPlugin() { - assertTrue(FCollection.contains(this.testee.findToolClasspathPlugins(), - theClass(CSVReportFactory.class))); - } - - @Test - public void shouldListDefaultMutationFilterAsToolClasspathPlugin() { - assertTrue(FCollection.contains(this.testee.findToolClasspathPlugins(), - theClass(LimitNumberOfMutationsPerClassFilterFactory.class))); - } - - private static Predicate theClass(final Class clss) { - return a -> a.getClass().equals(clss); - } - -} +package org.pitest.mutationtest.config; + +import static org.junit.Assert.assertTrue; + +import java.util.function.Predicate; + +import org.junit.Test; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; +import org.pitest.mutationtest.filter.LimitNumberOfMutationsPerClassFilterFactory; +import org.pitest.mutationtest.report.csv.CSVReportFactory; + +public class PluginServicesTest { + + private final PluginServices testee = PluginServices.makeForContextLoader(); + + @Test + public void shouldListDefaultEngineAsClientClasspathPlugin() { + assertTrue(FCollection.contains(this.testee.findClientClasspathPlugins(), + theClass(GregorEngineFactory.class))); + } + + @Test + public void shouldListCSVReportAsToolClasspathPlugin() { + assertTrue(FCollection.contains(this.testee.findToolClasspathPlugins(), + theClass(CSVReportFactory.class))); + } + + @Test + public void shouldListDefaultMutationFilterAsToolClasspathPlugin() { + assertTrue(FCollection.contains(this.testee.findToolClasspathPlugins(), + theClass(LimitNumberOfMutationsPerClassFilterFactory.class))); + } + + private static Predicate theClass(final Class clss) { + return a -> a.getClass().equals(clss); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/config/ReportOptionsTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/config/ReportOptionsTest.java index e16fd7484..d755c2943 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/config/ReportOptionsTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/config/ReportOptionsTest.java @@ -1,35 +1,35 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.config; - -import static org.junit.Assert.assertFalse; - -import org.junit.Before; -import org.junit.Test; - -public class ReportOptionsTest { - private ReportOptions testee; - - @Before - public void setUp() { - this.testee = new ReportOptions(); - } - - @Test - public void shouldDefaultToNoLineCoverageExport() { - assertFalse(this.testee.shouldExportLineCoverage()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.config; + +import static org.junit.Assert.assertFalse; + +import org.junit.Before; +import org.junit.Test; + +public class ReportOptionsTest { + private ReportOptions testee; + + @Before + public void setUp() { + this.testee = new ReportOptions(); + } + + @Test + public void shouldDefaultToNoLineCoverageExport() { + assertFalse(this.testee.shouldExportLineCoverage()); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/config/SettingsFactoryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/config/SettingsFactoryTest.java index 5756970f1..6be92b56d 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/config/SettingsFactoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/config/SettingsFactoryTest.java @@ -1,130 +1,130 @@ -package org.pitest.mutationtest.config; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.pitest.coverage.execute.CoverageOptions; -import org.pitest.coverage.export.NullCoverageExporter; -import org.pitest.functional.SideEffect1; -import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; -import org.pitest.plugin.Feature; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.util.PitError; - -public class SettingsFactoryTest { - - private final ReportOptions options = new ReportOptions(); - - private final PluginServices plugins = PluginServices.makeForContextLoader(); - - private SettingsFactory testee; - - @Before - public void setUp() { - this.testee = new SettingsFactory(this.options, this.plugins); - this.options.setGroupConfig(new TestGroupConfig()); - } - - @Test - public void shouldReturnANullCoverageExporterWhenOptionSetToFalse() { - this.options.setExportLineCoverage(false); - assertTrue(this.testee.createCoverageExporter() instanceof NullCoverageExporter); - } - - @Test - public void shouldReturnEngineWhenRequestedEngineIsKnown() { - assertTrue(this.testee.createEngine() instanceof GregorEngineFactory); - } - - @Test(expected = PitError.class) - public void shouldThrowErrorWhenRequestedEngineNotKnown() { - this.options.setMutationEngine("unknown"); - this.testee.createEngine(); - } - - @Test - public void shouldReturnListenerWhenRequestedListenerIsKnown() { - this.options.addOutputFormats(Arrays.asList("XML")); - assertNotNull(this.testee.createListener()); - } - - @Test - public void shouldSupportXMLAndCSV() { - this.options.addOutputFormats(Arrays.asList("CSV", "XML")); - assertNotNull(this.testee.createListener()); - } - - @Test(expected = PitError.class) - public void shouldThrowErrorWhenRequestedListenerNotKnown() { - this.options.addOutputFormats(Arrays.asList("unknown")); - this.testee.createListener(); - } - - @Test - public void shouldReturnADefaultJavaExecutableWhenNoneIsSpecified() { - this.options.setJavaExecutable(null); - File actual = new File(this.testee.getJavaExecutable().javaExecutable()); - if (System.getProperty("os.name").contains("Windows")) { - actual = new File(actual.getPath() + ".exe"); - } - assertTrue(actual.exists()); - } - - @Test - public void shouldReturnSpecifiedJavaExecutableWhenOneSet() { - this.options.setJavaExecutable("foo"); - assertEquals("foo", this.testee.getJavaExecutable().javaExecutable()); - } - - @Test - public void shouldNotAllowUserToCalculateCoverageForCoreClasses() { - this.options.setTargetClasses(Collections - .singleton("java/Integer")); - final CoverageOptions actual = this.testee.createCoverageOptions(); - assertFalse(actual.getFilter().test("java/Integer")); - } - - @Test - public void shouldNotAllowUserToCalculateCoverageForCoverageImplementation() { - this.options.setTargetClasses(Collections - .singleton("/org/pitest/coverage")); - final CoverageOptions actual = this.testee.createCoverageOptions(); - assertFalse(actual.getFilter().test("org/pitest/coverage")); - } - - @Test - public void shouldDescribeActiveFeatures() { - final SideEffect1 disabled = Mockito.mock(SideEffect1.class); - final SideEffect1 enabled = Mockito.mock(SideEffect1.class); - - this.options.setFeatures(Arrays.asList("+FSTATINIT")); - - this.testee.describeFeatures(enabled, disabled); - verify(enabled).apply(Feature.named("FSTATINIT")); - verify(disabled, never()).apply(Feature.named("FSTATINIT")); - } - - @Test - public void shouldDescribeDisabledFeatures() { - final SideEffect1 disabled = Mockito.mock(SideEffect1.class); - final SideEffect1 enabled = Mockito.mock(SideEffect1.class); - - this.options.setFeatures(Arrays.asList("-FSTATINIT")); - - this.testee.describeFeatures(enabled, disabled); - verify(enabled, never()).apply(Feature.named("FSTATINIT")); - verify(disabled).apply(Feature.named("FSTATINIT")); - } - -} +package org.pitest.mutationtest.config; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.pitest.coverage.execute.CoverageOptions; +import org.pitest.coverage.export.NullCoverageExporter; +import org.pitest.functional.SideEffect1; +import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; +import org.pitest.plugin.Feature; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.util.PitError; + +public class SettingsFactoryTest { + + private final ReportOptions options = new ReportOptions(); + + private final PluginServices plugins = PluginServices.makeForContextLoader(); + + private SettingsFactory testee; + + @Before + public void setUp() { + this.testee = new SettingsFactory(this.options, this.plugins); + this.options.setGroupConfig(new TestGroupConfig()); + } + + @Test + public void shouldReturnANullCoverageExporterWhenOptionSetToFalse() { + this.options.setExportLineCoverage(false); + assertTrue(this.testee.createCoverageExporter() instanceof NullCoverageExporter); + } + + @Test + public void shouldReturnEngineWhenRequestedEngineIsKnown() { + assertTrue(this.testee.createEngine() instanceof GregorEngineFactory); + } + + @Test(expected = PitError.class) + public void shouldThrowErrorWhenRequestedEngineNotKnown() { + this.options.setMutationEngine("unknown"); + this.testee.createEngine(); + } + + @Test + public void shouldReturnListenerWhenRequestedListenerIsKnown() { + this.options.addOutputFormats(Arrays.asList("XML")); + assertNotNull(this.testee.createListener()); + } + + @Test + public void shouldSupportXMLAndCSV() { + this.options.addOutputFormats(Arrays.asList("CSV", "XML")); + assertNotNull(this.testee.createListener()); + } + + @Test(expected = PitError.class) + public void shouldThrowErrorWhenRequestedListenerNotKnown() { + this.options.addOutputFormats(Arrays.asList("unknown")); + this.testee.createListener(); + } + + @Test + public void shouldReturnADefaultJavaExecutableWhenNoneIsSpecified() { + this.options.setJavaExecutable(null); + File actual = new File(this.testee.getJavaExecutable().javaExecutable()); + if (System.getProperty("os.name").contains("Windows")) { + actual = new File(actual.getPath() + ".exe"); + } + assertTrue(actual.exists()); + } + + @Test + public void shouldReturnSpecifiedJavaExecutableWhenOneSet() { + this.options.setJavaExecutable("foo"); + assertEquals("foo", this.testee.getJavaExecutable().javaExecutable()); + } + + @Test + public void shouldNotAllowUserToCalculateCoverageForCoreClasses() { + this.options.setTargetClasses(Collections + .singleton("java/Integer")); + final CoverageOptions actual = this.testee.createCoverageOptions(); + assertFalse(actual.getFilter().test("java/Integer")); + } + + @Test + public void shouldNotAllowUserToCalculateCoverageForCoverageImplementation() { + this.options.setTargetClasses(Collections + .singleton("/org/pitest/coverage")); + final CoverageOptions actual = this.testee.createCoverageOptions(); + assertFalse(actual.getFilter().test("org/pitest/coverage")); + } + + @Test + public void shouldDescribeActiveFeatures() { + final SideEffect1 disabled = Mockito.mock(SideEffect1.class); + final SideEffect1 enabled = Mockito.mock(SideEffect1.class); + + this.options.setFeatures(Arrays.asList("+FSTATINIT")); + + this.testee.describeFeatures(enabled, disabled); + verify(enabled).apply(Feature.named("FSTATINIT")); + verify(disabled, never()).apply(Feature.named("FSTATINIT")); + } + + @Test + public void shouldDescribeDisabledFeatures() { + final SideEffect1 disabled = Mockito.mock(SideEffect1.class); + final SideEffect1 enabled = Mockito.mock(SideEffect1.class); + + this.options.setFeatures(Arrays.asList("-FSTATINIT")); + + this.testee.describeFeatures(enabled, disabled); + verify(enabled, never()).apply(Feature.named("FSTATINIT")); + verify(disabled).apply(Feature.named("FSTATINIT")); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/filter/LimitNumberOfMutationPerClassFilterTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/filter/LimitNumberOfMutationPerClassFilterTest.java index 25ace32e9..17203ac90 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/filter/LimitNumberOfMutationPerClassFilterTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/filter/LimitNumberOfMutationPerClassFilterTest.java @@ -1,81 +1,81 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.filter; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public class LimitNumberOfMutationPerClassFilterTest { - - private LimitNumberOfMutationPerClassFilter testee; - private Mutater unused; - - @Before - public void setUp() { - this.testee = new LimitNumberOfMutationPerClassFilter(3); - } - - @Test - public void shouldReturnUnalteredCollectionIfCollectionContainsLessThenMaxMutations() { - final Collection expected = make(1, 2); - assertSame(expected, this.testee.intercept(expected, this.unused)); - } - - @Test - public void shouldReturnUnalteredCollectionIfCollectionContainsExactlyMaxMutations() { - final Collection expected = make(1, 2, 3); - assertSame(expected, this.testee.intercept(expected, this.unused)); - } - - @Test - public void shouldTrimCollectionToMaximumAllowedNumber() { - final Collection input = make(1, 2, 3, 4); - assertEquals(make(1, 2, 3), this.testee.intercept(input, this.unused)); - } - - @Test - public void shouldUseEvenDistributionOfMutations() { - final Collection input = make(1, 2, 3, 4, 5, 6, 7, 8); - assertEquals(make(2, 4, 6), this.testee.intercept(input, this.unused)); - } - - private Collection make(final Integer... ids) { - final List ms = new ArrayList<>(); - for (final int each : ids) { - ms.add(makeMutation(each)); - } - return ms; - } - - private MutationDetails makeMutation(final int id) { - return new MutationDetails(makeId(id), "", "", 0, 0); - } - - private MutationIdentifier makeId(final int id) { - return aMutationId().withIndex(id).build(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.filter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; + +public class LimitNumberOfMutationPerClassFilterTest { + + private LimitNumberOfMutationPerClassFilter testee; + private Mutater unused; + + @Before + public void setUp() { + this.testee = new LimitNumberOfMutationPerClassFilter(3); + } + + @Test + public void shouldReturnUnalteredCollectionIfCollectionContainsLessThenMaxMutations() { + final Collection expected = make(1, 2); + assertSame(expected, this.testee.intercept(expected, this.unused)); + } + + @Test + public void shouldReturnUnalteredCollectionIfCollectionContainsExactlyMaxMutations() { + final Collection expected = make(1, 2, 3); + assertSame(expected, this.testee.intercept(expected, this.unused)); + } + + @Test + public void shouldTrimCollectionToMaximumAllowedNumber() { + final Collection input = make(1, 2, 3, 4); + assertEquals(make(1, 2, 3), this.testee.intercept(input, this.unused)); + } + + @Test + public void shouldUseEvenDistributionOfMutations() { + final Collection input = make(1, 2, 3, 4, 5, 6, 7, 8); + assertEquals(make(2, 4, 6), this.testee.intercept(input, this.unused)); + } + + private Collection make(final Integer... ids) { + final List ms = new ArrayList<>(); + for (final int each : ids) { + ms.add(makeMutation(each)); + } + return ms; + } + + private MutationDetails makeMutation(final int id) { + return new MutationDetails(makeId(id), "", "", 0, 0); + } + + private MutationIdentifier makeId(final int id) { + return aMutationId().withIndex(id).build(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/filter/LimitNumberOfMutationsPerClassFilterFactoryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/filter/LimitNumberOfMutationsPerClassFilterFactoryTest.java index 5f5ae7623..f1f46083c 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/filter/LimitNumberOfMutationsPerClassFilterFactoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/filter/LimitNumberOfMutationsPerClassFilterFactoryTest.java @@ -1,16 +1,16 @@ -package org.pitest.mutationtest.filter; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -public class LimitNumberOfMutationsPerClassFilterFactoryTest { - - private final LimitNumberOfMutationsPerClassFilterFactory testee = new LimitNumberOfMutationsPerClassFilterFactory(); - - @Test - public void shouldBeOffByDefault() { - assertThat(this.testee.provides().isOnByDefault()).isFalse(); - } - -} +package org.pitest.mutationtest.filter; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class LimitNumberOfMutationsPerClassFilterFactoryTest { + + private final LimitNumberOfMutationsPerClassFilterFactory testee = new LimitNumberOfMutationsPerClassFilterFactory(); + + @Test + public void shouldBeOffByDefault() { + assertThat(this.testee.provides().isOnByDefault()).isFalse(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/DefaultCodeHistoryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/DefaultCodeHistoryTest.java index c1298b78b..4b53f0b35 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/DefaultCodeHistoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/DefaultCodeHistoryTest.java @@ -1,131 +1,131 @@ -package org.pitest.mutationtest.incremental; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassIdentifier; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassInfoMother; -import org.pitest.classinfo.ClassInfoSource; -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.HierarchicalClassId; -import java.util.Optional; -import org.pitest.mutationtest.ClassHistory; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public class DefaultCodeHistoryTest { - - private DefaultCodeHistory testee; - - @Mock - private ClassInfoSource classInfoSource; - - private final Map historicClassPath = new HashMap<>(); - - private final Map results = new HashMap<>(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new DefaultCodeHistory(this.classInfoSource, this.results, - this.historicClassPath); - } - - @Test - public void shouldReturnNoneWhenNoMatchingHistoricResultExists() { - final MutationIdentifier id = aMutationId().build(); - final Optional actual = this.testee - .getPreviousResult(id); - assertEquals(Optional.empty(), actual); - } - - @Test - public void shouldReturnHistoricResultWhenOneExists() { - final MutationIdentifier id = aMutationId().build(); - final MutationStatusTestPair expected = new MutationStatusTestPair(0, - DetectionStatus.KILLED, "foo"); - this.results.put(id, expected); - final Optional actual = this.testee - .getPreviousResult(id); - assertEquals(Optional.ofNullable(expected), actual); - } - - @Test - public void shouldTreatNewClassAsChanged() { - assertTrue(this.testee - .hasClassChanged(ClassName.fromString("notInLastRun"))); - } - - @Test - public void shouldTreatClassesWithDifferentHashesAsChanged() { - final long currentHash = 42; - final ClassName foo = ClassName.fromString("foo"); - final ClassIdentifier currentId = new ClassIdentifier(currentHash, foo); - setCurrentClassPath(ClassInfoMother.make(currentId)); - this.historicClassPath.put(foo, makeHistory(new HierarchicalClassId( - currentHash + 1, foo, "0"))); - assertTrue(this.testee.hasClassChanged(ClassName.fromString("foo"))); - } - - @Test - public void shouldTreatClassesWithModifiedParentAsChanged() { - final long currentHash = 42; - final ClassName foo = ClassName.fromString("foo"); - - final ClassInfo parent = ClassInfoMother.make("parent"); - final ClassIdentifier currentId = new ClassIdentifier(currentHash, foo); - final ClassInfo currentFoo = ClassInfoMother.make(currentId, parent); - - final ClassInfo modifiedParent = ClassInfoMother.make(new ClassIdentifier( - parent.getHash().longValue() + 1, ClassName.fromString("parent"))); - final ClassInfo modifiedFoo = ClassInfoMother.make(currentId, - modifiedParent); - - setCurrentClassPath(currentFoo); - - this.historicClassPath.put(foo, makeHistory(modifiedFoo)); - - assertTrue(this.testee.hasClassChanged(foo)); - } - - @Test - public void shouldTreatClassesWithSameHashAsUnChanged() { - final ClassName foo = ClassName.fromString("foo"); - final HierarchicalClassId currentId = new HierarchicalClassId(0, foo, "0"); - setCurrentClassPath(currentId); - this.historicClassPath.put(foo, makeHistory(currentId)); - assertFalse(this.testee.hasClassChanged(ClassName.fromString("foo"))); - } - - private void setCurrentClassPath(final HierarchicalClassId currentId) { - final ClassInfo currentClass = ClassInfoMother.make(currentId.getId()); - when(this.classInfoSource.fetchClass(ClassName.fromString("foo"))) - .thenReturn(Optional.ofNullable(currentClass)); - } - - private void setCurrentClassPath(final ClassInfo info) { - when(this.classInfoSource.fetchClass(ClassName.fromString("foo"))) - .thenReturn(Optional.ofNullable(info)); - } - - private ClassHistory makeHistory(final HierarchicalClassId id) { - return new ClassHistory(id, ""); - } - - private ClassHistory makeHistory(final ClassInfo ci) { - return makeHistory(ci.getHierarchicalId()); - } - -} +package org.pitest.mutationtest.incremental; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassIdentifier; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassInfoMother; +import org.pitest.classinfo.ClassInfoSource; +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.HierarchicalClassId; +import java.util.Optional; +import org.pitest.mutationtest.ClassHistory; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationIdentifier; + +public class DefaultCodeHistoryTest { + + private DefaultCodeHistory testee; + + @Mock + private ClassInfoSource classInfoSource; + + private final Map historicClassPath = new HashMap<>(); + + private final Map results = new HashMap<>(); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new DefaultCodeHistory(this.classInfoSource, this.results, + this.historicClassPath); + } + + @Test + public void shouldReturnNoneWhenNoMatchingHistoricResultExists() { + final MutationIdentifier id = aMutationId().build(); + final Optional actual = this.testee + .getPreviousResult(id); + assertEquals(Optional.empty(), actual); + } + + @Test + public void shouldReturnHistoricResultWhenOneExists() { + final MutationIdentifier id = aMutationId().build(); + final MutationStatusTestPair expected = new MutationStatusTestPair(0, + DetectionStatus.KILLED, "foo"); + this.results.put(id, expected); + final Optional actual = this.testee + .getPreviousResult(id); + assertEquals(Optional.ofNullable(expected), actual); + } + + @Test + public void shouldTreatNewClassAsChanged() { + assertTrue(this.testee + .hasClassChanged(ClassName.fromString("notInLastRun"))); + } + + @Test + public void shouldTreatClassesWithDifferentHashesAsChanged() { + final long currentHash = 42; + final ClassName foo = ClassName.fromString("foo"); + final ClassIdentifier currentId = new ClassIdentifier(currentHash, foo); + setCurrentClassPath(ClassInfoMother.make(currentId)); + this.historicClassPath.put(foo, makeHistory(new HierarchicalClassId( + currentHash + 1, foo, "0"))); + assertTrue(this.testee.hasClassChanged(ClassName.fromString("foo"))); + } + + @Test + public void shouldTreatClassesWithModifiedParentAsChanged() { + final long currentHash = 42; + final ClassName foo = ClassName.fromString("foo"); + + final ClassInfo parent = ClassInfoMother.make("parent"); + final ClassIdentifier currentId = new ClassIdentifier(currentHash, foo); + final ClassInfo currentFoo = ClassInfoMother.make(currentId, parent); + + final ClassInfo modifiedParent = ClassInfoMother.make(new ClassIdentifier( + parent.getHash().longValue() + 1, ClassName.fromString("parent"))); + final ClassInfo modifiedFoo = ClassInfoMother.make(currentId, + modifiedParent); + + setCurrentClassPath(currentFoo); + + this.historicClassPath.put(foo, makeHistory(modifiedFoo)); + + assertTrue(this.testee.hasClassChanged(foo)); + } + + @Test + public void shouldTreatClassesWithSameHashAsUnChanged() { + final ClassName foo = ClassName.fromString("foo"); + final HierarchicalClassId currentId = new HierarchicalClassId(0, foo, "0"); + setCurrentClassPath(currentId); + this.historicClassPath.put(foo, makeHistory(currentId)); + assertFalse(this.testee.hasClassChanged(ClassName.fromString("foo"))); + } + + private void setCurrentClassPath(final HierarchicalClassId currentId) { + final ClassInfo currentClass = ClassInfoMother.make(currentId.getId()); + when(this.classInfoSource.fetchClass(ClassName.fromString("foo"))) + .thenReturn(Optional.ofNullable(currentClass)); + } + + private void setCurrentClassPath(final ClassInfo info) { + when(this.classInfoSource.fetchClass(ClassName.fromString("foo"))) + .thenReturn(Optional.ofNullable(info)); + } + + private ClassHistory makeHistory(final HierarchicalClassId id) { + return new ClassHistory(id, ""); + } + + private ClassHistory makeHistory(final ClassInfo ci) { + return makeHistory(ci.getHierarchicalId()); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/FileWriterFactoryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/FileWriterFactoryTest.java index 44c728b94..0be6da587 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/FileWriterFactoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/FileWriterFactoryTest.java @@ -1,64 +1,64 @@ -package org.pitest.mutationtest.incremental; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.PrintWriter; - -import org.hamcrest.Matcher; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.pitest.util.FileUtil; -import org.pitest.util.PitError; - -public class FileWriterFactoryTest { - - @Rule - public TemporaryFolder testFolder = new TemporaryFolder(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void writeToFile() throws IOException { - final File file = this.testFolder.newFile(); - final FileWriterFactory writerFactory = new FileWriterFactory(file); - final PrintWriter writer = writerFactory.create(); - writer.write("test"); - writerFactory.close(); - - final String content = FileUtil.readToString(new FileInputStream(file)); - assertThat(content, equalTo("test")); - } - - @Test - public void writeToFolder() throws IOException { - this.thrown.expect(PitError.class); - final Matcher causedBy = instanceOf(IOException.class); - this.thrown.expectCause(causedBy); - - final File folder = this.testFolder.newFolder(); - final FileWriterFactory writerFactory = new FileWriterFactory(folder); - writerFactory.create(); - } - - @Test - public void writeToFileWithinFolder() throws IOException { - final File folder = this.testFolder.newFolder(); - final File file = new File(folder, "subfolder/file"); - final FileWriterFactory writerFactory = new FileWriterFactory(file); - final PrintWriter writer = writerFactory.create(); - writer.write("test"); - writerFactory.close(); - - final String content = FileUtil.readToString(new FileInputStream(file)); - assertThat(content, equalTo("test")); - } - -} +package org.pitest.mutationtest.incremental; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintWriter; + +import org.hamcrest.Matcher; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.pitest.util.FileUtil; +import org.pitest.util.PitError; + +public class FileWriterFactoryTest { + + @Rule + public TemporaryFolder testFolder = new TemporaryFolder(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void writeToFile() throws IOException { + final File file = this.testFolder.newFile(); + final FileWriterFactory writerFactory = new FileWriterFactory(file); + final PrintWriter writer = writerFactory.create(); + writer.write("test"); + writerFactory.close(); + + final String content = FileUtil.readToString(new FileInputStream(file)); + assertThat(content, equalTo("test")); + } + + @Test + public void writeToFolder() throws IOException { + this.thrown.expect(PitError.class); + final Matcher causedBy = instanceOf(IOException.class); + this.thrown.expectCause(causedBy); + + final File folder = this.testFolder.newFolder(); + final FileWriterFactory writerFactory = new FileWriterFactory(folder); + writerFactory.create(); + } + + @Test + public void writeToFileWithinFolder() throws IOException { + final File folder = this.testFolder.newFolder(); + final File file = new File(folder, "subfolder/file"); + final FileWriterFactory writerFactory = new FileWriterFactory(file); + final PrintWriter writer = writerFactory.create(); + writer.write("test"); + writerFactory.close(); + + final String content = FileUtil.readToString(new FileInputStream(file)); + assertThat(content, equalTo("test")); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/HistoryListenerTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/HistoryListenerTest.java index 0a60c4cd2..5299f27a3 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/HistoryListenerTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/HistoryListenerTest.java @@ -1,45 +1,45 @@ -package org.pitest.mutationtest.incremental; - -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.report.MutationTestResultMother; - -public class HistoryListenerTest { - - private HistoryListener testee; - - @Mock - private HistoryStore store; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new HistoryListener(this.store); - } - - @Test - public void shouldRecordMutationResults() { - final MutationResult mr = makeResult(); - final ClassMutationResults metaData = MutationTestResultMother - .createClassResults(mr); - this.testee.handleMutationResult(metaData); - verify(this.store).recordResult(mr); - } - - private MutationResult makeResult() { - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails(), new MutationStatusTestPair(0, - DetectionStatus.KILLED)); - return mr; - } - -} +package org.pitest.mutationtest.incremental; + +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.report.MutationTestResultMother; + +public class HistoryListenerTest { + + private HistoryListener testee; + + @Mock + private HistoryStore store; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new HistoryListener(this.store); + } + + @Test + public void shouldRecordMutationResults() { + final MutationResult mr = makeResult(); + final ClassMutationResults metaData = MutationTestResultMother + .createClassResults(mr); + this.testee.handleMutationResult(metaData); + verify(this.store).recordResult(mr); + } + + private MutationResult makeResult() { + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails(), new MutationStatusTestPair(0, + DetectionStatus.KILLED)); + return mr; + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/IncrementalAnalyserTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/IncrementalAnalyserTest.java index f1f1c3f3e..712ca8555 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/IncrementalAnalyserTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/IncrementalAnalyserTest.java @@ -1,159 +1,159 @@ -package org.pitest.mutationtest.incremental; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; -import static org.pitest.mutationtest.LocationMother.aLocation; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.math.BigInteger; -import java.util.Collection; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.coverage.TestInfo; -import java.util.Optional; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public class IncrementalAnalyserTest { - - private IncrementalAnalyser testee; - - @Mock - private CodeHistory history; - - @Mock - private CoverageDatabase coverage; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new IncrementalAnalyser(this.history, this.coverage); - } - - @Test - public void shouldStartNewMutationsAtAStatusOfNotStarted() { - final MutationDetails md = makeMutation("foo"); - when(this.history.getPreviousResult(any(MutationIdentifier.class))) - .thenReturn(Optional. empty()); - - final Collection actual = this.testee.analyse(Collections - .singletonList(md)); - - assertEquals(DetectionStatus.NOT_STARTED, actual.iterator().next() - .getStatus()); - } - - @Test - public void shouldStartPreviousSurvivedMutationsAtAStatusOfNotStartedWhenCoverageHasChanged() { - final MutationDetails md = makeMutation("foo"); - setHistoryForAllMutationsTo(DetectionStatus.SURVIVED); - when( - this.history.hasCoverageChanged(any(ClassName.class), - any(BigInteger.class))).thenReturn(true); - final Collection actual = this.testee.analyse(Collections - .singletonList(md)); - assertEquals(DetectionStatus.NOT_STARTED, actual.iterator().next() - .getStatus()); - } - - @Test - public void shouldStartPreviousSurvivedMutationsAtAStatusOfSurvivedWhenCoverageHasNotChanged() { - final MutationDetails md = makeMutation("foo"); - setHistoryForAllMutationsTo(DetectionStatus.SURVIVED); - when( - this.history.hasCoverageChanged(any(ClassName.class), - any(BigInteger.class))).thenReturn(false); - final Collection actual = this.testee.analyse(Collections - .singletonList(md)); - assertEquals(DetectionStatus.SURVIVED, actual.iterator().next().getStatus()); - } - - @Test - public void shouldStartPreviousTimedOutMutationsAtAStatusOfNotStartedWhenClassHasChanged() { - final MutationDetails md = makeMutation("foo"); - setHistoryForAllMutationsTo(DetectionStatus.TIMED_OUT); - when(this.history.hasClassChanged(any(ClassName.class))).thenReturn(true); - final Collection actual = this.testee.analyse(Collections - .singletonList(md)); - - assertEquals(DetectionStatus.NOT_STARTED, actual.iterator().next() - .getStatus()); - } - - @Test - public void shouldStartPreviousTimedOutMutationsAtAStatusOfTimedOutWhenClassHasNotChanged() { - final MutationDetails md = makeMutation("foo"); - setHistoryForAllMutationsTo(DetectionStatus.TIMED_OUT); - when(this.history.hasClassChanged(any(ClassName.class))).thenReturn(false); - final Collection actual = this.testee.analyse(Collections - .singletonList(md)); - - assertEquals(DetectionStatus.TIMED_OUT, actual.iterator().next() - .getStatus()); - } - - @Test - public void shouldStartPreviousKilledMutationsAtAStatusOfNotStartedWhenNeitherClassOrTestHasChanged() { - final MutationDetails md = makeMutation("foo"); - final String killingTest = "fooTest"; - setHistoryForAllMutationsTo(DetectionStatus.KILLED, killingTest); - - final Collection tests = Collections.singleton(new TestInfo( - "TEST_CLASS", killingTest, 0, Optional. empty(), 0)); - when(this.coverage.getTestsForClass(any(ClassName.class))) - .thenReturn(tests); - when(this.history.hasClassChanged(any(ClassName.class))).thenReturn(false); - final MutationResult actual = this.testee - .analyse(Collections.singletonList(md)).iterator().next(); - - assertEquals(DetectionStatus.KILLED, actual.getStatus()); - assertEquals(Optional.ofNullable(killingTest), actual.getKillingTest()); - } - - @Test - public void shouldStartPreviousKilledMutationsAtAStatusOfKilledWhenNeitherClassOrTestHasChanged() { - final MutationDetails md = makeMutation("foo"); - final String killingTest = "fooTest"; - setHistoryForAllMutationsTo(DetectionStatus.KILLED, killingTest); - - final Collection tests = Collections.singleton(new TestInfo( - "TEST_CLASS", killingTest, 0, Optional. empty(), 0)); - when(this.coverage.getTestsForClass(any(ClassName.class))) - .thenReturn(tests); - when(this.history.hasClassChanged(ClassName.fromString("foo"))).thenReturn( - false); - when(this.history.hasClassChanged(ClassName.fromString("TEST_CLASS"))) - .thenReturn(true); - final MutationResult actual = this.testee - .analyse(Collections.singletonList(md)).iterator().next(); - - assertEquals(DetectionStatus.NOT_STARTED, actual.getStatus()); - } - - private MutationDetails makeMutation(final String method) { - final MutationIdentifier id = aMutationId().withLocation( - aLocation().withMethod(method)).build(); - return new MutationDetails(id, "file", "desc", 1, 2); - } - - private void setHistoryForAllMutationsTo(final DetectionStatus status) { - setHistoryForAllMutationsTo(status, "bar"); - } - - private void setHistoryForAllMutationsTo(final DetectionStatus status, - final String test) { - when(this.history.getPreviousResult(any(MutationIdentifier.class))) - .thenReturn(Optional.ofNullable(new MutationStatusTestPair(0, status, test))); - } - -} +package org.pitest.mutationtest.incremental; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +import static org.pitest.mutationtest.LocationMother.aLocation; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.math.BigInteger; +import java.util.Collection; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.coverage.TestInfo; +import java.util.Optional; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; + +public class IncrementalAnalyserTest { + + private IncrementalAnalyser testee; + + @Mock + private CodeHistory history; + + @Mock + private CoverageDatabase coverage; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new IncrementalAnalyser(this.history, this.coverage); + } + + @Test + public void shouldStartNewMutationsAtAStatusOfNotStarted() { + final MutationDetails md = makeMutation("foo"); + when(this.history.getPreviousResult(any(MutationIdentifier.class))) + .thenReturn(Optional. empty()); + + final Collection actual = this.testee.analyse(Collections + .singletonList(md)); + + assertEquals(DetectionStatus.NOT_STARTED, actual.iterator().next() + .getStatus()); + } + + @Test + public void shouldStartPreviousSurvivedMutationsAtAStatusOfNotStartedWhenCoverageHasChanged() { + final MutationDetails md = makeMutation("foo"); + setHistoryForAllMutationsTo(DetectionStatus.SURVIVED); + when( + this.history.hasCoverageChanged(any(ClassName.class), + any(BigInteger.class))).thenReturn(true); + final Collection actual = this.testee.analyse(Collections + .singletonList(md)); + assertEquals(DetectionStatus.NOT_STARTED, actual.iterator().next() + .getStatus()); + } + + @Test + public void shouldStartPreviousSurvivedMutationsAtAStatusOfSurvivedWhenCoverageHasNotChanged() { + final MutationDetails md = makeMutation("foo"); + setHistoryForAllMutationsTo(DetectionStatus.SURVIVED); + when( + this.history.hasCoverageChanged(any(ClassName.class), + any(BigInteger.class))).thenReturn(false); + final Collection actual = this.testee.analyse(Collections + .singletonList(md)); + assertEquals(DetectionStatus.SURVIVED, actual.iterator().next().getStatus()); + } + + @Test + public void shouldStartPreviousTimedOutMutationsAtAStatusOfNotStartedWhenClassHasChanged() { + final MutationDetails md = makeMutation("foo"); + setHistoryForAllMutationsTo(DetectionStatus.TIMED_OUT); + when(this.history.hasClassChanged(any(ClassName.class))).thenReturn(true); + final Collection actual = this.testee.analyse(Collections + .singletonList(md)); + + assertEquals(DetectionStatus.NOT_STARTED, actual.iterator().next() + .getStatus()); + } + + @Test + public void shouldStartPreviousTimedOutMutationsAtAStatusOfTimedOutWhenClassHasNotChanged() { + final MutationDetails md = makeMutation("foo"); + setHistoryForAllMutationsTo(DetectionStatus.TIMED_OUT); + when(this.history.hasClassChanged(any(ClassName.class))).thenReturn(false); + final Collection actual = this.testee.analyse(Collections + .singletonList(md)); + + assertEquals(DetectionStatus.TIMED_OUT, actual.iterator().next() + .getStatus()); + } + + @Test + public void shouldStartPreviousKilledMutationsAtAStatusOfNotStartedWhenNeitherClassOrTestHasChanged() { + final MutationDetails md = makeMutation("foo"); + final String killingTest = "fooTest"; + setHistoryForAllMutationsTo(DetectionStatus.KILLED, killingTest); + + final Collection tests = Collections.singleton(new TestInfo( + "TEST_CLASS", killingTest, 0, Optional. empty(), 0)); + when(this.coverage.getTestsForClass(any(ClassName.class))) + .thenReturn(tests); + when(this.history.hasClassChanged(any(ClassName.class))).thenReturn(false); + final MutationResult actual = this.testee + .analyse(Collections.singletonList(md)).iterator().next(); + + assertEquals(DetectionStatus.KILLED, actual.getStatus()); + assertEquals(Optional.ofNullable(killingTest), actual.getKillingTest()); + } + + @Test + public void shouldStartPreviousKilledMutationsAtAStatusOfKilledWhenNeitherClassOrTestHasChanged() { + final MutationDetails md = makeMutation("foo"); + final String killingTest = "fooTest"; + setHistoryForAllMutationsTo(DetectionStatus.KILLED, killingTest); + + final Collection tests = Collections.singleton(new TestInfo( + "TEST_CLASS", killingTest, 0, Optional. empty(), 0)); + when(this.coverage.getTestsForClass(any(ClassName.class))) + .thenReturn(tests); + when(this.history.hasClassChanged(ClassName.fromString("foo"))).thenReturn( + false); + when(this.history.hasClassChanged(ClassName.fromString("TEST_CLASS"))) + .thenReturn(true); + final MutationResult actual = this.testee + .analyse(Collections.singletonList(md)).iterator().next(); + + assertEquals(DetectionStatus.NOT_STARTED, actual.getStatus()); + } + + private MutationDetails makeMutation(final String method) { + final MutationIdentifier id = aMutationId().withLocation( + aLocation().withMethod(method)).build(); + return new MutationDetails(id, "file", "desc", 1, 2); + } + + private void setHistoryForAllMutationsTo(final DetectionStatus status) { + setHistoryForAllMutationsTo(status, "bar"); + } + + private void setHistoryForAllMutationsTo(final DetectionStatus status, + final String test) { + when(this.history.getPreviousResult(any(MutationIdentifier.class))) + .thenReturn(Optional.ofNullable(new MutationStatusTestPair(0, status, test))); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullHistoryStore.java b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullHistoryStore.java index 83b3a265a..617c6303e 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullHistoryStore.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullHistoryStore.java @@ -1,44 +1,44 @@ -package org.pitest.mutationtest.incremental; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.HierarchicalClassId; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.mutationtest.ClassHistory; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public class NullHistoryStore implements HistoryStore { - - @Override - public void initialize() { - - } - - @Override - public void recordResult(final MutationResult result) { - - } - - @Override - public Map getHistoricResults() { - return Collections.emptyMap(); - } - - @Override - public Map getHistoricClassPath() { - return Collections.emptyMap(); - } - - @Override - public void recordClassPath(final Collection ids, - final CoverageDatabase coverageInfo) { - - } - -} +package org.pitest.mutationtest.incremental; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; + +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.HierarchicalClassId; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.mutationtest.ClassHistory; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationIdentifier; + +public class NullHistoryStore implements HistoryStore { + + @Override + public void initialize() { + + } + + @Override + public void recordResult(final MutationResult result) { + + } + + @Override + public Map getHistoricResults() { + return Collections.emptyMap(); + } + + @Override + public Map getHistoricClassPath() { + return Collections.emptyMap(); + } + + @Override + public void recordClassPath(final Collection ids, + final CoverageDatabase coverageInfo) { + + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullHistoryStoreTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullHistoryStoreTest.java index 4c3c47f55..93f58db5b 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullHistoryStoreTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullHistoryStoreTest.java @@ -1,21 +1,21 @@ -package org.pitest.mutationtest.incremental; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class NullHistoryStoreTest { - - private final NullHistoryStore testee = new NullHistoryStore(); - - @Test - public void shouldReturnEmptyClassPath() { - assertTrue(this.testee.getHistoricClassPath().isEmpty()); - } - - @Test - public void shouldReturnEmptyResults() { - assertTrue(this.testee.getHistoricResults().isEmpty()); - } - -} +package org.pitest.mutationtest.incremental; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class NullHistoryStoreTest { + + private final NullHistoryStore testee = new NullHistoryStore(); + + @Test + public void shouldReturnEmptyClassPath() { + assertTrue(this.testee.getHistoricClassPath().isEmpty()); + } + + @Test + public void shouldReturnEmptyResults() { + assertTrue(this.testee.getHistoricResults().isEmpty()); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullWriterFactoryTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullWriterFactoryTest.java index fa8e786fa..3162f5104 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullWriterFactoryTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/NullWriterFactoryTest.java @@ -1,14 +1,14 @@ -package org.pitest.mutationtest.incremental; - -import org.junit.Test; - -public class NullWriterFactoryTest { - - @Test - public void shouldCreateAUsableWriter() { - final NullWriterFactory testee = new NullWriterFactory(); - testee.create().println("foo"); - // pass - } - -} +package org.pitest.mutationtest.incremental; + +import org.junit.Test; + +public class NullWriterFactoryTest { + + @Test + public void shouldCreateAUsableWriter() { + final NullWriterFactory testee = new NullWriterFactory(); + testee.create().println("foo"); + // pass + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/ObjectOutputStreamHistoryStoreTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/ObjectOutputStreamHistoryStoreTest.java index 8ac52e045..50ed8dace 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/ObjectOutputStreamHistoryStoreTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/incremental/ObjectOutputStreamHistoryStoreTest.java @@ -1,151 +1,151 @@ -package org.pitest.mutationtest.incremental; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassIdentifier; -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.HierarchicalClassId; -import org.pitest.coverage.CoverageDatabase; -import java.util.Optional; -import org.pitest.mutationtest.ClassHistory; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.mutationtest.report.MutationTestResultMother; - -public class ObjectOutputStreamHistoryStoreTest { - - private static final String COV = BigInteger.TEN.toString(16); - - private ObjectOutputStreamHistoryStore testee; - - @Mock - private CoverageDatabase coverage; - - private final Writer output = new StringWriter(); - - private final WriterFactory writerFactory = new WriterFactory() { - - @Override - public PrintWriter create() { - return new PrintWriter( - ObjectOutputStreamHistoryStoreTest.this.output); - } - - @Override - public void close() { - - } - - }; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - when(this.coverage.getCoverageIdForClass(any(ClassName.class))).thenReturn( - BigInteger.TEN); - } - - @Test - public void shouldRecordAndRetrieveClassPath() { - final ClassHistory foo = new ClassHistory(new HierarchicalClassId( - new ClassIdentifier(0, ClassName.fromString("foo")), ""), COV); - final ClassHistory bar = new ClassHistory(new HierarchicalClassId( - new ClassIdentifier(0, ClassName.fromString("bar")), ""), COV); - - recordClassPathWithTestee(foo.getId(), bar.getId()); - - final Reader reader = new StringReader(this.output.toString()); - this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, - Optional.ofNullable(reader)); - this.testee.initialize(); - - final Map expected = new HashMap<>(); - expected.put(foo.getName(), foo); - expected.put(bar.getName(), bar); - assertEquals(expected, this.testee.getHistoricClassPath()); - } - - @Test - public void shouldRecordAndRetrieveResults() { - final HierarchicalClassId foo = new HierarchicalClassId( - new ClassIdentifier(0, ClassName.fromString("foo")), ""); - recordClassPathWithTestee(foo); - - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails("foo"), - new MutationStatusTestPair(1, DetectionStatus.KILLED, "testName")); - - this.testee.recordResult(mr); - - final Reader reader = new StringReader(this.output.toString()); - this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, - Optional.ofNullable(reader)); - this.testee.initialize(); - final Map expected = new HashMap<>(); - expected.put(mr.getDetails().getId(), mr.getStatusTestPair()); - assertEquals(expected, this.testee.getHistoricResults()); - } - - @Test - public void shouldNotAttemptToWriteToFileWhenNoneSupplied() { - try { - this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, - Optional. empty()); - this.testee.initialize(); - } catch (final Exception ex) { - fail(ex.getMessage()); - } - } - - @Test - public void shouldReadCorruptFiles() throws IOException { - final HierarchicalClassId foo = new HierarchicalClassId( - new ClassIdentifier(0, ClassName.fromString("foo")), ""); - recordClassPathWithTestee(foo); - - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails("foo"), - new MutationStatusTestPair(1, DetectionStatus.KILLED, "testName")); - - this.testee.recordResult(mr); - this.output.append("rubbish"); - - final Reader reader = new StringReader(this.output.toString()); - this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, - Optional.ofNullable(reader)); - this.testee.initialize(); - - assertFalse(this.testee.getHistoricResults().isEmpty()); - } - - private void recordClassPathWithTestee( - final HierarchicalClassId... classIdentifiers) { - this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, - Optional. empty()); - final Collection ids = Arrays.asList(classIdentifiers); - this.testee.recordClassPath(ids, this.coverage); - } - +package org.pitest.mutationtest.incremental; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassIdentifier; +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.HierarchicalClassId; +import org.pitest.coverage.CoverageDatabase; +import java.util.Optional; +import org.pitest.mutationtest.ClassHistory; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.mutationtest.report.MutationTestResultMother; + +public class ObjectOutputStreamHistoryStoreTest { + + private static final String COV = BigInteger.TEN.toString(16); + + private ObjectOutputStreamHistoryStore testee; + + @Mock + private CoverageDatabase coverage; + + private final Writer output = new StringWriter(); + + private final WriterFactory writerFactory = new WriterFactory() { + + @Override + public PrintWriter create() { + return new PrintWriter( + ObjectOutputStreamHistoryStoreTest.this.output); + } + + @Override + public void close() { + + } + + }; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + when(this.coverage.getCoverageIdForClass(any(ClassName.class))).thenReturn( + BigInteger.TEN); + } + + @Test + public void shouldRecordAndRetrieveClassPath() { + final ClassHistory foo = new ClassHistory(new HierarchicalClassId( + new ClassIdentifier(0, ClassName.fromString("foo")), ""), COV); + final ClassHistory bar = new ClassHistory(new HierarchicalClassId( + new ClassIdentifier(0, ClassName.fromString("bar")), ""), COV); + + recordClassPathWithTestee(foo.getId(), bar.getId()); + + final Reader reader = new StringReader(this.output.toString()); + this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, + Optional.ofNullable(reader)); + this.testee.initialize(); + + final Map expected = new HashMap<>(); + expected.put(foo.getName(), foo); + expected.put(bar.getName(), bar); + assertEquals(expected, this.testee.getHistoricClassPath()); + } + + @Test + public void shouldRecordAndRetrieveResults() { + final HierarchicalClassId foo = new HierarchicalClassId( + new ClassIdentifier(0, ClassName.fromString("foo")), ""); + recordClassPathWithTestee(foo); + + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails("foo"), + new MutationStatusTestPair(1, DetectionStatus.KILLED, "testName")); + + this.testee.recordResult(mr); + + final Reader reader = new StringReader(this.output.toString()); + this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, + Optional.ofNullable(reader)); + this.testee.initialize(); + final Map expected = new HashMap<>(); + expected.put(mr.getDetails().getId(), mr.getStatusTestPair()); + assertEquals(expected, this.testee.getHistoricResults()); + } + + @Test + public void shouldNotAttemptToWriteToFileWhenNoneSupplied() { + try { + this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, + Optional. empty()); + this.testee.initialize(); + } catch (final Exception ex) { + fail(ex.getMessage()); + } + } + + @Test + public void shouldReadCorruptFiles() throws IOException { + final HierarchicalClassId foo = new HierarchicalClassId( + new ClassIdentifier(0, ClassName.fromString("foo")), ""); + recordClassPathWithTestee(foo); + + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails("foo"), + new MutationStatusTestPair(1, DetectionStatus.KILLED, "testName")); + + this.testee.recordResult(mr); + this.output.append("rubbish"); + + final Reader reader = new StringReader(this.output.toString()); + this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, + Optional.ofNullable(reader)); + this.testee.initialize(); + + assertFalse(this.testee.getHistoricResults().isEmpty()); + } + + private void recordClassPathWithTestee( + final HierarchicalClassId... classIdentifiers) { + this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory, + Optional. empty()); + final Collection ids = Arrays.asList(classIdentifiers); + this.testee.recordClassPath(ids, this.coverage); + } + } \ No newline at end of file diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/report/MutationTestResultMother.java b/pitest-entry/src/test/java/org/pitest/mutationtest/report/MutationTestResultMother.java index 4d640341f..fea31ec0e 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/report/MutationTestResultMother.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/report/MutationTestResultMother.java @@ -1,45 +1,45 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report; - -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.Arrays; - -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationMetaData; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.engine.MutationDetails; - -public class MutationTestResultMother { - - public static MutationDetails createDetails() { - return createDetails("file"); - } - - public static MutationDetails createDetails(final String sourceFile) { - return new MutationDetails(aMutationId().build(), sourceFile, "desc", 42, 0); - } - - public static MutationMetaData createMetaData(final MutationResult... mrs) { - return new MutationMetaData(Arrays.asList(mrs)); - } - - public static ClassMutationResults createClassResults( - final MutationResult... mrs) { - return new ClassMutationResults(Arrays.asList(mrs)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report; + +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.Arrays; + +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationMetaData; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.engine.MutationDetails; + +public class MutationTestResultMother { + + public static MutationDetails createDetails() { + return createDetails("file"); + } + + public static MutationDetails createDetails(final String sourceFile) { + return new MutationDetails(aMutationId().build(), sourceFile, "desc", 42, 0); + } + + public static MutationMetaData createMetaData(final MutationResult... mrs) { + return new MutationMetaData(Arrays.asList(mrs)); + } + + public static ClassMutationResults createClassResults( + final MutationResult... mrs) { + return new ClassMutationResults(Arrays.asList(mrs)); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/report/csv/CSVReportListenerTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/report/csv/CSVReportListenerTest.java index a3b57c1d3..b8956ec75 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/report/csv/CSVReportListenerTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/report/csv/CSVReportListenerTest.java @@ -1,71 +1,71 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.csv; - -import static org.mockito.Mockito.verify; - -import java.io.IOException; -import java.io.Writer; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.report.MutationTestResultMother; - -public class CSVReportListenerTest { - - private static final String NEW_LINE = System.getProperty("line.separator"); - - private CSVReportListener testee; - - @Mock - private Writer out; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - this.testee = new CSVReportListener(this.out); - } - - @Test - public void shouldOutputKillingTestWhenOneFound() throws IOException { - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails(), new MutationStatusTestPair(1, - DetectionStatus.KILLED, "foo")); - this.testee.handleMutationResult(MutationTestResultMother - .createClassResults(mr)); - final String expected = "file,clazz,mutator,method,42,KILLED,foo" - + NEW_LINE; - verify(this.out).write(expected); - } - - @Test - public void shouldOutputNoneWhenNoKillingTestFound() throws IOException { - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails(), new MutationStatusTestPair(1, - DetectionStatus.SURVIVED)); - this.testee.handleMutationResult(MutationTestResultMother - .createClassResults(mr)); - final String expected = "file,clazz,mutator,method,42,SURVIVED,none" - + NEW_LINE; - - verify(this.out).write(expected); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.csv; + +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.io.Writer; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.report.MutationTestResultMother; + +public class CSVReportListenerTest { + + private static final String NEW_LINE = System.getProperty("line.separator"); + + private CSVReportListener testee; + + @Mock + private Writer out; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + this.testee = new CSVReportListener(this.out); + } + + @Test + public void shouldOutputKillingTestWhenOneFound() throws IOException { + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails(), new MutationStatusTestPair(1, + DetectionStatus.KILLED, "foo")); + this.testee.handleMutationResult(MutationTestResultMother + .createClassResults(mr)); + final String expected = "file,clazz,mutator,method,42,KILLED,foo" + + NEW_LINE; + verify(this.out).write(expected); + } + + @Test + public void shouldOutputNoneWhenNoKillingTestFound() throws IOException { + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails(), new MutationStatusTestPair(1, + DetectionStatus.SURVIVED)); + this.testee.handleMutationResult(MutationTestResultMother + .createClassResults(mr)); + final String expected = "file,clazz,mutator,method,42,SURVIVED,none" + + NEW_LINE; + + verify(this.out).write(expected); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/report/xml/XMLReportListenerTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/report/xml/XMLReportListenerTest.java index 623c8119d..e7c208935 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/report/xml/XMLReportListenerTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/report/xml/XMLReportListenerTest.java @@ -1,92 +1,92 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.xml; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.report.MutationTestResultMother; - -public class XMLReportListenerTest { - - private XMLReportListener testee; - - private Writer out; - - @Before - public void setup() { - this.out = new StringWriter(); - this.testee = new XMLReportListener(this.out); - } - - @Test - public void shouldCreateAValidXmlDocumentWhenNoResults() throws IOException { - this.testee.runStart(); - this.testee.runEnd(); - final String expected = "\n\n\n"; - assertEquals(expected, this.out.toString()); - } - - @Test - public void shouldOutputKillingTestWhenOneFound() throws IOException { - final MutationResult mr = createdKilledMutationWithKillingTestOf("foo"); - this.testee - .handleMutationResult(MutationTestResultMother.createClassResults(mr)); - final String expected = "fileclazzmethod()I42mutator10foodesc\n"; - assertEquals(expected, this.out.toString()); - } - - @Test - public void shouldEscapeGTAndLTSymbols() { - final MutationResult mr = createdKilledMutationWithKillingTestOf(""); - this.testee - .handleMutationResult(MutationTestResultMother.createClassResults(mr)); - assertTrue(this.out.toString().contains("<foo>")); - } - - private MutationResult createdKilledMutationWithKillingTestOf( - final String killingTest) { - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails(), - new MutationStatusTestPair(1, DetectionStatus.KILLED, killingTest)); - return mr; - } - - @Test - public void shouldOutputNoneWhenNoKillingTestFound() throws IOException { - final MutationResult mr = createSurvivingMutant(); - this.testee - .handleMutationResult(MutationTestResultMother.createClassResults(mr)); - final String expected = "fileclazzmethod()I42mutator10desc\n"; - assertEquals(expected, this.out.toString()); - } - - private MutationResult createSurvivingMutant() { - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails(), - new MutationStatusTestPair(1, DetectionStatus.SURVIVED)); - return mr; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.xml; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.report.MutationTestResultMother; + +public class XMLReportListenerTest { + + private XMLReportListener testee; + + private Writer out; + + @Before + public void setup() { + this.out = new StringWriter(); + this.testee = new XMLReportListener(this.out); + } + + @Test + public void shouldCreateAValidXmlDocumentWhenNoResults() throws IOException { + this.testee.runStart(); + this.testee.runEnd(); + final String expected = "\n\n\n"; + assertEquals(expected, this.out.toString()); + } + + @Test + public void shouldOutputKillingTestWhenOneFound() throws IOException { + final MutationResult mr = createdKilledMutationWithKillingTestOf("foo"); + this.testee + .handleMutationResult(MutationTestResultMother.createClassResults(mr)); + final String expected = "fileclazzmethod()I42mutator10foodesc\n"; + assertEquals(expected, this.out.toString()); + } + + @Test + public void shouldEscapeGTAndLTSymbols() { + final MutationResult mr = createdKilledMutationWithKillingTestOf(""); + this.testee + .handleMutationResult(MutationTestResultMother.createClassResults(mr)); + assertTrue(this.out.toString().contains("<foo>")); + } + + private MutationResult createdKilledMutationWithKillingTestOf( + final String killingTest) { + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails(), + new MutationStatusTestPair(1, DetectionStatus.KILLED, killingTest)); + return mr; + } + + @Test + public void shouldOutputNoneWhenNoKillingTestFound() throws IOException { + final MutationResult mr = createSurvivingMutant(); + this.testee + .handleMutationResult(MutationTestResultMother.createClassResults(mr)); + final String expected = "fileclazzmethod()I42mutator10desc\n"; + assertEquals(expected, this.out.toString()); + } + + private MutationResult createSurvivingMutant() { + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails(), + new MutationStatusTestPair(1, DetectionStatus.SURVIVED)); + return mr; + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/MutationStatisticsListenerTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/MutationStatisticsListenerTest.java index 9e5ff0f4b..73593be07 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/MutationStatisticsListenerTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/MutationStatisticsListenerTest.java @@ -1,66 +1,66 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.statistics; - -import static org.junit.Assert.assertTrue; - -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.report.MutationTestResultMother; - -public class MutationStatisticsListenerTest { - - private MutationStatisticsListener testee; - - @Before - public void setUp() { - this.testee = new MutationStatisticsListener(); - } - - @Test - public void shouldGatherStatistics() { - final MutationResult mr = makeResult(); - this.testee.handleMutationResult(createMetaData(mr)); - assertTrue(hasResultFor(mr.getDetails().getId().getMutator())); - } - - private MutationResult makeResult() { - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails("foo.java"), - new MutationStatusTestPair(1, DetectionStatus.KILLED, "foo")); - return mr; - } - - private boolean hasResultFor(final String mutator) { - return FCollection.contains(this.testee.getStatistics().getScores(), - hasResultForMutator(mutator)); - } - - private Predicate hasResultForMutator(final String mutator) { - return a -> a.getMutatorName().equals(mutator); - } - - private ClassMutationResults createMetaData(final MutationResult... mrs) { - return MutationTestResultMother.createClassResults(mrs); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.statistics; + +import static org.junit.Assert.assertTrue; + +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.report.MutationTestResultMother; + +public class MutationStatisticsListenerTest { + + private MutationStatisticsListener testee; + + @Before + public void setUp() { + this.testee = new MutationStatisticsListener(); + } + + @Test + public void shouldGatherStatistics() { + final MutationResult mr = makeResult(); + this.testee.handleMutationResult(createMetaData(mr)); + assertTrue(hasResultFor(mr.getDetails().getId().getMutator())); + } + + private MutationResult makeResult() { + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails("foo.java"), + new MutationStatusTestPair(1, DetectionStatus.KILLED, "foo")); + return mr; + } + + private boolean hasResultFor(final String mutator) { + return FCollection.contains(this.testee.getStatistics().getScores(), + hasResultForMutator(mutator)); + } + + private Predicate hasResultForMutator(final String mutator) { + return a -> a.getMutatorName().equals(mutator); + } + + private ClassMutationResults createMetaData(final MutationResult... mrs) { + return MutationTestResultMother.createClassResults(mrs); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/MutationStatisticsPrecursorTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/MutationStatisticsPrecursorTest.java index 5af023169..3405c7e15 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/MutationStatisticsPrecursorTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/MutationStatisticsPrecursorTest.java @@ -1,156 +1,156 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.statistics; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.report.MutationTestResultMother; -import org.pitest.util.StringUtil; - -public class MutationStatisticsPrecursorTest { - - private MutationStatisticsPrecursor testee; - - @Before - public void setUp() { - this.testee = new MutationStatisticsPrecursor(); - } - - @Test - public void shouldContainNoResultsWhenFirstConstructed() { - assertFalse(this.testee.getScores().iterator().hasNext()); - } - - @Test - public void shouldRecordStatisticsAgainstMutators() { - final MutationResult mr = makeResult(DetectionStatus.KILLED); - this.testee.registerResults(Collections.singletonList(mr)); - assertTrue(FCollection.contains(this.testee.getScores(), - hasResultForMutator(mr.getDetails().getId().getMutator()))); - } - - @Test - public void shouldCalculateTotalNumberOfMutationsWhenNoneGenerated() { - assertEquals(0, this.testee.toStatistics().getTotalMutations()); - } - - @Test - public void shouldCalculateTotalNumberOfMutationsWhenSomeGenerated() { - final MutationResult mr = makeResult(DetectionStatus.KILLED); - this.testee.registerResults(Arrays.asList(mr, mr, mr)); - assertEquals(3, this.testee.toStatistics().getTotalMutations()); - } - - @Test - public void shouldCalculateTotalNumberOfDetectedMutationsWhenNoneGenerated() { - assertEquals(0, this.testee.toStatistics().getTotalDetectedMutations()); - } - - @Test - public void shouldCalculateTotalNumberOfDetectedMutationsWhenNoneDetected() { - final MutationResult mr = makeResult(DetectionStatus.SURVIVED); - this.testee.registerResults(Arrays.asList(mr, mr, mr)); - assertEquals(0, this.testee.toStatistics().getTotalDetectedMutations()); - } - - @Test - public void shouldCalculateTotalNumberOfDetectedMutationsWhenSomeDetected() { - this.testee.registerResults(Arrays.asList( - makeResult(DetectionStatus.SURVIVED), - makeResult(DetectionStatus.KILLED))); - assertEquals(1, this.testee.toStatistics().getTotalDetectedMutations()); - } - - @Test - public void shouldCalculatePercentageDetected() { - this.testee.registerResults(Arrays.asList( - makeResult(DetectionStatus.SURVIVED), - makeResult(DetectionStatus.KILLED))); - assertEquals(50, this.testee.toStatistics().getPercentageDetected()); - } - - @Test - public void shouldReportNumberOfSurvivingMutants() { - this.testee.registerResults(Arrays.asList( - makeResult(DetectionStatus.SURVIVED), - makeResult(DetectionStatus.SURVIVED))); - assertEquals(2, this.testee.toStatistics().getTotalSurvivingMutations()); - } - - @Test - public void shouldReportNumberOfSurvivingMutantsWhenNoneSurvive() { - this.testee.registerResults(Arrays.asList( - makeResult(DetectionStatus.KILLED), - makeResult(DetectionStatus.TIMED_OUT))); - assertEquals(0, this.testee.toStatistics().getTotalSurvivingMutations()); - } - - @Test - public void shouldReportTotalNumberOfMutationsWhenNoneGenerated() { - this.testee.registerResults(Arrays.asList( - makeResult(DetectionStatus.SURVIVED), - makeResult(DetectionStatus.KILLED))); - final String[] actual = generateReportLines(); - assertEquals(">> Generated 2 mutations Killed 1 (50%)", actual[0]); - } - - @Test - public void shouldReportTotalNumberOfTestsRun() { - this.testee.registerResults(Arrays.asList( - makeResult(DetectionStatus.SURVIVED, 1), - makeResult(DetectionStatus.KILLED, 42))); - final String[] actual = generateReportLines(); - assertEquals(">> Ran 43 tests (21.5 tests per mutation)", actual[1]); - } - - private Predicate hasResultForMutator(final String mutator) { - return a -> a.getMutatorName().equals(mutator); - } - - private MutationResult makeResult(final DetectionStatus status) { - return makeResult(status, 0); - } - - private MutationResult makeResult(final DetectionStatus status, - final int numberOfTests) { - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails("foo.java"), - new MutationStatusTestPair(numberOfTests, status, "foo")); - return mr; - } - - private String[] generateReportLines() { - final ByteArrayOutputStream s = new ByteArrayOutputStream(); - final PrintStream out = new PrintStream(s); - this.testee.toStatistics().report(out); - final String actual = new String(s.toByteArray()); - final String[] ss = actual.split(StringUtil.newLine()); - return ss; - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.statistics; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.report.MutationTestResultMother; +import org.pitest.util.StringUtil; + +public class MutationStatisticsPrecursorTest { + + private MutationStatisticsPrecursor testee; + + @Before + public void setUp() { + this.testee = new MutationStatisticsPrecursor(); + } + + @Test + public void shouldContainNoResultsWhenFirstConstructed() { + assertFalse(this.testee.getScores().iterator().hasNext()); + } + + @Test + public void shouldRecordStatisticsAgainstMutators() { + final MutationResult mr = makeResult(DetectionStatus.KILLED); + this.testee.registerResults(Collections.singletonList(mr)); + assertTrue(FCollection.contains(this.testee.getScores(), + hasResultForMutator(mr.getDetails().getId().getMutator()))); + } + + @Test + public void shouldCalculateTotalNumberOfMutationsWhenNoneGenerated() { + assertEquals(0, this.testee.toStatistics().getTotalMutations()); + } + + @Test + public void shouldCalculateTotalNumberOfMutationsWhenSomeGenerated() { + final MutationResult mr = makeResult(DetectionStatus.KILLED); + this.testee.registerResults(Arrays.asList(mr, mr, mr)); + assertEquals(3, this.testee.toStatistics().getTotalMutations()); + } + + @Test + public void shouldCalculateTotalNumberOfDetectedMutationsWhenNoneGenerated() { + assertEquals(0, this.testee.toStatistics().getTotalDetectedMutations()); + } + + @Test + public void shouldCalculateTotalNumberOfDetectedMutationsWhenNoneDetected() { + final MutationResult mr = makeResult(DetectionStatus.SURVIVED); + this.testee.registerResults(Arrays.asList(mr, mr, mr)); + assertEquals(0, this.testee.toStatistics().getTotalDetectedMutations()); + } + + @Test + public void shouldCalculateTotalNumberOfDetectedMutationsWhenSomeDetected() { + this.testee.registerResults(Arrays.asList( + makeResult(DetectionStatus.SURVIVED), + makeResult(DetectionStatus.KILLED))); + assertEquals(1, this.testee.toStatistics().getTotalDetectedMutations()); + } + + @Test + public void shouldCalculatePercentageDetected() { + this.testee.registerResults(Arrays.asList( + makeResult(DetectionStatus.SURVIVED), + makeResult(DetectionStatus.KILLED))); + assertEquals(50, this.testee.toStatistics().getPercentageDetected()); + } + + @Test + public void shouldReportNumberOfSurvivingMutants() { + this.testee.registerResults(Arrays.asList( + makeResult(DetectionStatus.SURVIVED), + makeResult(DetectionStatus.SURVIVED))); + assertEquals(2, this.testee.toStatistics().getTotalSurvivingMutations()); + } + + @Test + public void shouldReportNumberOfSurvivingMutantsWhenNoneSurvive() { + this.testee.registerResults(Arrays.asList( + makeResult(DetectionStatus.KILLED), + makeResult(DetectionStatus.TIMED_OUT))); + assertEquals(0, this.testee.toStatistics().getTotalSurvivingMutations()); + } + + @Test + public void shouldReportTotalNumberOfMutationsWhenNoneGenerated() { + this.testee.registerResults(Arrays.asList( + makeResult(DetectionStatus.SURVIVED), + makeResult(DetectionStatus.KILLED))); + final String[] actual = generateReportLines(); + assertEquals(">> Generated 2 mutations Killed 1 (50%)", actual[0]); + } + + @Test + public void shouldReportTotalNumberOfTestsRun() { + this.testee.registerResults(Arrays.asList( + makeResult(DetectionStatus.SURVIVED, 1), + makeResult(DetectionStatus.KILLED, 42))); + final String[] actual = generateReportLines(); + assertEquals(">> Ran 43 tests (21.5 tests per mutation)", actual[1]); + } + + private Predicate hasResultForMutator(final String mutator) { + return a -> a.getMutatorName().equals(mutator); + } + + private MutationResult makeResult(final DetectionStatus status) { + return makeResult(status, 0); + } + + private MutationResult makeResult(final DetectionStatus status, + final int numberOfTests) { + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails("foo.java"), + new MutationStatusTestPair(numberOfTests, status, "foo")); + return mr; + } + + private String[] generateReportLines() { + final ByteArrayOutputStream s = new ByteArrayOutputStream(); + final PrintStream out = new PrintStream(s); + this.testee.toStatistics().report(out); + final String actual = new String(s.toByteArray()); + final String[] ss = actual.split(StringUtil.newLine()); + return ss; + } +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/ScoreTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/ScoreTest.java index ce9362d82..1072454c1 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/ScoreTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/statistics/ScoreTest.java @@ -1,143 +1,143 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.statistics; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.util.StringUtil; - -public class ScoreTest { - - private ScorePrecursor testee; - - @Before - public void setUp() { - this.testee = new ScorePrecursor("foo"); - } - - @Test - public void shouldContainEmptyScoreForEachStatusWhenConstructed() { - for (final DetectionStatus each : DetectionStatus.values()) { - assertTrue(FCollection.contains(this.testee.getCounts(), - countFor(each, 0))); - } - - } - - @Test - public void registerResultsShouldIncrementCount() { - this.testee.registerResult(DetectionStatus.KILLED); - assertTrue(FCollection.contains(this.testee.getCounts(), - countFor(DetectionStatus.KILLED, 1))); - } - - @Test - public void shouldPrintMutatorNameOnFirstLine() { - final String[] ss = generateReportLines(); - assertEquals("> foo", ss[0]); - } - - @Test - public void shouldPrintTotalsAndPercentageInSecondLine() { - final String[] ss = generateReportLines(); - assertEquals(">> Generated 0 Killed 0 (100%)", ss[1]); - } - - @Test - public void shouldPrintScoresFourToALine() { - final String[] ss = generateReportLines(); - assertEquals("> KILLED 0 SURVIVED 0 TIMED_OUT 0 NON_VIABLE 0 ", ss[2]); - } - - private String[] generateReportLines() { - final ByteArrayOutputStream s = new ByteArrayOutputStream(); - final PrintStream out = new PrintStream(s); - this.testee.toScore().report(out); - final String actual = new String(s.toByteArray()); - final String[] ss = actual.split(StringUtil.newLine()); - return ss; - } - - @Test - public void shouldCalculateTotalNumberOfMutationsWhenNoneRegistered() { - assertEquals(0, this.testee.toScore().getTotalMutations()); - } - - @Test - public void shouldCalculateTotalNumberOfDectedMutationsWhenNoneRegistered() { - assertEquals(0, this.testee.toScore().getTotalDetectedMutations()); - } - - @Test - public void shouldCalculateTotalNumberOfMutationsWhenSomeRegistered() { - this.testee.registerResult(DetectionStatus.KILLED); - this.testee.registerResult(DetectionStatus.NO_COVERAGE); - assertEquals(2, this.testee.toScore().getTotalMutations()); - } - - @Test - public void shouldCalculateTotalNumberOfDetectedMutationsWhenSomeRegistered() { - this.testee.registerResult(DetectionStatus.KILLED); - this.testee.registerResult(DetectionStatus.NO_COVERAGE); - this.testee.registerResult(DetectionStatus.TIMED_OUT); - this.testee.registerResult(DetectionStatus.SURVIVED); - assertEquals(2, this.testee.toScore().getTotalDetectedMutations()); - } - - @Test - public void shouldCalculatePercentageDetectedWhenNoneFound() { - assertEquals(100, this.testee.toScore().getPercentageDetected()); - } - - @Test - public void shouldCalculatePercentageDetectedWhenNoneDetected() { - this.testee.registerResult(DetectionStatus.SURVIVED); - assertEquals(0, this.testee.toScore().getPercentageDetected()); - } - - @Test - public void shouldCalculatePercentageDetectedWhenSomeDetected() { - registerResults(DetectionStatus.SURVIVED, 2); - registerResults(DetectionStatus.KILLED, 1); - assertEquals(33, this.testee.toScore().getPercentageDetected()); - } - - @Test - public void shouldCalculatePercentageDetectedWhenAllDetected() { - registerResults(DetectionStatus.KILLED, 8); - assertEquals(100, this.testee.toScore().getPercentageDetected()); - } - - private void registerResults(final DetectionStatus status, final int times) { - for (int i = 0; i != times; i++) { - this.testee.registerResult(status); - } - } - - private Predicate countFor(final DetectionStatus each, - final int count) { - return a -> a.getStatus().equals(each) && (a.getCount() == count); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.statistics; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.util.StringUtil; + +public class ScoreTest { + + private ScorePrecursor testee; + + @Before + public void setUp() { + this.testee = new ScorePrecursor("foo"); + } + + @Test + public void shouldContainEmptyScoreForEachStatusWhenConstructed() { + for (final DetectionStatus each : DetectionStatus.values()) { + assertTrue(FCollection.contains(this.testee.getCounts(), + countFor(each, 0))); + } + + } + + @Test + public void registerResultsShouldIncrementCount() { + this.testee.registerResult(DetectionStatus.KILLED); + assertTrue(FCollection.contains(this.testee.getCounts(), + countFor(DetectionStatus.KILLED, 1))); + } + + @Test + public void shouldPrintMutatorNameOnFirstLine() { + final String[] ss = generateReportLines(); + assertEquals("> foo", ss[0]); + } + + @Test + public void shouldPrintTotalsAndPercentageInSecondLine() { + final String[] ss = generateReportLines(); + assertEquals(">> Generated 0 Killed 0 (100%)", ss[1]); + } + + @Test + public void shouldPrintScoresFourToALine() { + final String[] ss = generateReportLines(); + assertEquals("> KILLED 0 SURVIVED 0 TIMED_OUT 0 NON_VIABLE 0 ", ss[2]); + } + + private String[] generateReportLines() { + final ByteArrayOutputStream s = new ByteArrayOutputStream(); + final PrintStream out = new PrintStream(s); + this.testee.toScore().report(out); + final String actual = new String(s.toByteArray()); + final String[] ss = actual.split(StringUtil.newLine()); + return ss; + } + + @Test + public void shouldCalculateTotalNumberOfMutationsWhenNoneRegistered() { + assertEquals(0, this.testee.toScore().getTotalMutations()); + } + + @Test + public void shouldCalculateTotalNumberOfDectedMutationsWhenNoneRegistered() { + assertEquals(0, this.testee.toScore().getTotalDetectedMutations()); + } + + @Test + public void shouldCalculateTotalNumberOfMutationsWhenSomeRegistered() { + this.testee.registerResult(DetectionStatus.KILLED); + this.testee.registerResult(DetectionStatus.NO_COVERAGE); + assertEquals(2, this.testee.toScore().getTotalMutations()); + } + + @Test + public void shouldCalculateTotalNumberOfDetectedMutationsWhenSomeRegistered() { + this.testee.registerResult(DetectionStatus.KILLED); + this.testee.registerResult(DetectionStatus.NO_COVERAGE); + this.testee.registerResult(DetectionStatus.TIMED_OUT); + this.testee.registerResult(DetectionStatus.SURVIVED); + assertEquals(2, this.testee.toScore().getTotalDetectedMutations()); + } + + @Test + public void shouldCalculatePercentageDetectedWhenNoneFound() { + assertEquals(100, this.testee.toScore().getPercentageDetected()); + } + + @Test + public void shouldCalculatePercentageDetectedWhenNoneDetected() { + this.testee.registerResult(DetectionStatus.SURVIVED); + assertEquals(0, this.testee.toScore().getPercentageDetected()); + } + + @Test + public void shouldCalculatePercentageDetectedWhenSomeDetected() { + registerResults(DetectionStatus.SURVIVED, 2); + registerResults(DetectionStatus.KILLED, 1); + assertEquals(33, this.testee.toScore().getPercentageDetected()); + } + + @Test + public void shouldCalculatePercentageDetectedWhenAllDetected() { + registerResults(DetectionStatus.KILLED, 8); + assertEquals(100, this.testee.toScore().getPercentageDetected()); + } + + private void registerResults(final DetectionStatus status, final int times) { + for (int i = 0; i != times; i++) { + this.testee.registerResult(status); + } + } + + private Predicate countFor(final DetectionStatus each, + final int count) { + return a -> a.getStatus().equals(each) && (a.getCount() == count); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/DirectorySourceLocatorTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/DirectorySourceLocatorTest.java index ec50319bc..d7a6c31a3 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/DirectorySourceLocatorTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/DirectorySourceLocatorTest.java @@ -1,64 +1,64 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.tooling; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.Reader; -import java.util.Collections; -import java.util.function.Function; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import java.util.Optional; - -public class DirectorySourceLocatorTest { - - private DirectorySourceLocator testee; - private File root; - - @Mock - Function> locator; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.root = new File("."); - this.testee = new DirectorySourceLocator(this.root, this.locator); - when(this.locator.apply(any(File.class))) - .thenReturn(Optional. empty()); - } - - @Test - public void shouldLocateSourceForClassesInDefaultPackage() { - this.testee.locate(Collections.singletonList("Foo"), "Foo.java"); - final File expected = new File(this.root + File.separator + "Foo.java"); - verify(this.locator).apply(expected); - } - - @Test - public void shouldLocateSourceForClassesInNamedPacakges() { - this.testee - .locate(Collections.singletonList("com.example.Foo"), "Foo.java"); - final File expected = new File(this.root + File.separator + "com" - + File.separator + "example" + File.separator + "Foo.java"); - verify(this.locator).apply(expected); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.tooling; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.Reader; +import java.util.Collections; +import java.util.function.Function; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import java.util.Optional; + +public class DirectorySourceLocatorTest { + + private DirectorySourceLocator testee; + private File root; + + @Mock + Function> locator; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.root = new File("."); + this.testee = new DirectorySourceLocator(this.root, this.locator); + when(this.locator.apply(any(File.class))) + .thenReturn(Optional. empty()); + } + + @Test + public void shouldLocateSourceForClassesInDefaultPackage() { + this.testee.locate(Collections.singletonList("Foo"), "Foo.java"); + final File expected = new File(this.root + File.separator + "Foo.java"); + verify(this.locator).apply(expected); + } + + @Test + public void shouldLocateSourceForClassesInNamedPacakges() { + this.testee + .locate(Collections.singletonList("com.example.Foo"), "Foo.java"); + final File expected = new File(this.root + File.separator + "com" + + File.separator + "example" + File.separator + "Foo.java"); + verify(this.locator).apply(expected); + } +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/JarCreatingJarFinderTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/JarCreatingJarFinderTest.java index d9eb3199d..9b3d794d9 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/JarCreatingJarFinderTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/JarCreatingJarFinderTest.java @@ -1,144 +1,144 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.tooling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.jar.Attributes; -import java.util.jar.JarInputStream; -import java.util.jar.Manifest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.boot.HotSwapAgent; -import org.pitest.classinfo.ClassByteArraySource; -import java.util.Optional; -import org.pitest.util.PitError; - -public class JarCreatingJarFinderTest { - - private JarCreatingJarFinder testee; - - @Mock - private ClassByteArraySource byteSource; - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - when(this.byteSource.getBytes(anyString())).thenReturn( - Optional.ofNullable(new byte[1])); - this.testee = new JarCreatingJarFinder(this.byteSource); - } - - @After - public void cleanup() { - if (this.testee != null) { - this.testee.close(); - } - } - - @Test - public void shouldConstructWithoutError() { - new JarCreatingJarFinder(); - // pass - } - - @Test - public void shouldCloseWithoutErrorWhenNoLocationSet() { - this.testee.close(); - // pass - } - - @Test - public void shouldCreateJarFile() { - final Optional actual = this.testee.getJarLocation(); - assertTrue(actual.isPresent()); - } - - @Test - public void shouldCreateJarFileInSystemTempDirectory() { - final String tempDirLocation = System.getProperty("java.io.tmpdir"); - final Optional actual = this.testee.getJarLocation(); - assertTrue(actual.get().startsWith(tempDirLocation)); - } - - @Test - public void shouldSetPreMainClassAttribute() throws IOException { - assertGeneratedManifestEntryEquals(JarCreatingJarFinder.PREMAIN_CLASS, - HotSwapAgent.class.getName()); - } - - @Test - public void shouldSetCanRedefineClasses() throws IOException { - assertGeneratedManifestEntryEquals( - JarCreatingJarFinder.CAN_REDEFINE_CLASSES, "true"); - } - - @Test - public void shouldSetNativeMethodPrefix() throws IOException { - assertGeneratedManifestEntryEquals( - JarCreatingJarFinder.CAN_SET_NATIVE_METHOD, "true"); - } - - @Test - public void shouldAddPITToTheBootClassPath() throws IOException { - final String actual = getGeneratedManifestAttribute(JarCreatingJarFinder.BOOT_CLASSPATH); - assertTrue(!actual.equals("")); - } - - @Test - public void shouldFailOnUnreadableRessources() throws IOException { - this.thrown.expect(PitError.class); - - when(this.byteSource.getBytes(anyString())).thenReturn( - Optional. empty()); - - this.testee.getJarLocation(); - } - - private void assertGeneratedManifestEntryEquals(final String key, - final String expected) throws IOException, FileNotFoundException { - final String am = getGeneratedManifestAttribute(key); - assertEquals(expected, am); - } - - private String getGeneratedManifestAttribute(final String key) - throws IOException, FileNotFoundException { - final Optional actual = this.testee.getJarLocation(); - final File f = new File(actual.get()); - try (JarInputStream jis = new JarInputStream(new FileInputStream(f))) { - final Manifest m = jis.getManifest(); - final Attributes a = m.getMainAttributes(); - final String am = a.getValue(key); - - return am; - } - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.tooling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.jar.Attributes; +import java.util.jar.JarInputStream; +import java.util.jar.Manifest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.boot.HotSwapAgent; +import org.pitest.classinfo.ClassByteArraySource; +import java.util.Optional; +import org.pitest.util.PitError; + +public class JarCreatingJarFinderTest { + + private JarCreatingJarFinder testee; + + @Mock + private ClassByteArraySource byteSource; + + @Rule + public final ExpectedException thrown = ExpectedException.none(); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + when(this.byteSource.getBytes(anyString())).thenReturn( + Optional.ofNullable(new byte[1])); + this.testee = new JarCreatingJarFinder(this.byteSource); + } + + @After + public void cleanup() { + if (this.testee != null) { + this.testee.close(); + } + } + + @Test + public void shouldConstructWithoutError() { + new JarCreatingJarFinder(); + // pass + } + + @Test + public void shouldCloseWithoutErrorWhenNoLocationSet() { + this.testee.close(); + // pass + } + + @Test + public void shouldCreateJarFile() { + final Optional actual = this.testee.getJarLocation(); + assertTrue(actual.isPresent()); + } + + @Test + public void shouldCreateJarFileInSystemTempDirectory() { + final String tempDirLocation = System.getProperty("java.io.tmpdir"); + final Optional actual = this.testee.getJarLocation(); + assertTrue(actual.get().startsWith(tempDirLocation)); + } + + @Test + public void shouldSetPreMainClassAttribute() throws IOException { + assertGeneratedManifestEntryEquals(JarCreatingJarFinder.PREMAIN_CLASS, + HotSwapAgent.class.getName()); + } + + @Test + public void shouldSetCanRedefineClasses() throws IOException { + assertGeneratedManifestEntryEquals( + JarCreatingJarFinder.CAN_REDEFINE_CLASSES, "true"); + } + + @Test + public void shouldSetNativeMethodPrefix() throws IOException { + assertGeneratedManifestEntryEquals( + JarCreatingJarFinder.CAN_SET_NATIVE_METHOD, "true"); + } + + @Test + public void shouldAddPITToTheBootClassPath() throws IOException { + final String actual = getGeneratedManifestAttribute(JarCreatingJarFinder.BOOT_CLASSPATH); + assertTrue(!actual.equals("")); + } + + @Test + public void shouldFailOnUnreadableRessources() throws IOException { + this.thrown.expect(PitError.class); + + when(this.byteSource.getBytes(anyString())).thenReturn( + Optional. empty()); + + this.testee.getJarLocation(); + } + + private void assertGeneratedManifestEntryEquals(final String key, + final String expected) throws IOException, FileNotFoundException { + final String am = getGeneratedManifestAttribute(key); + assertEquals(expected, am); + } + + private String getGeneratedManifestAttribute(final String key) + throws IOException, FileNotFoundException { + final Optional actual = this.testee.getJarLocation(); + final File f = new File(actual.get()); + try (JarInputStream jis = new JarInputStream(new FileInputStream(f))) { + final Manifest m = jis.getManifest(); + final Attributes a = m.getMainAttributes(); + final String am = a.getValue(key); + + return am; + } + } +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/MutationCoverageReportTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/MutationCoverageReportTest.java index f0b00ce4d..c83b857d9 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/MutationCoverageReportTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/MutationCoverageReportTest.java @@ -1,209 +1,209 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.tooling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassIdentifier; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassInfoMother; -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.HierarchicalClassId; -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.coverage.CoverageGenerator; -import org.pitest.help.Help; -import org.pitest.help.PitHelpError; -import org.pitest.mutationtest.EngineArguments; -import org.pitest.mutationtest.HistoryStore; -import org.pitest.mutationtest.ListenerArguments; -import org.pitest.mutationtest.MutationEngineFactory; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.MutationResultListenerFactory; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.config.SettingsFactory; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetailsMother; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; -import org.pitest.mutationtest.verify.BuildVerifier; -import org.pitest.util.ResultOutputStrategy; -import org.pitest.util.Timings; -import org.pitest.util.Unchecked; - -public class MutationCoverageReportTest { - - private MutationCoverage testee; - - private ReportOptions data; - - @Mock - private MutationResultListenerFactory listenerFactory; - - @Mock - private MutationResultListener listener; - - @Mock - private CoverageDatabase coverageDb; - - @Mock - private CoverageGenerator coverage; - - @Mock - private CodeSource code; - - @Mock - private HistoryStore history; - - @Mock - private MutationEngineFactory mutationFactory; - - @Mock - private BuildVerifier verifier; - - @Mock - private MutationEngine engine; - - @Mock - private Mutater mutater; - - @Mock - private ResultOutputStrategy output; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.data = new ReportOptions(); - this.data.setSourceDirs(Collections. emptyList()); - when(this.coverage.calculateCoverage()).thenReturn(this.coverageDb); - when( - this.listenerFactory.getListener(Matchers. any(), - any(ListenerArguments.class))).thenReturn(this.listener); - mockMutationEngine(); - } - - private void mockMutationEngine() { - when( - this.mutationFactory.createEngine(any(EngineArguments.class))).thenReturn( - this.engine); - when(this.engine.createMutator(any(ClassByteArraySource.class))) - .thenReturn(this.mutater); - } - - @Test - public void shouldReportErrorWhenNoMutationsFoundAndFlagSet() { - try { - this.data.setFailWhenNoMutations(true); - createAndRunTestee(); - } catch (final PitHelpError phe) { - assertEquals(Help.NO_MUTATIONS_FOUND.toString(), phe.getMessage()); - } - } - - @Test - public void shouldNotReportErrorWhenNoMutationsFoundAndFlagNotSet() { - try { - this.data.setFailWhenNoMutations(false); - createAndRunTestee(); - } catch (final PitHelpError phe) { - fail(); - } - } - - @Test - public void shouldRecordClassPath() { - - final ClassName clazz = ClassName.fromClass(Foo.class); - - final HierarchicalClassId fooId = new HierarchicalClassId( - new ClassIdentifier(0, clazz), "0"); - final ClassInfo foo = ClassInfoMother.make(fooId.getId()); - - when(this.code.getCodeUnderTestNames()).thenReturn( - Collections.singleton(clazz)); - when(this.code.getClassInfo(any(List.class))).thenReturn( - Collections.singletonList(foo)); - - createAndRunTestee(); - - verify(this.history).recordClassPath(Arrays.asList(fooId), this.coverageDb); - } - - @Test - public void shouldCheckBuildSuitableForMutationTesting() { - createAndRunTestee(); - verify(this.verifier).verify(any(CodeSource.class)); - } - - @Test - public void shouldReportNoMutationsFoundWhenNoneDetected() { - this.data.setFailWhenNoMutations(false); - final CombinedStatistics actual = createAndRunTestee(); - assertEquals(0, actual.getMutationStatistics().getTotalMutations()); - } - - @Test - @Ignore("is triggering filter with fake classes") - public void shouldReportMutationsFoundWhenSomeDetected() { - this.data.setFailWhenNoMutations(false); - final ClassName foo = ClassName.fromClass(Foo.class); - when(this.mutater.findMutations(foo)).thenReturn( - MutationDetailsMother.aMutationDetail().build(1)); - when(this.code.getCodeUnderTestNames()).thenReturn( - Collections.singleton(foo)); - final CombinedStatistics actual = createAndRunTestee(); - assertEquals(1, actual.getMutationStatistics().getTotalMutations()); - } - - private CombinedStatistics createAndRunTestee() { - final MutationStrategies strategies = new MutationStrategies( - new GregorEngineFactory(), this.history, this.coverage, - this.listenerFactory, this.output).with(this.mutationFactory).with( - this.verifier); - - this.testee = new MutationCoverage(strategies, null, this.code, this.data, - new SettingsFactory(this.data, PluginServices.makeForContextLoader()), - new Timings()); - try { - return this.testee.runReport(); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - -} - -class Foo { - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.tooling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassIdentifier; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassInfoMother; +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.HierarchicalClassId; +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.coverage.CoverageGenerator; +import org.pitest.help.Help; +import org.pitest.help.PitHelpError; +import org.pitest.mutationtest.EngineArguments; +import org.pitest.mutationtest.HistoryStore; +import org.pitest.mutationtest.ListenerArguments; +import org.pitest.mutationtest.MutationEngineFactory; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.MutationResultListenerFactory; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.config.SettingsFactory; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetailsMother; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.mutationtest.engine.gregor.config.GregorEngineFactory; +import org.pitest.mutationtest.verify.BuildVerifier; +import org.pitest.util.ResultOutputStrategy; +import org.pitest.util.Timings; +import org.pitest.util.Unchecked; + +public class MutationCoverageReportTest { + + private MutationCoverage testee; + + private ReportOptions data; + + @Mock + private MutationResultListenerFactory listenerFactory; + + @Mock + private MutationResultListener listener; + + @Mock + private CoverageDatabase coverageDb; + + @Mock + private CoverageGenerator coverage; + + @Mock + private CodeSource code; + + @Mock + private HistoryStore history; + + @Mock + private MutationEngineFactory mutationFactory; + + @Mock + private BuildVerifier verifier; + + @Mock + private MutationEngine engine; + + @Mock + private Mutater mutater; + + @Mock + private ResultOutputStrategy output; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.data = new ReportOptions(); + this.data.setSourceDirs(Collections. emptyList()); + when(this.coverage.calculateCoverage()).thenReturn(this.coverageDb); + when( + this.listenerFactory.getListener(Matchers. any(), + any(ListenerArguments.class))).thenReturn(this.listener); + mockMutationEngine(); + } + + private void mockMutationEngine() { + when( + this.mutationFactory.createEngine(any(EngineArguments.class))).thenReturn( + this.engine); + when(this.engine.createMutator(any(ClassByteArraySource.class))) + .thenReturn(this.mutater); + } + + @Test + public void shouldReportErrorWhenNoMutationsFoundAndFlagSet() { + try { + this.data.setFailWhenNoMutations(true); + createAndRunTestee(); + } catch (final PitHelpError phe) { + assertEquals(Help.NO_MUTATIONS_FOUND.toString(), phe.getMessage()); + } + } + + @Test + public void shouldNotReportErrorWhenNoMutationsFoundAndFlagNotSet() { + try { + this.data.setFailWhenNoMutations(false); + createAndRunTestee(); + } catch (final PitHelpError phe) { + fail(); + } + } + + @Test + public void shouldRecordClassPath() { + + final ClassName clazz = ClassName.fromClass(Foo.class); + + final HierarchicalClassId fooId = new HierarchicalClassId( + new ClassIdentifier(0, clazz), "0"); + final ClassInfo foo = ClassInfoMother.make(fooId.getId()); + + when(this.code.getCodeUnderTestNames()).thenReturn( + Collections.singleton(clazz)); + when(this.code.getClassInfo(any(List.class))).thenReturn( + Collections.singletonList(foo)); + + createAndRunTestee(); + + verify(this.history).recordClassPath(Arrays.asList(fooId), this.coverageDb); + } + + @Test + public void shouldCheckBuildSuitableForMutationTesting() { + createAndRunTestee(); + verify(this.verifier).verify(any(CodeSource.class)); + } + + @Test + public void shouldReportNoMutationsFoundWhenNoneDetected() { + this.data.setFailWhenNoMutations(false); + final CombinedStatistics actual = createAndRunTestee(); + assertEquals(0, actual.getMutationStatistics().getTotalMutations()); + } + + @Test + @Ignore("is triggering filter with fake classes") + public void shouldReportMutationsFoundWhenSomeDetected() { + this.data.setFailWhenNoMutations(false); + final ClassName foo = ClassName.fromClass(Foo.class); + when(this.mutater.findMutations(foo)).thenReturn( + MutationDetailsMother.aMutationDetail().build(1)); + when(this.code.getCodeUnderTestNames()).thenReturn( + Collections.singleton(foo)); + final CombinedStatistics actual = createAndRunTestee(); + assertEquals(1, actual.getMutationStatistics().getTotalMutations()); + } + + private CombinedStatistics createAndRunTestee() { + final MutationStrategies strategies = new MutationStrategies( + new GregorEngineFactory(), this.history, this.coverage, + this.listenerFactory, this.output).with(this.mutationFactory).with( + this.verifier); + + this.testee = new MutationCoverage(strategies, null, this.code, this.data, + new SettingsFactory(this.data, PluginServices.makeForContextLoader()), + new Timings()); + try { + return this.testee.runReport(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + +} + +class Foo { + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/SpinnerListenerTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/SpinnerListenerTest.java index 56e377b90..1faa84c80 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/SpinnerListenerTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/tooling/SpinnerListenerTest.java @@ -1,22 +1,22 @@ -package org.pitest.mutationtest.tooling; - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import org.junit.Test; - -public class SpinnerListenerTest { - - @Test - public void shouldPrintSpinnerSequence() { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final PrintStream out = new PrintStream(bos); - final SpinnerListener testee = new SpinnerListener(out); - testee.handleMutationResult(null); - testee.handleMutationResult(null); - assertEquals("\u0008/\u0008-", new String(bos.toByteArray())); - } - -} +package org.pitest.mutationtest.tooling; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.Test; + +public class SpinnerListenerTest { + + @Test + public void shouldPrintSpinnerSequence() { + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final PrintStream out = new PrintStream(bos); + final SpinnerListener testee = new SpinnerListener(out); + testee.handleMutationResult(null); + testee.handleMutationResult(null); + assertEquals("\u0008/\u0008-", new String(bos.toByteArray())); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/mutationtest/verify/DefaultBuildVerifierTest.java b/pitest-entry/src/test/java/org/pitest/mutationtest/verify/DefaultBuildVerifierTest.java index ca3254ef7..608797a9f 100644 --- a/pitest-entry/src/test/java/org/pitest/mutationtest/verify/DefaultBuildVerifierTest.java +++ b/pitest-entry/src/test/java/org/pitest/mutationtest/verify/DefaultBuildVerifierTest.java @@ -1,122 +1,122 @@ -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.verify; - -import static org.junit.Assert.fail; -import static org.mockito.Mockito.when; - -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.Repository; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.classpath.CodeSource; -import org.pitest.help.PitHelpError; -import org.pitest.util.IsolationUtils; -import org.pitest.util.ResourceFolderByteArraySource; - -public class DefaultBuildVerifierTest { - - private DefaultBuildVerifier testee; - - @Mock - private CodeSource code; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new DefaultBuildVerifier(); - } - - private static class AClass { - - } - - private static interface AnInterface { - - } - - - @Test - public void shouldNotThrowErrorForClassCompiledWithDebugInfo() { - setupClassPath(AClass.class); - this.testee.verify(this.code); - // pass - } - - @Test(expected = PitHelpError.class) - public void shouldThrowErrorForClassCompiledWithoutSourceFileDebugInfo() { - setupClassPath(new ResourceFolderByteArraySource(), "FooNoSource"); - this.testee.verify(this.code); - } - - @Test - public void shouldNotThrowErrorForSyntheticClassCompiledWithoutSourceFileDebugInfo() { - setupClassPath(new ResourceFolderByteArraySource(), "SyntheticNoSourceDebug"); - try { - this.testee.verify(this.code); - } catch (final PitHelpError ex) { - fail(); - } - } - - @Test(expected = PitHelpError.class) - public void shouldThrowErrorForClassCompiledWithoutLineNumberDebugInfo() { - setupClassPath(new ResourceFolderByteArraySource(), "FooNoLines"); - this.testee.verify(this.code); - } - - @Test - public void shouldNotThrowAnErrorWhenNoClassesFound() { - when(this.code.getCode()).thenReturn(Collections. emptyList()); - try { - this.testee.verify(this.code); - } catch (final PitHelpError e) { - fail(); - } - } - - @Test - public void shouldNotThrowAnErrorWhenOnlyInterfacesPresent() { - setupClassPath(AnInterface.class); - try { - this.testee.verify(this.code); - } catch (final PitHelpError e) { - fail(); - } - } - - private void setupClassPath(final Class clazz) { - this.setupClassPath( - new ClassloaderByteArraySource(IsolationUtils.getContextClassLoader()), - clazz.getName()); - } - - private void setupClassPath(final ClassByteArraySource source, - final String clazz) { - final Repository repository = new Repository(source); - final ClassInfo ci = repository.fetchClass(ClassName.fromString(clazz)) - .get(); - when(this.code.getCode()).thenReturn(Collections.singletonList(ci)); - } - -} +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.verify; + +import static org.junit.Assert.fail; +import static org.mockito.Mockito.when; + +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.Repository; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.classpath.CodeSource; +import org.pitest.help.PitHelpError; +import org.pitest.util.IsolationUtils; +import org.pitest.util.ResourceFolderByteArraySource; + +public class DefaultBuildVerifierTest { + + private DefaultBuildVerifier testee; + + @Mock + private CodeSource code; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new DefaultBuildVerifier(); + } + + private static class AClass { + + } + + private static interface AnInterface { + + } + + + @Test + public void shouldNotThrowErrorForClassCompiledWithDebugInfo() { + setupClassPath(AClass.class); + this.testee.verify(this.code); + // pass + } + + @Test(expected = PitHelpError.class) + public void shouldThrowErrorForClassCompiledWithoutSourceFileDebugInfo() { + setupClassPath(new ResourceFolderByteArraySource(), "FooNoSource"); + this.testee.verify(this.code); + } + + @Test + public void shouldNotThrowErrorForSyntheticClassCompiledWithoutSourceFileDebugInfo() { + setupClassPath(new ResourceFolderByteArraySource(), "SyntheticNoSourceDebug"); + try { + this.testee.verify(this.code); + } catch (final PitHelpError ex) { + fail(); + } + } + + @Test(expected = PitHelpError.class) + public void shouldThrowErrorForClassCompiledWithoutLineNumberDebugInfo() { + setupClassPath(new ResourceFolderByteArraySource(), "FooNoLines"); + this.testee.verify(this.code); + } + + @Test + public void shouldNotThrowAnErrorWhenNoClassesFound() { + when(this.code.getCode()).thenReturn(Collections. emptyList()); + try { + this.testee.verify(this.code); + } catch (final PitHelpError e) { + fail(); + } + } + + @Test + public void shouldNotThrowAnErrorWhenOnlyInterfacesPresent() { + setupClassPath(AnInterface.class); + try { + this.testee.verify(this.code); + } catch (final PitHelpError e) { + fail(); + } + } + + private void setupClassPath(final Class clazz) { + this.setupClassPath( + new ClassloaderByteArraySource(IsolationUtils.getContextClassLoader()), + clazz.getName()); + } + + private void setupClassPath(final ClassByteArraySource source, + final String clazz) { + final Repository repository = new Repository(source); + final ClassInfo ci = repository.fetchClass(ClassName.fromString(clazz)) + .get(); + when(this.code.getCode()).thenReturn(Collections.singletonList(ci)); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/plugin/export/MutantExportInterceptorTest.java b/pitest-entry/src/test/java/org/pitest/plugin/export/MutantExportInterceptorTest.java index 75d351a4a..14f29e629 100644 --- a/pitest-entry/src/test/java/org/pitest/plugin/export/MutantExportInterceptorTest.java +++ b/pitest-entry/src/test/java/org/pitest/plugin/export/MutantExportInterceptorTest.java @@ -1,127 +1,127 @@ -package org.pitest.plugin.export; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.nio.file.FileSystem; -import java.nio.file.Path; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.bytecode.analysis.ClassTree; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.GregorMutater; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.mutationtest.engine.gregor.config.Mutator; - -import com.google.common.jimfs.Configuration; -import com.google.common.jimfs.Jimfs; - -public class MutantExportInterceptorTest { - - ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); - MutantExportInterceptor testee; - FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); - GregorMutater mutator; - - @Before - public void setUp() { - final Collection mutators = Mutator.defaults(); - this.mutator = new GregorMutater(this.source, m -> true, mutators); - this.testee = new MutantExportInterceptor(this.fileSystem, this.source, "target"); - } - - @Test - public void shouldCreateAMutantsDirectoryForEachClass() { - this.testee.begin(tree(Foo.class)); - this.testee.begin(tree(String.class)); - assertThat(this.fileSystem.getPath("target", "export", "org", "pitest", "plugin", "export", "Foo", "mutants")).exists(); - assertThat(this.fileSystem.getPath("target", "export", "java", "lang", "String", "mutants")).exists(); - } - - @Test - public void shouldReturnMutantListUnmodified() { - final Collection mutations = this.mutator.findMutations(ClassName.fromClass(VeryMutable.class)); - - this.testee.begin(tree(VeryMutable.class)); - final Collection actual = this.testee.intercept(mutations, this.mutator); - this.testee.end(); - - assertThat(actual).isSameAs(mutations); - } - - @Test - public void shouldWriteMutantBytesToDisk() { - final Collection mutations = executeFor(VeryMutable.class); - - final Mutant firstMutant = this.mutator.getMutation(mutations.iterator().next().getId()); - final Path shouldBeCreated = mutantBasePath(VeryMutable.class,0).resolve(ClassName.fromClass(VeryMutable.class).asJavaName() + ".class"); - assertThat(shouldBeCreated).hasBinaryContent(firstMutant.getBytes()); - } - - @Test - public void shouldWriteMutantDetailsToDisk() { - final Collection mutations = executeFor(VeryMutable.class); - - final MutationDetails firstMutant = mutations.iterator().next(); - final Path shouldBeCreated = mutantBasePath(VeryMutable.class,0).resolve("details.txt"); - assertThat(shouldBeCreated).hasContent(firstMutant.toString()); - } - - @Test - public void shouldWriteDissasembledMutantBytecodeToDisk() { - executeFor(VeryMutable.class); - final Path shouldBeCreated = mutantBasePath(VeryMutable.class,0).resolve(ClassName.fromClass(VeryMutable.class).asJavaName() + ".txt"); - assertThat(shouldBeCreated).exists(); - } - - - @Test - public void shouldWriteDisassembledOriginalBytecodeToDisk() { - executeFor(VeryMutable.class); - final Path shouldBeCreated = classBasePath(VeryMutable.class).resolve(ClassName.fromClass(VeryMutable.class).asJavaName() + ".txt"); - assertThat(shouldBeCreated).exists(); - } - - - private Collection executeFor(Class clazz) { - final Collection mutations = this.mutator.findMutations(ClassName.fromClass(clazz)); - - this.testee.begin(tree(VeryMutable.class)); - this.testee.intercept(mutations, this.mutator); - this.testee.end(); - return mutations; - } - - - private ClassTree tree(Class clazz) { - return ClassTree.fromBytes(this.source.getBytes(clazz.getName()).get()); - } - - private Path mutantBasePath(Class clazz, int mutant) { - return classBasePath(clazz).resolve("mutants").resolve(""+ mutant); - } - - private Path classBasePath(Class clazz) { - final ClassName name = ClassName.fromClass(clazz); - return this.fileSystem.getPath("target/export",name.asInternalName().split("/")); - } -} - - -class Foo { - -} - - -class VeryMutable { - public int foo(int i) { - for (int y = 0; y != i; y++) { - System.out.println("" + (i * y)); - } - return i + 2; - } +package org.pitest.plugin.export; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.file.FileSystem; +import java.nio.file.Path; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.GregorMutater; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.mutationtest.engine.gregor.config.Mutator; + +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; + +public class MutantExportInterceptorTest { + + ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext(); + MutantExportInterceptor testee; + FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); + GregorMutater mutator; + + @Before + public void setUp() { + final Collection mutators = Mutator.defaults(); + this.mutator = new GregorMutater(this.source, m -> true, mutators); + this.testee = new MutantExportInterceptor(this.fileSystem, this.source, "target"); + } + + @Test + public void shouldCreateAMutantsDirectoryForEachClass() { + this.testee.begin(tree(Foo.class)); + this.testee.begin(tree(String.class)); + assertThat(this.fileSystem.getPath("target", "export", "org", "pitest", "plugin", "export", "Foo", "mutants")).exists(); + assertThat(this.fileSystem.getPath("target", "export", "java", "lang", "String", "mutants")).exists(); + } + + @Test + public void shouldReturnMutantListUnmodified() { + final Collection mutations = this.mutator.findMutations(ClassName.fromClass(VeryMutable.class)); + + this.testee.begin(tree(VeryMutable.class)); + final Collection actual = this.testee.intercept(mutations, this.mutator); + this.testee.end(); + + assertThat(actual).isSameAs(mutations); + } + + @Test + public void shouldWriteMutantBytesToDisk() { + final Collection mutations = executeFor(VeryMutable.class); + + final Mutant firstMutant = this.mutator.getMutation(mutations.iterator().next().getId()); + final Path shouldBeCreated = mutantBasePath(VeryMutable.class,0).resolve(ClassName.fromClass(VeryMutable.class).asJavaName() + ".class"); + assertThat(shouldBeCreated).hasBinaryContent(firstMutant.getBytes()); + } + + @Test + public void shouldWriteMutantDetailsToDisk() { + final Collection mutations = executeFor(VeryMutable.class); + + final MutationDetails firstMutant = mutations.iterator().next(); + final Path shouldBeCreated = mutantBasePath(VeryMutable.class,0).resolve("details.txt"); + assertThat(shouldBeCreated).hasContent(firstMutant.toString()); + } + + @Test + public void shouldWriteDissasembledMutantBytecodeToDisk() { + executeFor(VeryMutable.class); + final Path shouldBeCreated = mutantBasePath(VeryMutable.class,0).resolve(ClassName.fromClass(VeryMutable.class).asJavaName() + ".txt"); + assertThat(shouldBeCreated).exists(); + } + + + @Test + public void shouldWriteDisassembledOriginalBytecodeToDisk() { + executeFor(VeryMutable.class); + final Path shouldBeCreated = classBasePath(VeryMutable.class).resolve(ClassName.fromClass(VeryMutable.class).asJavaName() + ".txt"); + assertThat(shouldBeCreated).exists(); + } + + + private Collection executeFor(Class clazz) { + final Collection mutations = this.mutator.findMutations(ClassName.fromClass(clazz)); + + this.testee.begin(tree(VeryMutable.class)); + this.testee.intercept(mutations, this.mutator); + this.testee.end(); + return mutations; + } + + + private ClassTree tree(Class clazz) { + return ClassTree.fromBytes(this.source.getBytes(clazz.getName()).get()); + } + + private Path mutantBasePath(Class clazz, int mutant) { + return classBasePath(clazz).resolve("mutants").resolve(""+ mutant); + } + + private Path classBasePath(Class clazz) { + final ClassName name = ClassName.fromClass(clazz); + return this.fileSystem.getPath("target/export",name.asInternalName().split("/")); + } +} + + +class Foo { + +} + + +class VeryMutable { + public int foo(int i) { + for (int y = 0; y != i; y++) { + System.out.println("" + (i * y)); + } + return i + 2; + } } \ No newline at end of file diff --git a/pitest-entry/src/test/java/org/pitest/process/KnownLocationJavaExecutableLocatorTest.java b/pitest-entry/src/test/java/org/pitest/process/KnownLocationJavaExecutableLocatorTest.java index dc589a9d6..ce6610c8d 100644 --- a/pitest-entry/src/test/java/org/pitest/process/KnownLocationJavaExecutableLocatorTest.java +++ b/pitest-entry/src/test/java/org/pitest/process/KnownLocationJavaExecutableLocatorTest.java @@ -1,15 +1,15 @@ -package org.pitest.process; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class KnownLocationJavaExecutableLocatorTest { - - @Test - public void shouldReturnWrappedLocation() { - assertEquals("foo", - new KnownLocationJavaExecutableLocator("foo").javaExecutable()); - } - -} +package org.pitest.process; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class KnownLocationJavaExecutableLocatorTest { + + @Test + public void shouldReturnWrappedLocation() { + assertEquals("foo", + new KnownLocationJavaExecutableLocator("foo").javaExecutable()); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/process/WrappingProcessTest.java b/pitest-entry/src/test/java/org/pitest/process/WrappingProcessTest.java index 6292502cd..318abe452 100644 --- a/pitest-entry/src/test/java/org/pitest/process/WrappingProcessTest.java +++ b/pitest-entry/src/test/java/org/pitest/process/WrappingProcessTest.java @@ -1,60 +1,60 @@ -package org.pitest.process; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; - -import org.junit.Test; -import org.pitest.classpath.ClassPath; -import org.pitest.functional.SideEffect1; -import org.pitest.util.NullJavaAgent; - -public class WrappingProcessTest { - - private static final int EXIT_CODE = 10; - - public static void main(final String[] args) { - try { - System.out.println("Sleeping"); - Thread.sleep(100); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - System.out.println("Exiting"); - System.exit(EXIT_CODE); - } - - @Test - public void waitToDieShouldReturnProcessExitCode() throws IOException, - InterruptedException { - - final LaunchOptions launchOptions = new LaunchOptions(NullJavaAgent.instance(), - new DefaultJavaExecutableLocator(), Collections. emptyList(), - new HashMap()); - - final ProcessArgs processArgs = ProcessArgs - .withClassPath(new ClassPath().getLocalClassPath()) - .andBaseDir(new File(System.getProperty("user.dir"))) - .andLaunchOptions(launchOptions).andStdout(nullHandler()) - .andStderr(nullHandler()); - - final WrappingProcess wrappingProcess = new WrappingProcess(-1, processArgs, - getClass()); - wrappingProcess.start(); - final JavaProcess process = wrappingProcess.getProcess(); - - assertTrue(process.isAlive()); - assertEquals(EXIT_CODE, process.waitToDie()); - } - - private SideEffect1 nullHandler() { - return a -> { - - }; - } - -} +package org.pitest.process; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; + +import org.junit.Test; +import org.pitest.classpath.ClassPath; +import org.pitest.functional.SideEffect1; +import org.pitest.util.NullJavaAgent; + +public class WrappingProcessTest { + + private static final int EXIT_CODE = 10; + + public static void main(final String[] args) { + try { + System.out.println("Sleeping"); + Thread.sleep(100); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Exiting"); + System.exit(EXIT_CODE); + } + + @Test + public void waitToDieShouldReturnProcessExitCode() throws IOException, + InterruptedException { + + final LaunchOptions launchOptions = new LaunchOptions(NullJavaAgent.instance(), + new DefaultJavaExecutableLocator(), Collections. emptyList(), + new HashMap()); + + final ProcessArgs processArgs = ProcessArgs + .withClassPath(new ClassPath().getLocalClassPath()) + .andBaseDir(new File(System.getProperty("user.dir"))) + .andLaunchOptions(launchOptions).andStdout(nullHandler()) + .andStderr(nullHandler()); + + final WrappingProcess wrappingProcess = new WrappingProcess(-1, processArgs, + getClass()); + wrappingProcess.start(); + final JavaProcess process = wrappingProcess.getProcess(); + + assertTrue(process.isAlive()); + assertEquals(EXIT_CODE, process.waitToDie()); + } + + private SideEffect1 nullHandler() { + return a -> { + + }; + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/util/NullJavaAgent.java b/pitest-entry/src/test/java/org/pitest/util/NullJavaAgent.java index f49b1b809..2850cc081 100644 --- a/pitest-entry/src/test/java/org/pitest/util/NullJavaAgent.java +++ b/pitest-entry/src/test/java/org/pitest/util/NullJavaAgent.java @@ -1,35 +1,35 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import java.util.Optional; -import org.pitest.process.JavaAgent; - -public class NullJavaAgent implements JavaAgent { - - public static NullJavaAgent instance() { - return new NullJavaAgent(); - } - - @Override - public Optional getJarLocation() { - return Optional.empty(); - } - - @Override - public void close() { - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import java.util.Optional; +import org.pitest.process.JavaAgent; + +public class NullJavaAgent implements JavaAgent { + + public static NullJavaAgent instance() { + return new NullJavaAgent(); + } + + @Override + public Optional getJarLocation() { + return Optional.empty(); + } + + @Override + public void close() { + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/util/SocketFinderTest.java b/pitest-entry/src/test/java/org/pitest/util/SocketFinderTest.java index 25bc4f089..4b6bdf3d5 100644 --- a/pitest-entry/src/test/java/org/pitest/util/SocketFinderTest.java +++ b/pitest-entry/src/test/java/org/pitest/util/SocketFinderTest.java @@ -1,41 +1,41 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.net.ServerSocket; - -import org.junit.Before; -import org.junit.Test; - -public class SocketFinderTest { - - private SocketFinder testee; - - @Before - public void setUp() { - this.testee = new SocketFinder(); - } - - @Test - public void shouldFindAvailableSockets() throws IOException { - final ServerSocket socket = this.testee.getNextAvailableServerSocket(); - assertTrue(socket != null); - socket.close(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.ServerSocket; + +import org.junit.Before; +import org.junit.Test; + +public class SocketFinderTest { + + private SocketFinder testee; + + @Before + public void setUp() { + this.testee = new SocketFinder(); + } + + @Test + public void shouldFindAvailableSockets() throws IOException { + final ServerSocket socket = this.testee.getNextAvailableServerSocket(); + assertTrue(socket != null); + socket.close(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/util/SocketReadingCallableTest.java b/pitest-entry/src/test/java/org/pitest/util/SocketReadingCallableTest.java index fb8a73661..8c7232241 100644 --- a/pitest-entry/src/test/java/org/pitest/util/SocketReadingCallableTest.java +++ b/pitest-entry/src/test/java/org/pitest/util/SocketReadingCallableTest.java @@ -1,99 +1,99 @@ -package org.pitest.util; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyByte; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.functional.SideEffect1; - -public class SocketReadingCallableTest { - - private SocketReadingCallable testee; - - @Mock - private ServerSocket socket; - - @Mock - private SideEffect1 sendDataSideEffect; - - @Mock - private ReceiveStrategy receiveStrategy; - - @Mock - private Socket clientSocket; - - private ByteArrayOutputStream o; - - @Before - public void setUp() throws IOException { - MockitoAnnotations.initMocks(this); - this.testee = new SocketReadingCallable(this.socket, - this.sendDataSideEffect, this.receiveStrategy); - - when(this.socket.accept()).thenReturn(this.clientSocket); - - this.o = new ByteArrayOutputStream(); - } - - @Test - public void shouldReportTheExitCodeSentByTheMinionProcess() throws Exception { - mockClientSocketToSendExitCode(ExitCode.TIMEOUT); - assertEquals(ExitCode.TIMEOUT, this.testee.call()); - } - - @Test - public void shouldSendInitialDataToMinion() throws Exception { - mockClientSocketToSendExitCode(ExitCode.TIMEOUT); - this.testee.call(); - verify(this.sendDataSideEffect).apply(any(SafeDataOutputStream.class)); - } - - @Test - public void shouldPassNotPassDoneCommandToReceiver() throws Exception { - mockClientSocketToSendExitCode(ExitCode.TIMEOUT); - this.testee.call(); - verify(this.receiveStrategy, never()).apply(anyByte(), - any(SafeDataInputStream.class)); - } - - @Test - public void shouldPassCommandsToReceiver() throws Exception { - final SafeDataOutputStream dos = new SafeDataOutputStream(this.o); - dos.writeByte(Id.DESCRIBE); - dos.writeByte(Id.DONE); - dos.writeInt(ExitCode.OK.getCode()); - mockClientSocketInputStream(); - this.testee.call(); - verify(this.receiveStrategy, times(1)).apply(anyByte(), - any(SafeDataInputStream.class)); - } - - private void mockClientSocketInputStream() throws IOException { - final ByteArrayInputStream bis = new ByteArrayInputStream( - this.o.toByteArray()); - when(this.clientSocket.getInputStream()).thenReturn(bis); - } - - private void mockClientSocketToSendExitCode(final ExitCode timeout) - throws IOException { - final SafeDataOutputStream dos = new SafeDataOutputStream(this.o); - dos.writeByte(Id.DONE); - dos.writeInt(timeout.getCode()); - mockClientSocketInputStream(); - } - -} +package org.pitest.util; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyByte; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.functional.SideEffect1; + +public class SocketReadingCallableTest { + + private SocketReadingCallable testee; + + @Mock + private ServerSocket socket; + + @Mock + private SideEffect1 sendDataSideEffect; + + @Mock + private ReceiveStrategy receiveStrategy; + + @Mock + private Socket clientSocket; + + private ByteArrayOutputStream o; + + @Before + public void setUp() throws IOException { + MockitoAnnotations.initMocks(this); + this.testee = new SocketReadingCallable(this.socket, + this.sendDataSideEffect, this.receiveStrategy); + + when(this.socket.accept()).thenReturn(this.clientSocket); + + this.o = new ByteArrayOutputStream(); + } + + @Test + public void shouldReportTheExitCodeSentByTheMinionProcess() throws Exception { + mockClientSocketToSendExitCode(ExitCode.TIMEOUT); + assertEquals(ExitCode.TIMEOUT, this.testee.call()); + } + + @Test + public void shouldSendInitialDataToMinion() throws Exception { + mockClientSocketToSendExitCode(ExitCode.TIMEOUT); + this.testee.call(); + verify(this.sendDataSideEffect).apply(any(SafeDataOutputStream.class)); + } + + @Test + public void shouldPassNotPassDoneCommandToReceiver() throws Exception { + mockClientSocketToSendExitCode(ExitCode.TIMEOUT); + this.testee.call(); + verify(this.receiveStrategy, never()).apply(anyByte(), + any(SafeDataInputStream.class)); + } + + @Test + public void shouldPassCommandsToReceiver() throws Exception { + final SafeDataOutputStream dos = new SafeDataOutputStream(this.o); + dos.writeByte(Id.DESCRIBE); + dos.writeByte(Id.DONE); + dos.writeInt(ExitCode.OK.getCode()); + mockClientSocketInputStream(); + this.testee.call(); + verify(this.receiveStrategy, times(1)).apply(anyByte(), + any(SafeDataInputStream.class)); + } + + private void mockClientSocketInputStream() throws IOException { + final ByteArrayInputStream bis = new ByteArrayInputStream( + this.o.toByteArray()); + when(this.clientSocket.getInputStream()).thenReturn(bis); + } + + private void mockClientSocketToSendExitCode(final ExitCode timeout) + throws IOException { + final SafeDataOutputStream dos = new SafeDataOutputStream(this.o); + dos.writeByte(Id.DONE); + dos.writeInt(timeout.getCode()); + mockClientSocketInputStream(); + } + +} diff --git a/pitest-entry/src/test/java/org/pitest/util/TimeSpanTest.java b/pitest-entry/src/test/java/org/pitest/util/TimeSpanTest.java index 0c3023d8d..2002a3d6a 100644 --- a/pitest-entry/src/test/java/org/pitest/util/TimeSpanTest.java +++ b/pitest-entry/src/test/java/org/pitest/util/TimeSpanTest.java @@ -1,44 +1,44 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class TimeSpanTest { - - @Test - public void shouldReportTimesAsLessThanOneSecondWhenLessThanOneSecond() { - assertEquals("< 1 second", new TimeSpan(0, 999).toString()); - } - - @Test - public void shouldReportTimesInSecondsWhenLessThenOneMinute() { - assertEquals("59 seconds", new TimeSpan(0, 59 * 1000).toString()); - } - - @Test - public void shouldReportTimesInMinutesWhenMoreThanOneMinute() { - assertEquals("1 minutes and 1 seconds", - new TimeSpan(0, (61 * 1000)).toString()); - } - - @Test - public void shouldReportTimesInHoursWhenMoreThanOneHour() { - assertEquals("1 hours, 2 minutes and 1 seconds", new TimeSpan(0, - (1000 * 60 * 60) + (121 * 1000)).toString()); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class TimeSpanTest { + + @Test + public void shouldReportTimesAsLessThanOneSecondWhenLessThanOneSecond() { + assertEquals("< 1 second", new TimeSpan(0, 999).toString()); + } + + @Test + public void shouldReportTimesInSecondsWhenLessThenOneMinute() { + assertEquals("59 seconds", new TimeSpan(0, 59 * 1000).toString()); + } + + @Test + public void shouldReportTimesInMinutesWhenMoreThanOneMinute() { + assertEquals("1 minutes and 1 seconds", + new TimeSpan(0, (61 * 1000)).toString()); + } + + @Test + public void shouldReportTimesInHoursWhenMoreThanOneHour() { + assertEquals("1 hours, 2 minutes and 1 seconds", new TimeSpan(0, + (1000 * 60 * 60) + (121 * 1000)).toString()); + } +} diff --git a/pitest-groovy-verification/pom.xml b/pitest-groovy-verification/pom.xml index a93dd3a45..d530af7f3 100644 --- a/pitest-groovy-verification/pom.xml +++ b/pitest-groovy-verification/pom.xml @@ -1,133 +1,133 @@ - - - 4.0.0 - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - pitest-groovy-verification - jar - pitest-groovy-verification - tests for pit groovy integration - http://pitest.org - - - - - - - - maven-deploy-plugin - - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - - groovy-eclipse-compiler - 1.7 - 1.7 - - **/*.groovy - **/*.java - - - **/*.groovy - **/*.java - - - - - org.codehaus.groovy - groovy-eclipse-compiler - 2.7.0-01 - - - org.codehaus.groovy - groovy-eclipse-batch - - - - - org.codehaus.groovy - groovy-eclipse-batch - 2.4.3-01 - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.9.1 - - - add-source - generate-sources - - add-source - - - - src/main/groovy - - - - - add-test-source - generate-test-sources - - add-test-source - - - - src/test/groovy - - - - - - - - - - - - org.pitest - pitest - ${project.version} - - - org.codehaus.groovy - groovy-all - 2.4.12 - - - junit - junit - ${junit.version} - test - - - org.spockframework - spock-core - 1.1-groovy-2.4 - test - - - org.codehaus.groovy - groovy-all - - - junit - junit-dep - - - - - - - + + + 4.0.0 + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + pitest-groovy-verification + jar + pitest-groovy-verification + tests for pit groovy integration + http://pitest.org + + + + + + + + maven-deploy-plugin + + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + + groovy-eclipse-compiler + 1.7 + 1.7 + + **/*.groovy + **/*.java + + + **/*.groovy + **/*.java + + + + + org.codehaus.groovy + groovy-eclipse-compiler + 2.7.0-01 + + + org.codehaus.groovy + groovy-eclipse-batch + + + + + org.codehaus.groovy + groovy-eclipse-batch + 2.4.3-01 + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/main/groovy + + + + + add-test-source + generate-test-sources + + add-test-source + + + + src/test/groovy + + + + + + + + + + + + org.pitest + pitest + ${project.version} + + + org.codehaus.groovy + groovy-all + 2.4.12 + + + junit + junit + ${junit.version} + test + + + org.spockframework + spock-core + 1.1-groovy-2.4 + test + + + org.codehaus.groovy + groovy-all + + + junit + junit-dep + + + + + + + diff --git a/pitest-groovy-verification/src/test/groovy/com/example/spock/ParametrizedSpockTest.groovy b/pitest-groovy-verification/src/test/groovy/com/example/spock/ParametrizedSpockTest.groovy index b19e0e522..1b5339139 100644 --- a/pitest-groovy-verification/src/test/groovy/com/example/spock/ParametrizedSpockTest.groovy +++ b/pitest-groovy-verification/src/test/groovy/com/example/spock/ParametrizedSpockTest.groovy @@ -1,23 +1,23 @@ -package com.example.spock - -import groovy.transform.TypeChecked -import spock.lang.Specification -import spock.lang.Unroll - -@TypeChecked -class ParametrizedSpockTest extends Specification{ - - def testDummyForPit = new TestDummyForPit() - - @Unroll - def "should get list of lengths for given strings"(int input, int expectedResult) { - expect: - testDummyForPit.returnParametrizedSpock(input) == expectedResult - - where: - input | expectedResult - 1 | 1 - 2 | 2 - 3 | 3 - } -} +package com.example.spock + +import groovy.transform.TypeChecked +import spock.lang.Specification +import spock.lang.Unroll + +@TypeChecked +class ParametrizedSpockTest extends Specification{ + + def testDummyForPit = new TestDummyForPit() + + @Unroll + def "should get list of lengths for given strings"(int input, int expectedResult) { + expect: + testDummyForPit.returnParametrizedSpock(input) == expectedResult + + where: + input | expectedResult + 1 | 1 + 2 | 2 + 3 | 3 + } +} diff --git a/pitest-groovy-verification/src/test/groovy/com/example/spock/SpockTest.groovy b/pitest-groovy-verification/src/test/groovy/com/example/spock/SpockTest.groovy index 97cbb1582..0105587ee 100644 --- a/pitest-groovy-verification/src/test/groovy/com/example/spock/SpockTest.groovy +++ b/pitest-groovy-verification/src/test/groovy/com/example/spock/SpockTest.groovy @@ -1,19 +1,19 @@ -package com.example.spock - -import groovy.transform.TypeChecked -import spock.lang.Specification - -@TypeChecked -class SpockTest extends Specification { - - def "should generate coverage for return3Spock method in TestDummyForPit"() { - given: - def testDummyForPit = new TestDummyForPit() - - when: - int result = testDummyForPit.return3Spock() - - then: - assert result == 3 - } -} +package com.example.spock + +import groovy.transform.TypeChecked +import spock.lang.Specification + +@TypeChecked +class SpockTest extends Specification { + + def "should generate coverage for return3Spock method in TestDummyForPit"() { + given: + def testDummyForPit = new TestDummyForPit() + + when: + int result = testDummyForPit.return3Spock() + + then: + assert result == 3 + } +} diff --git a/pitest-groovy-verification/src/test/java/com/example/spock/TestDummyForPit.java b/pitest-groovy-verification/src/test/java/com/example/spock/TestDummyForPit.java index 009ac969a..9abbc0ee6 100644 --- a/pitest-groovy-verification/src/test/java/com/example/spock/TestDummyForPit.java +++ b/pitest-groovy-verification/src/test/java/com/example/spock/TestDummyForPit.java @@ -1,28 +1,28 @@ -package com.example.spock; - -public class TestDummyForPit { - - public int return1Junit() { - return 1; - } - - public int return2TestNG() { - return 2; - } - - public int return3Spock() { - return 3; - } - - public int returnParametrizedSpock(int input) { - return input; - } - - public int returnParametrizedTestNG(int input) { - return input; - } - - public int returnJUnitParams(int input) { - return input; - } -} +package com.example.spock; + +public class TestDummyForPit { + + public int return1Junit() { + return 1; + } + + public int return2TestNG() { + return 2; + } + + public int return3Spock() { + return 3; + } + + public int returnParametrizedSpock(int input) { + return input; + } + + public int returnParametrizedTestNG(int input) { + return input; + } + + public int returnJUnitParams(int input) { + return input; + } +} diff --git a/pitest-groovy-verification/src/test/java/org/pitest/groovy/verification/TestJUnitConfigurationForSpock.java b/pitest-groovy-verification/src/test/java/org/pitest/groovy/verification/TestJUnitConfigurationForSpock.java index 5892451fb..4b2efccc0 100644 --- a/pitest-groovy-verification/src/test/java/org/pitest/groovy/verification/TestJUnitConfigurationForSpock.java +++ b/pitest-groovy-verification/src/test/java/org/pitest/groovy/verification/TestJUnitConfigurationForSpock.java @@ -1,56 +1,56 @@ -package org.pitest.groovy.verification; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.util.Collections; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.testapi.execute.Container; -import org.pitest.testapi.execute.Pitest; -import org.pitest.testapi.execute.containers.UnContainer; -import org.pitest.junit.JUnitCompatibleConfiguration; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.testapi.TestListener; -import org.pitest.testapi.TestResult; - -import com.example.spock.SpockTest; -import com.example.spock.ParametrizedSpockTest; - -public class TestJUnitConfigurationForSpock { - - private final JUnitCompatibleConfiguration testee = new JUnitCompatibleConfiguration(new TestGroupConfig(), - Collections.emptyList(), Collections.emptyList()); - private Pitest pitest; - private Container container; - - @Mock - private TestListener listener; - - @Before - public void createTestee() { - MockitoAnnotations.initMocks(this); - this.container = new UnContainer(); - this.pitest = new Pitest(this.listener); - } - - @Test - public void shouldFindTestInSpockTest() { - run(SpockTest.class); - verify(this.listener, times(1)).onTestSuccess(any(TestResult.class)); - } - - @Test - public void shouldFindTestsInParameterisedSpockTest() { - run(ParametrizedSpockTest.class); - verify(this.listener, times(3)).onTestSuccess(any(TestResult.class)); - } - - private void run(final Class clazz) { - this.pitest.run(this.container, this.testee, clazz); - } - -} +package org.pitest.groovy.verification; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.Collections; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.testapi.execute.Container; +import org.pitest.testapi.execute.Pitest; +import org.pitest.testapi.execute.containers.UnContainer; +import org.pitest.junit.JUnitCompatibleConfiguration; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.testapi.TestListener; +import org.pitest.testapi.TestResult; + +import com.example.spock.SpockTest; +import com.example.spock.ParametrizedSpockTest; + +public class TestJUnitConfigurationForSpock { + + private final JUnitCompatibleConfiguration testee = new JUnitCompatibleConfiguration(new TestGroupConfig(), + Collections.emptyList(), Collections.emptyList()); + private Pitest pitest; + private Container container; + + @Mock + private TestListener listener; + + @Before + public void createTestee() { + MockitoAnnotations.initMocks(this); + this.container = new UnContainer(); + this.pitest = new Pitest(this.listener); + } + + @Test + public void shouldFindTestInSpockTest() { + run(SpockTest.class); + verify(this.listener, times(1)).onTestSuccess(any(TestResult.class)); + } + + @Test + public void shouldFindTestsInParameterisedSpockTest() { + run(ParametrizedSpockTest.class); + verify(this.listener, times(3)).onTestSuccess(any(TestResult.class)); + } + + private void run(final Class clazz) { + this.pitest.run(this.container, this.testee, clazz); + } + +} diff --git a/pitest-html-report/pom.xml b/pitest-html-report/pom.xml index 82d432ae4..5f1bea599 100644 --- a/pitest-html-report/pom.xml +++ b/pitest-html-report/pom.xml @@ -1,104 +1,104 @@ - - - - 4.0.0 - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - pitest-html-report - pitest-html-report - http://pitest.org - Pitest html report plugin. - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - org.pitest.mutationtest.commandline.MutationCoverageReport - true - - true - - - - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - - - org.antlr:* - antlr:* - - - - - - - - org.antlr - org.pitest.reloc.antlr - - - antlr - org.pitest.reloc.antlr.common - - - - - - - - - - - - - - - - org.pitest - pitest-entry - ${project.version} - - - org.antlr - stringtemplate - 3.2.1 - - - org.pitest - pitest-entry - ${project.version} - test-jar - test - - - org.pitest - pitest - ${project.version} - test-jar - test - - - - - - - + + + + 4.0.0 + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + pitest-html-report + pitest-html-report + http://pitest.org + Pitest html report plugin. + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.pitest.mutationtest.commandline.MutationCoverageReport + true + + true + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + org.antlr:* + antlr:* + + + + + + + + org.antlr + org.pitest.reloc.antlr + + + antlr + org.pitest.reloc.antlr.common + + + + + + + + + + + + + + + + org.pitest + pitest-entry + ${project.version} + + + org.antlr + stringtemplate + 3.2.1 + + + org.pitest + pitest-entry + ${project.version} + test-jar + test + + + org.pitest + pitest + ${project.version} + test-jar + test + + + + + + + diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/AnnotatedLineFactory.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/AnnotatedLineFactory.java index 8bdb9214f..1c17f5654 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/AnnotatedLineFactory.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/AnnotatedLineFactory.java @@ -1,106 +1,106 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import java.io.IOException; -import java.io.Reader; -import java.util.Collection; -import java.util.List; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.pitest.classinfo.ClassInfo; -import org.pitest.coverage.ClassLine; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.MutationResult; -import org.pitest.util.StringUtil; - -public class AnnotatedLineFactory { - - private final Collection mutations; - private final CoverageDatabase statistics; - private final Collection classesInFile; - - public AnnotatedLineFactory( - final Collection mutations, - final CoverageDatabase statistics, final Collection classes) { - this.mutations = mutations; - this.statistics = statistics; - this.classesInFile = classes; - } - - public List convert(final Reader source) throws IOException { - try { - final InputStreamLineIterable lines = new InputStreamLineIterable(source); - return FCollection.map(lines, stringToAnnotatedLine()); - } finally { - source.close(); - } - - } - - private Function stringToAnnotatedLine() { - return new Function() { - private int lineNumber = 1; - - @Override - public Line apply(final String a) { - final Line l = new Line(this.lineNumber, - StringUtil.escapeBasicHtmlChars(a), lineCovered(this.lineNumber), - getMutationsForLine(this.lineNumber)); - this.lineNumber++; - return l; - } - - }; - } - - private List getMutationsForLine(final int lineNumber) { - return this.mutations.stream() - .filter(isAtLineNumber(lineNumber)) - .collect(Collectors.toList()); - } - - private Predicate isAtLineNumber(final int lineNumber) { - return result -> result.getDetails().getLineNumber() == lineNumber; - } - - private LineStatus lineCovered(final int line) { - - if (!isCodeLine(line)) { - return LineStatus.NotApplicable; - } else { - if (isLineCovered(line)) { - return LineStatus.Covered; - } else { - return LineStatus.NotCovered; - } - } - } - - private boolean isCodeLine(final int line) { - return FCollection.contains(this.classesInFile, a -> a.isCodeLine(line)); - } - - private boolean isLineCovered(final int line) { - final Predicate predicate = a -> !AnnotatedLineFactory.this.statistics.getTestsForClassLine( - new ClassLine(a.getName().asInternalName(), line)).isEmpty(); - return FCollection.contains(this.classesInFile, predicate); - - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import java.io.IOException; +import java.io.Reader; +import java.util.Collection; +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.pitest.classinfo.ClassInfo; +import org.pitest.coverage.ClassLine; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.MutationResult; +import org.pitest.util.StringUtil; + +public class AnnotatedLineFactory { + + private final Collection mutations; + private final CoverageDatabase statistics; + private final Collection classesInFile; + + public AnnotatedLineFactory( + final Collection mutations, + final CoverageDatabase statistics, final Collection classes) { + this.mutations = mutations; + this.statistics = statistics; + this.classesInFile = classes; + } + + public List convert(final Reader source) throws IOException { + try { + final InputStreamLineIterable lines = new InputStreamLineIterable(source); + return FCollection.map(lines, stringToAnnotatedLine()); + } finally { + source.close(); + } + + } + + private Function stringToAnnotatedLine() { + return new Function() { + private int lineNumber = 1; + + @Override + public Line apply(final String a) { + final Line l = new Line(this.lineNumber, + StringUtil.escapeBasicHtmlChars(a), lineCovered(this.lineNumber), + getMutationsForLine(this.lineNumber)); + this.lineNumber++; + return l; + } + + }; + } + + private List getMutationsForLine(final int lineNumber) { + return this.mutations.stream() + .filter(isAtLineNumber(lineNumber)) + .collect(Collectors.toList()); + } + + private Predicate isAtLineNumber(final int lineNumber) { + return result -> result.getDetails().getLineNumber() == lineNumber; + } + + private LineStatus lineCovered(final int line) { + + if (!isCodeLine(line)) { + return LineStatus.NotApplicable; + } else { + if (isLineCovered(line)) { + return LineStatus.Covered; + } else { + return LineStatus.NotCovered; + } + } + } + + private boolean isCodeLine(final int line) { + return FCollection.contains(this.classesInFile, a -> a.isCodeLine(line)); + } + + private boolean isLineCovered(final int line) { + final Predicate predicate = a -> !AnnotatedLineFactory.this.statistics.getTestsForClassLine( + new ClassLine(a.getName().asInternalName(), line)).isEmpty(); + return FCollection.contains(this.classesInFile, predicate); + + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/ConfidenceMap.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/ConfidenceMap.java index 5534907f8..3ef52166a 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/ConfidenceMap.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/ConfidenceMap.java @@ -1,19 +1,19 @@ -package org.pitest.mutationtest.report.html; - -import java.util.EnumSet; - -import org.pitest.mutationtest.DetectionStatus; - -class ConfidenceMap { - - private static final EnumSet HIGH = EnumSet - .of(DetectionStatus.KILLED, - DetectionStatus.SURVIVED, - DetectionStatus.NO_COVERAGE, - DetectionStatus.NON_VIABLE); - - public static boolean hasHighConfidence(final DetectionStatus status) { - return HIGH.contains(status); - } - -} +package org.pitest.mutationtest.report.html; + +import java.util.EnumSet; + +import org.pitest.mutationtest.DetectionStatus; + +class ConfidenceMap { + + private static final EnumSet HIGH = EnumSet + .of(DetectionStatus.KILLED, + DetectionStatus.SURVIVED, + DetectionStatus.NO_COVERAGE, + DetectionStatus.NON_VIABLE); + + public static boolean hasHighConfidence(final DetectionStatus status) { + return HIGH.contains(status); + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/HtmlReportFactory.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/HtmlReportFactory.java index f7d2b13b3..caa6a4665 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/HtmlReportFactory.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/HtmlReportFactory.java @@ -1,43 +1,43 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.report.html; - -import java.util.Properties; - -import org.pitest.mutationtest.ListenerArguments; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.MutationResultListenerFactory; - -public class HtmlReportFactory implements MutationResultListenerFactory { - - @Override - public MutationResultListener getListener(Properties props, - ListenerArguments args) { - return new MutationHtmlReportListener(args.getCoverage(), - args.getOutputStrategy(), args.getEngine().getMutatorNames(), - args.getLocator()); - } - - @Override - public String name() { - return "HTML"; - } - - @Override - public String description() { - return "Default html report plugin"; - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.report.html; + +import java.util.Properties; + +import org.pitest.mutationtest.ListenerArguments; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.MutationResultListenerFactory; + +public class HtmlReportFactory implements MutationResultListenerFactory { + + @Override + public MutationResultListener getListener(Properties props, + ListenerArguments args) { + return new MutationHtmlReportListener(args.getCoverage(), + args.getOutputStrategy(), args.getEngine().getMutatorNames(), + args.getLocator()); + } + + @Override + public String name() { + return "HTML"; + } + + @Override + public String description() { + return "Default html report plugin"; + } +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/InputStreamLineIterable.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/InputStreamLineIterable.java index 6627db12b..76732053b 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/InputStreamLineIterable.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/InputStreamLineIterable.java @@ -1,68 +1,68 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.Iterator; - -public class InputStreamLineIterable implements Iterable { - - private final BufferedReader reader; - private String next; - - public InputStreamLineIterable(final Reader reader) { - this.reader = new BufferedReader(reader); - advance(); - } - - private void advance() { - try { - this.next = this.reader.readLine(); - } catch (final IOException e) { - this.next = null; - } - } - - public String next() { - final String t = this.next; - advance(); - return t; - } - - @Override - public Iterator iterator() { - return new Iterator() { - - @Override - public boolean hasNext() { - return InputStreamLineIterable.this.next != null; - } - - @Override - public String next() { - return InputStreamLineIterable.this.next(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - }; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import java.util.Iterator; + +public class InputStreamLineIterable implements Iterable { + + private final BufferedReader reader; + private String next; + + public InputStreamLineIterable(final Reader reader) { + this.reader = new BufferedReader(reader); + advance(); + } + + private void advance() { + try { + this.next = this.reader.readLine(); + } catch (final IOException e) { + this.next = null; + } + } + + public String next() { + final String t = this.next; + advance(); + return t; + } + + @Override + public Iterator iterator() { + return new Iterator() { + + @Override + public boolean hasNext() { + return InputStreamLineIterable.this.next != null; + } + + @Override + public String next() { + return InputStreamLineIterable.this.next(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + }; + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/Line.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/Line.java index d40474201..7fc9b1b56 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/Line.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/Line.java @@ -1,78 +1,78 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import java.util.Collections; -import java.util.List; - -import java.util.Optional; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; - -public class Line { - private final long number; - private final String text; - private final LineStatus lineCovered; - private final List mutations; - - public Line(final long number, final String text, - final LineStatus lineCovered, final List mutations) { - this.number = number; - this.text = text; - this.lineCovered = lineCovered; - this.mutations = mutations; - Collections.sort(mutations, new ResultComparator()); - } - - public long getNumber() { - return this.number; - } - - public String getText() { - return this.text; - } - - public LineStatus getLineCovered() { - return this.lineCovered; - } - - public List getMutations() { - return this.mutations; - } - - public Optional detectionStatus() { - if (this.mutations.isEmpty()) { - return Optional.empty(); - } - return Optional.ofNullable(this.mutations.get(0).getStatus()); - } - - public int getNumberOfMutations() { - return this.mutations.size(); - } - - public String getNumberOfMutationsForDisplay() { - if (getNumberOfMutations() > 0) { - return "" + getNumberOfMutations(); - } else { - return ""; - } - } - - public LineStyle getStyles() { - return new LineStyle(this); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import java.util.Collections; +import java.util.List; + +import java.util.Optional; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; + +public class Line { + private final long number; + private final String text; + private final LineStatus lineCovered; + private final List mutations; + + public Line(final long number, final String text, + final LineStatus lineCovered, final List mutations) { + this.number = number; + this.text = text; + this.lineCovered = lineCovered; + this.mutations = mutations; + Collections.sort(mutations, new ResultComparator()); + } + + public long getNumber() { + return this.number; + } + + public String getText() { + return this.text; + } + + public LineStatus getLineCovered() { + return this.lineCovered; + } + + public List getMutations() { + return this.mutations; + } + + public Optional detectionStatus() { + if (this.mutations.isEmpty()) { + return Optional.empty(); + } + return Optional.ofNullable(this.mutations.get(0).getStatus()); + } + + public int getNumberOfMutations() { + return this.mutations.size(); + } + + public String getNumberOfMutationsForDisplay() { + if (getNumberOfMutations() > 0) { + return "" + getNumberOfMutations(); + } else { + return ""; + } + } + + public LineStyle getStyles() { + return new LineStyle(this); + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/LineStatus.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/LineStatus.java index 17b66f77e..48131f459 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/LineStatus.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/LineStatus.java @@ -1,21 +1,21 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -enum LineStatus { - - Covered, NotCovered, NotApplicable; - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +enum LineStatus { + + Covered, NotCovered, NotApplicable; + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/LineStyle.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/LineStyle.java index 452765ead..b721a7b5a 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/LineStyle.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/LineStyle.java @@ -1,71 +1,71 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import org.pitest.mutationtest.DetectionStatus; - -public class LineStyle { - - private final Line line; - - public LineStyle(final Line line) { - this.line = line; - } - - public String getLineCoverage() { - switch (this.line.getLineCovered()) { - case Covered: - return "covered"; - case NotCovered: - return "uncovered"; - default: - return "na"; - } - } - - public String getCode() { - switch (this.line.getLineCovered()) { - case Covered: - return "covered"; - case NotCovered: - return "uncovered"; - default: - return ""; - } - } - - public String getMutation() { - if (!this.line.detectionStatus().isPresent()) { - return ""; - } - - final DetectionStatus status = this.line.detectionStatus().get(); - if (!status.isDetected()) { - return "survived"; - } - - if (ConfidenceMap.hasHighConfidence(status)) { - return "killed"; - } else { - return "uncertain"; - } - - } - - public String getText() { - return getLineCoverage(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import org.pitest.mutationtest.DetectionStatus; + +public class LineStyle { + + private final Line line; + + public LineStyle(final Line line) { + this.line = line; + } + + public String getLineCoverage() { + switch (this.line.getLineCovered()) { + case Covered: + return "covered"; + case NotCovered: + return "uncovered"; + default: + return "na"; + } + } + + public String getCode() { + switch (this.line.getLineCovered()) { + case Covered: + return "covered"; + case NotCovered: + return "uncovered"; + default: + return ""; + } + } + + public String getMutation() { + if (!this.line.detectionStatus().isPresent()) { + return ""; + } + + final DetectionStatus status = this.line.detectionStatus().get(); + if (!status.isDetected()) { + return "survived"; + } + + if (ConfidenceMap.hasHighConfidence(status)) { + return "killed"; + } else { + return "uncertain"; + } + + } + + public String getText() { + return getLineCoverage(); + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationGrouping.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationGrouping.java index 772c35ae6..dd3f73a7c 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationGrouping.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationGrouping.java @@ -1,46 +1,46 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import java.util.List; - -import org.pitest.mutationtest.MutationResult; - -public class MutationGrouping { - - private final int id; - private final String title; - private final List mutations; - - public MutationGrouping(final int id, final String title, - final List mutations) { - this.title = title; - this.mutations = mutations; - this.id = id; - } - - public String getTitle() { - return this.title; - } - - public List getMutations() { - return this.mutations; - } - - public int getId() { - return this.id; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import java.util.List; + +import org.pitest.mutationtest.MutationResult; + +public class MutationGrouping { + + private final int id; + private final String title; + private final List mutations; + + public MutationGrouping(final int id, final String title, + final List mutations) { + this.title = title; + this.mutations = mutations; + this.id = id; + } + + public String getTitle() { + return this.title; + } + + public List getMutations() { + return this.mutations; + } + + public int getId() { + return this.id; + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationHtmlReportListener.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationHtmlReportListener.java index 298a77d1d..cd949c44c 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationHtmlReportListener.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationHtmlReportListener.java @@ -1,256 +1,256 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.logging.Level; - -import org.antlr.stringtemplate.StringTemplate; -import org.antlr.stringtemplate.StringTemplateGroup; -import org.pitest.classinfo.ClassInfo; -import org.pitest.coverage.CoverageDatabase; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.ClassMutationResults; -import org.pitest.mutationtest.MutationResultListener; -import org.pitest.mutationtest.SourceLocator; -import org.pitest.util.FileUtil; -import org.pitest.util.IsolationUtils; -import org.pitest.util.Log; -import org.pitest.util.ResultOutputStrategy; - -public class MutationHtmlReportListener implements MutationResultListener { - - private final ResultOutputStrategy outputStrategy; - - private final Collection sourceRoots; - - private final PackageSummaryMap packageSummaryData = new PackageSummaryMap(); - private final CoverageDatabase coverage; - private final Set mutatorNames; - - private final String css; - - public MutationHtmlReportListener(final CoverageDatabase coverage, - final ResultOutputStrategy outputStrategy, - Collection mutatorNames, final SourceLocator... locators) { - this.coverage = coverage; - this.outputStrategy = outputStrategy; - this.sourceRoots = new HashSet<>(Arrays.asList(locators)); - this.mutatorNames = new HashSet<>(mutatorNames); - this.css = loadCss(); - } - - private String loadCss() { - try { - return FileUtil.readToString(IsolationUtils.getContextClassLoader() - .getResourceAsStream("templates/mutation/style.css")); - } catch (final IOException e) { - Log.getLogger().log(Level.SEVERE, "Error while loading css", e); - } - return ""; - } - - private void generateAnnotatedSourceFile( - final MutationTestSummaryData mutationMetaData) { - - - final String fileName = mutationMetaData.getPackageName() - + File.separator + mutationMetaData.getFileName() + ".html"; - - try (Writer writer = this.outputStrategy.createWriterForFile(fileName)) { - - final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); - final StringTemplate st = group - .getInstanceOf("templates/mutation/mutation_report"); - st.setAttribute("css", this.css); - - st.setAttribute("tests", mutationMetaData.getTests()); - - st.setAttribute("mutators", mutationMetaData.getMutators()); - - final SourceFile sourceFile = createAnnotatedSourceFile(mutationMetaData); - - st.setAttribute("sourceFile", sourceFile); - st.setAttribute("mutatedClasses", mutationMetaData.getMutatedClasses()); - - writer.write(st.toString()); - - - } catch (final IOException ex) { - Log.getLogger().log(Level.WARNING, "Error while writing report", ex); - } - } - - private PackageSummaryData collectPackageSummaries( - final ClassMutationResults mutationMetaData) { - final String packageName = mutationMetaData.getPackageName(); - - return this.packageSummaryData.update(packageName, - createSummaryData(this.coverage, mutationMetaData)); - } - - public MutationTestSummaryData createSummaryData( - final CoverageDatabase coverage, final ClassMutationResults data) { - return new MutationTestSummaryData(data.getFileName(), data.getMutations(), - this.mutatorNames, coverage.getClassInfo(Collections.singleton(data - .getMutatedClass())), coverage.getNumberOfCoveredLines(Collections - .singleton(data.getMutatedClass()))); - } - - private SourceFile createAnnotatedSourceFile( - final MutationTestSummaryData mutationMetaData) throws IOException { - - final String fileName = mutationMetaData.getFileName(); - final String packageName = mutationMetaData.getPackageName(); - - final MutationResultList mutationsForThisFile = mutationMetaData - .getResults(); - - final List lines = createAnnotatedSourceCodeLines(fileName, - packageName, mutationsForThisFile); - - return new SourceFile(fileName, lines, - mutationsForThisFile.groupMutationsByLine()); - } - - private List createAnnotatedSourceCodeLines(final String sourceFile, - final String packageName, final MutationResultList mutationsForThisFile) - throws IOException { - final Collection classes = this.coverage.getClassesForFile( - sourceFile, packageName); - final Optional reader = findSourceFile(classInfoToNames(classes), - sourceFile); - if (reader.isPresent()) { - final AnnotatedLineFactory alf = new AnnotatedLineFactory( - mutationsForThisFile.list(), this.coverage, classes); - return alf.convert(reader.get()); - } - return Collections.emptyList(); - } - - private Collection classInfoToNames( - final Collection classes) { - return FCollection.map(classes, classInfoToJavaName()); - } - - private Function classInfoToJavaName() { - return a -> a.getName().asJavaName(); - } - - private Optional findSourceFile(final Collection classes, - final String fileName) { - for (final SourceLocator each : this.sourceRoots) { - final Optional maybe = each.locate(classes, fileName); - if (maybe.isPresent()) { - return maybe; - } - } - return Optional.empty(); - } - - public void onRunEnd() { - createIndexPages(); - createCssFile(); - } - - private void createCssFile() { - final Writer cssWriter = this.outputStrategy.createWriterForFile("style.css"); - try { - cssWriter.write(this.css); - cssWriter.close(); - } catch (final IOException e) { - e.printStackTrace(); - } - } - - private void createIndexPages() { - - final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); - final StringTemplate st = group - .getInstanceOf("templates/mutation/mutation_package_index"); - - final Writer writer = this.outputStrategy.createWriterForFile("index.html"); - final MutationTotals totals = new MutationTotals(); - - final List psd = new ArrayList<>( - this.packageSummaryData.values()); - Collections.sort(psd); - for (final PackageSummaryData psData : psd) { - totals.add(psData.getTotals()); - createPackageIndexPage(psData); - } - - st.setAttribute("totals", totals); - st.setAttribute("packageSummaries", psd); - try { - writer.write(st.toString()); - writer.close(); - } catch (final IOException e) { - e.printStackTrace(); - } - - } - - private void createPackageIndexPage(final PackageSummaryData psData) { - final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); - final StringTemplate st = group - .getInstanceOf("templates/mutation/package_index"); - - final Writer writer = this.outputStrategy.createWriterForFile(psData - .getPackageDirectory() + File.separator + "index.html"); - st.setAttribute("packageData", psData); - try { - writer.write(st.toString()); - writer.close(); - } catch (final IOException e) { - e.printStackTrace(); - } - - } - - @Override - public void runStart() { - // TODO Auto-generated method stub - - } - - @Override - public void runEnd() { - createIndexPages(); - createCssFile(); - } - - @Override - public void handleMutationResult(final ClassMutationResults metaData) { - final PackageSummaryData packageData = collectPackageSummaries(metaData); - - generateAnnotatedSourceFile(packageData.getForSourceFile(metaData - .getFileName())); - - } - +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.logging.Level; + +import org.antlr.stringtemplate.StringTemplate; +import org.antlr.stringtemplate.StringTemplateGroup; +import org.pitest.classinfo.ClassInfo; +import org.pitest.coverage.CoverageDatabase; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.ClassMutationResults; +import org.pitest.mutationtest.MutationResultListener; +import org.pitest.mutationtest.SourceLocator; +import org.pitest.util.FileUtil; +import org.pitest.util.IsolationUtils; +import org.pitest.util.Log; +import org.pitest.util.ResultOutputStrategy; + +public class MutationHtmlReportListener implements MutationResultListener { + + private final ResultOutputStrategy outputStrategy; + + private final Collection sourceRoots; + + private final PackageSummaryMap packageSummaryData = new PackageSummaryMap(); + private final CoverageDatabase coverage; + private final Set mutatorNames; + + private final String css; + + public MutationHtmlReportListener(final CoverageDatabase coverage, + final ResultOutputStrategy outputStrategy, + Collection mutatorNames, final SourceLocator... locators) { + this.coverage = coverage; + this.outputStrategy = outputStrategy; + this.sourceRoots = new HashSet<>(Arrays.asList(locators)); + this.mutatorNames = new HashSet<>(mutatorNames); + this.css = loadCss(); + } + + private String loadCss() { + try { + return FileUtil.readToString(IsolationUtils.getContextClassLoader() + .getResourceAsStream("templates/mutation/style.css")); + } catch (final IOException e) { + Log.getLogger().log(Level.SEVERE, "Error while loading css", e); + } + return ""; + } + + private void generateAnnotatedSourceFile( + final MutationTestSummaryData mutationMetaData) { + + + final String fileName = mutationMetaData.getPackageName() + + File.separator + mutationMetaData.getFileName() + ".html"; + + try (Writer writer = this.outputStrategy.createWriterForFile(fileName)) { + + final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); + final StringTemplate st = group + .getInstanceOf("templates/mutation/mutation_report"); + st.setAttribute("css", this.css); + + st.setAttribute("tests", mutationMetaData.getTests()); + + st.setAttribute("mutators", mutationMetaData.getMutators()); + + final SourceFile sourceFile = createAnnotatedSourceFile(mutationMetaData); + + st.setAttribute("sourceFile", sourceFile); + st.setAttribute("mutatedClasses", mutationMetaData.getMutatedClasses()); + + writer.write(st.toString()); + + + } catch (final IOException ex) { + Log.getLogger().log(Level.WARNING, "Error while writing report", ex); + } + } + + private PackageSummaryData collectPackageSummaries( + final ClassMutationResults mutationMetaData) { + final String packageName = mutationMetaData.getPackageName(); + + return this.packageSummaryData.update(packageName, + createSummaryData(this.coverage, mutationMetaData)); + } + + public MutationTestSummaryData createSummaryData( + final CoverageDatabase coverage, final ClassMutationResults data) { + return new MutationTestSummaryData(data.getFileName(), data.getMutations(), + this.mutatorNames, coverage.getClassInfo(Collections.singleton(data + .getMutatedClass())), coverage.getNumberOfCoveredLines(Collections + .singleton(data.getMutatedClass()))); + } + + private SourceFile createAnnotatedSourceFile( + final MutationTestSummaryData mutationMetaData) throws IOException { + + final String fileName = mutationMetaData.getFileName(); + final String packageName = mutationMetaData.getPackageName(); + + final MutationResultList mutationsForThisFile = mutationMetaData + .getResults(); + + final List lines = createAnnotatedSourceCodeLines(fileName, + packageName, mutationsForThisFile); + + return new SourceFile(fileName, lines, + mutationsForThisFile.groupMutationsByLine()); + } + + private List createAnnotatedSourceCodeLines(final String sourceFile, + final String packageName, final MutationResultList mutationsForThisFile) + throws IOException { + final Collection classes = this.coverage.getClassesForFile( + sourceFile, packageName); + final Optional reader = findSourceFile(classInfoToNames(classes), + sourceFile); + if (reader.isPresent()) { + final AnnotatedLineFactory alf = new AnnotatedLineFactory( + mutationsForThisFile.list(), this.coverage, classes); + return alf.convert(reader.get()); + } + return Collections.emptyList(); + } + + private Collection classInfoToNames( + final Collection classes) { + return FCollection.map(classes, classInfoToJavaName()); + } + + private Function classInfoToJavaName() { + return a -> a.getName().asJavaName(); + } + + private Optional findSourceFile(final Collection classes, + final String fileName) { + for (final SourceLocator each : this.sourceRoots) { + final Optional maybe = each.locate(classes, fileName); + if (maybe.isPresent()) { + return maybe; + } + } + return Optional.empty(); + } + + public void onRunEnd() { + createIndexPages(); + createCssFile(); + } + + private void createCssFile() { + final Writer cssWriter = this.outputStrategy.createWriterForFile("style.css"); + try { + cssWriter.write(this.css); + cssWriter.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + } + + private void createIndexPages() { + + final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); + final StringTemplate st = group + .getInstanceOf("templates/mutation/mutation_package_index"); + + final Writer writer = this.outputStrategy.createWriterForFile("index.html"); + final MutationTotals totals = new MutationTotals(); + + final List psd = new ArrayList<>( + this.packageSummaryData.values()); + Collections.sort(psd); + for (final PackageSummaryData psData : psd) { + totals.add(psData.getTotals()); + createPackageIndexPage(psData); + } + + st.setAttribute("totals", totals); + st.setAttribute("packageSummaries", psd); + try { + writer.write(st.toString()); + writer.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + + } + + private void createPackageIndexPage(final PackageSummaryData psData) { + final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); + final StringTemplate st = group + .getInstanceOf("templates/mutation/package_index"); + + final Writer writer = this.outputStrategy.createWriterForFile(psData + .getPackageDirectory() + File.separator + "index.html"); + st.setAttribute("packageData", psData); + try { + writer.write(st.toString()); + writer.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + + } + + @Override + public void runStart() { + // TODO Auto-generated method stub + + } + + @Override + public void runEnd() { + createIndexPages(); + createCssFile(); + } + + @Override + public void handleMutationResult(final ClassMutationResults metaData) { + final PackageSummaryData packageData = collectPackageSummaries(metaData); + + generateAnnotatedSourceFile(packageData.getForSourceFile(metaData + .getFileName())); + + } + } \ No newline at end of file diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationResultList.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationResultList.java index 8755efc6b..eb31c6973 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationResultList.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationResultList.java @@ -1,71 +1,71 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - -import org.pitest.mutationtest.MutationResult; - -public class MutationResultList implements Iterable { - - private final List impl = new ArrayList<>(); - - public MutationResultList(final Collection results) { - this.impl.addAll(results); - } - - public List groupMutationsByLine() { - sortMutationsIntoLineOrder(); - final List groups = new ArrayList<>(); - List sublist = new ArrayList<>(); - int lastLineNumber = -1; - for (final MutationResult each : this.impl) { - if ((lastLineNumber != each.getDetails().getLineNumber()) - && !sublist.isEmpty()) { - groups.add(new MutationGrouping(lastLineNumber, "Line " - + lastLineNumber, sublist)); - sublist = new ArrayList<>(); - } - sublist.add(each); - lastLineNumber = each.getDetails().getLineNumber(); - } - if (!sublist.isEmpty()) { - groups.add(new MutationGrouping(lastLineNumber, "Line " + lastLineNumber, - sublist)); - } - return groups; - } - - private void sortMutationsIntoLineOrder() { - final Comparator c = (o1, o2) -> o1.getDetails().getLineNumber() - - o2.getDetails().getLineNumber(); - Collections.sort(this.impl, c); - } - - @Override - public Iterator iterator() { - return this.impl.iterator(); - } - - public List list() { - return impl; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +import org.pitest.mutationtest.MutationResult; + +public class MutationResultList implements Iterable { + + private final List impl = new ArrayList<>(); + + public MutationResultList(final Collection results) { + this.impl.addAll(results); + } + + public List groupMutationsByLine() { + sortMutationsIntoLineOrder(); + final List groups = new ArrayList<>(); + List sublist = new ArrayList<>(); + int lastLineNumber = -1; + for (final MutationResult each : this.impl) { + if ((lastLineNumber != each.getDetails().getLineNumber()) + && !sublist.isEmpty()) { + groups.add(new MutationGrouping(lastLineNumber, "Line " + + lastLineNumber, sublist)); + sublist = new ArrayList<>(); + } + sublist.add(each); + lastLineNumber = each.getDetails().getLineNumber(); + } + if (!sublist.isEmpty()) { + groups.add(new MutationGrouping(lastLineNumber, "Line " + lastLineNumber, + sublist)); + } + return groups; + } + + private void sortMutationsIntoLineOrder() { + final Comparator c = (o1, o2) -> o1.getDetails().getLineNumber() + - o2.getDetails().getLineNumber(); + Collections.sort(this.impl, c); + } + + @Override + public Iterator iterator() { + return this.impl.iterator(); + } + + public List list() { + return impl; + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTestSummaryData.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTestSummaryData.java index 4e500bac4..8f8a585ac 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTestSummaryData.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTestSummaryData.java @@ -1,129 +1,129 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.function.BiFunction; -import java.util.function.Function; - -import org.pitest.classinfo.ClassInfo; -import org.pitest.coverage.TestInfo; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.MutationResult; - -public class MutationTestSummaryData { - - private final String fileName; - private final Set mutators = new HashSet<>(); - private final Collection mutations = new ArrayList<>(); - private final Set classes = new HashSet<>(); - - private long numberOfCoveredLines; - - public MutationTestSummaryData(final String fileName, - final Collection results, - final Collection mutators, final Collection classes, - final long numberOfCoveredLines) { - this.fileName = fileName; - this.mutations.addAll(results); - this.mutators.addAll(mutators); - this.classes.addAll(classes); - this.numberOfCoveredLines = numberOfCoveredLines; - } - - public MutationTotals getTotals() { - final MutationTotals mt = new MutationTotals(); - mt.addFiles(1); - mt.addMutations(this.getNumberOfMutations()); - mt.addMutationsDetetcted(this.getNumberOfMutationsDetected()); - mt.addLines(getNumberOfLines()); - mt.addLinesCovered(this.numberOfCoveredLines); - return mt; - } - - public String getPackageName() { - final String packageName = getMutatedClasses().iterator().next().getName() - .asJavaName(); - final int lastDot = packageName.lastIndexOf('.'); - return lastDot > 0 ? packageName.substring(0, lastDot) : "default"; - } - - public void add(final MutationTestSummaryData data) { - this.mutations.addAll(data.mutations); - this.mutators.addAll(data.getMutators()); - final int classesBefore = this.classes.size(); - this.classes.addAll(data.classes); - if (classesBefore < this.classes.size()) { - this.numberOfCoveredLines += data.numberOfCoveredLines; - } - } - - public Collection getTests() { - final Set uniqueTests = new HashSet<>(); - FCollection.flatMapTo(this.mutations, mutationToTargettedTests(), - uniqueTests); - return uniqueTests; - } - - public String getFileName() { - return this.fileName; - } - - public Collection getMutatedClasses() { - return this.classes; - } - - public Set getMutators() { - return this.mutators; - } - - public MutationResultList getResults() { - return new MutationResultList(this.mutations); - } - - public Collection getClasses() { - return this.classes; - } - - private int getNumberOfLines() { - return FCollection.fold(accumulateCodeLines(), 0, this.classes); - } - - private BiFunction accumulateCodeLines() { - return (a, b) -> a + b.getNumberOfCodeLines(); - } - - private long getNumberOfMutations() { - return this.mutations.size(); - } - - private long getNumberOfMutationsDetected() { - int count = 0; - for (final MutationResult each : this.mutations) { - if (each.getStatus().isDetected()) { - count++; - } - } - return count; - } - - private Function> mutationToTargettedTests() { - return a -> a.getDetails().getTestsInOrder(); - } - +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; + +import org.pitest.classinfo.ClassInfo; +import org.pitest.coverage.TestInfo; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.MutationResult; + +public class MutationTestSummaryData { + + private final String fileName; + private final Set mutators = new HashSet<>(); + private final Collection mutations = new ArrayList<>(); + private final Set classes = new HashSet<>(); + + private long numberOfCoveredLines; + + public MutationTestSummaryData(final String fileName, + final Collection results, + final Collection mutators, final Collection classes, + final long numberOfCoveredLines) { + this.fileName = fileName; + this.mutations.addAll(results); + this.mutators.addAll(mutators); + this.classes.addAll(classes); + this.numberOfCoveredLines = numberOfCoveredLines; + } + + public MutationTotals getTotals() { + final MutationTotals mt = new MutationTotals(); + mt.addFiles(1); + mt.addMutations(this.getNumberOfMutations()); + mt.addMutationsDetetcted(this.getNumberOfMutationsDetected()); + mt.addLines(getNumberOfLines()); + mt.addLinesCovered(this.numberOfCoveredLines); + return mt; + } + + public String getPackageName() { + final String packageName = getMutatedClasses().iterator().next().getName() + .asJavaName(); + final int lastDot = packageName.lastIndexOf('.'); + return lastDot > 0 ? packageName.substring(0, lastDot) : "default"; + } + + public void add(final MutationTestSummaryData data) { + this.mutations.addAll(data.mutations); + this.mutators.addAll(data.getMutators()); + final int classesBefore = this.classes.size(); + this.classes.addAll(data.classes); + if (classesBefore < this.classes.size()) { + this.numberOfCoveredLines += data.numberOfCoveredLines; + } + } + + public Collection getTests() { + final Set uniqueTests = new HashSet<>(); + FCollection.flatMapTo(this.mutations, mutationToTargettedTests(), + uniqueTests); + return uniqueTests; + } + + public String getFileName() { + return this.fileName; + } + + public Collection getMutatedClasses() { + return this.classes; + } + + public Set getMutators() { + return this.mutators; + } + + public MutationResultList getResults() { + return new MutationResultList(this.mutations); + } + + public Collection getClasses() { + return this.classes; + } + + private int getNumberOfLines() { + return FCollection.fold(accumulateCodeLines(), 0, this.classes); + } + + private BiFunction accumulateCodeLines() { + return (a, b) -> a + b.getNumberOfCodeLines(); + } + + private long getNumberOfMutations() { + return this.mutations.size(); + } + + private long getNumberOfMutationsDetected() { + int count = 0; + for (final MutationResult each : this.mutations) { + if (each.getStatus().isDetected()) { + count++; + } + } + return count; + } + + private Function> mutationToTargettedTests() { + return a -> a.getDetails().getTestsInOrder(); + } + } \ No newline at end of file diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataFileNameComparator.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataFileNameComparator.java index a3df47a9a..a3770f4c7 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataFileNameComparator.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataFileNameComparator.java @@ -1,17 +1,17 @@ -package org.pitest.mutationtest.report.html; - -import java.io.Serializable; -import java.util.Comparator; - -public class MutationTestSummaryDataFileNameComparator implements -Comparator, Serializable { - - private static final long serialVersionUID = 1L; - - @Override - public int compare(final MutationTestSummaryData arg0, - final MutationTestSummaryData arg1) { - return arg0.getFileName().compareTo(arg1.getFileName()); - } - -} +package org.pitest.mutationtest.report.html; + +import java.io.Serializable; +import java.util.Comparator; + +public class MutationTestSummaryDataFileNameComparator implements +Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(final MutationTestSummaryData arg0, + final MutationTestSummaryData arg1) { + return arg0.getFileName().compareTo(arg1.getFileName()); + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTotals.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTotals.java index 0c2b6a6d6..1159cd0e8 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTotals.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationTotals.java @@ -1,74 +1,74 @@ -package org.pitest.mutationtest.report.html; - -public class MutationTotals { - - private long numberOfFiles = 0; - private long numberOfLines = 0; - private long numberOfLinesCovered = 0; - private long numberOfMutations = 0; - private long numberOfMutationsDetected = 0; - - public long getNumberOfFiles() { - return this.numberOfFiles; - } - - public void addFiles(final long files) { - this.numberOfFiles += files; - } - - public long getNumberOfLines() { - return this.numberOfLines; - } - - public void addLines(final long lines) { - this.numberOfLines += lines; - } - - public long getNumberOfLinesCovered() { - return this.numberOfLinesCovered; - } - - public void addLinesCovered(final long linesCovered) { - this.numberOfLinesCovered += linesCovered; - } - - public long getNumberOfMutations() { - return this.numberOfMutations; - } - - public void addMutations(final long mutations) { - this.numberOfMutations += mutations; - } - - public long getNumberOfMutationsDetected() { - return this.numberOfMutationsDetected; - } - - public void addMutationsDetetcted(final long mutationsKilled) { - this.numberOfMutationsDetected += mutationsKilled; - } - - public int getLineCoverage() { - return this.numberOfLines == 0 ? 100 : Math - .round((100f * this.numberOfLinesCovered) / this.numberOfLines); - } - - public int getMutationCoverage() { - return this.numberOfMutations == 0 ? 100 - : Math.round((100f * this.numberOfMutationsDetected) - / this.numberOfMutations); - } - - public void add(final MutationTotals data) { - add(data.getNumberOfLines(), data.getNumberOfFiles(), data); - } - - private void add(final long lines, final long files, final MutationTotals data) { - this.addFiles(files); - this.addLines(lines); - this.addLinesCovered(data.getNumberOfLinesCovered()); - this.addMutations(data.getNumberOfMutations()); - this.addMutationsDetetcted(data.getNumberOfMutationsDetected()); - } - +package org.pitest.mutationtest.report.html; + +public class MutationTotals { + + private long numberOfFiles = 0; + private long numberOfLines = 0; + private long numberOfLinesCovered = 0; + private long numberOfMutations = 0; + private long numberOfMutationsDetected = 0; + + public long getNumberOfFiles() { + return this.numberOfFiles; + } + + public void addFiles(final long files) { + this.numberOfFiles += files; + } + + public long getNumberOfLines() { + return this.numberOfLines; + } + + public void addLines(final long lines) { + this.numberOfLines += lines; + } + + public long getNumberOfLinesCovered() { + return this.numberOfLinesCovered; + } + + public void addLinesCovered(final long linesCovered) { + this.numberOfLinesCovered += linesCovered; + } + + public long getNumberOfMutations() { + return this.numberOfMutations; + } + + public void addMutations(final long mutations) { + this.numberOfMutations += mutations; + } + + public long getNumberOfMutationsDetected() { + return this.numberOfMutationsDetected; + } + + public void addMutationsDetetcted(final long mutationsKilled) { + this.numberOfMutationsDetected += mutationsKilled; + } + + public int getLineCoverage() { + return this.numberOfLines == 0 ? 100 : Math + .round((100f * this.numberOfLinesCovered) / this.numberOfLines); + } + + public int getMutationCoverage() { + return this.numberOfMutations == 0 ? 100 + : Math.round((100f * this.numberOfMutationsDetected) + / this.numberOfMutations); + } + + public void add(final MutationTotals data) { + add(data.getNumberOfLines(), data.getNumberOfFiles(), data); + } + + private void add(final long lines, final long files, final MutationTotals data) { + this.addFiles(files); + this.addLines(lines); + this.addLinesCovered(data.getNumberOfLinesCovered()); + this.addMutations(data.getNumberOfMutations()); + this.addMutationsDetetcted(data.getNumberOfMutationsDetected()); + } + } \ No newline at end of file diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/PackageSummaryData.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/PackageSummaryData.java index 62127f751..c04f64b20 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/PackageSummaryData.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/PackageSummaryData.java @@ -1,92 +1,92 @@ -package org.pitest.mutationtest.report.html; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class PackageSummaryData implements Comparable { - - private final String packageName; - private final Map fileNameToSummaryData = new HashMap<>(); - - public PackageSummaryData(final String packageName) { - this.packageName = packageName; - } - - public void addSummaryData(final MutationTestSummaryData data) { - final MutationTestSummaryData existing = this.fileNameToSummaryData - .get(data.getFileName()); - if (existing == null) { - this.fileNameToSummaryData.put(data.getFileName(), data); - } else { - existing.add(data); - } - - } - - public MutationTestSummaryData getForSourceFile(final String filename) { - return this.fileNameToSummaryData.get(filename); - } - - public MutationTotals getTotals() { - final MutationTotals mt = new MutationTotals(); - for (final MutationTestSummaryData each : this.fileNameToSummaryData - .values()) { - mt.add(each.getTotals()); - } - return mt; - } - - public String getPackageName() { - return this.packageName; - } - - public String getPackageDirectory() { - return this.packageName; - } - - public List getSummaryData() { - final ArrayList values = new ArrayList<>( - this.fileNameToSummaryData.values()); - Collections.sort(values, new MutationTestSummaryDataFileNameComparator()); - return values; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.packageName == null) ? 0 : this.packageName.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final PackageSummaryData other = (PackageSummaryData) obj; - if (this.packageName == null) { - if (other.packageName != null) { - return false; - } - } else if (!this.packageName.equals(other.packageName)) { - return false; - } - return true; - } - - @Override - public int compareTo(final PackageSummaryData arg0) { - return this.packageName.compareTo(arg0.packageName); - } +package org.pitest.mutationtest.report.html; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PackageSummaryData implements Comparable { + + private final String packageName; + private final Map fileNameToSummaryData = new HashMap<>(); + + public PackageSummaryData(final String packageName) { + this.packageName = packageName; + } + + public void addSummaryData(final MutationTestSummaryData data) { + final MutationTestSummaryData existing = this.fileNameToSummaryData + .get(data.getFileName()); + if (existing == null) { + this.fileNameToSummaryData.put(data.getFileName(), data); + } else { + existing.add(data); + } + + } + + public MutationTestSummaryData getForSourceFile(final String filename) { + return this.fileNameToSummaryData.get(filename); + } + + public MutationTotals getTotals() { + final MutationTotals mt = new MutationTotals(); + for (final MutationTestSummaryData each : this.fileNameToSummaryData + .values()) { + mt.add(each.getTotals()); + } + return mt; + } + + public String getPackageName() { + return this.packageName; + } + + public String getPackageDirectory() { + return this.packageName; + } + + public List getSummaryData() { + final ArrayList values = new ArrayList<>( + this.fileNameToSummaryData.values()); + Collections.sort(values, new MutationTestSummaryDataFileNameComparator()); + return values; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.packageName == null) ? 0 : this.packageName.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PackageSummaryData other = (PackageSummaryData) obj; + if (this.packageName == null) { + if (other.packageName != null) { + return false; + } + } else if (!this.packageName.equals(other.packageName)) { + return false; + } + return true; + } + + @Override + public int compareTo(final PackageSummaryData arg0) { + return this.packageName.compareTo(arg0.packageName); + } } \ No newline at end of file diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/PackageSummaryMap.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/PackageSummaryMap.java index 4cfe8cb38..539eecb9b 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/PackageSummaryMap.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/PackageSummaryMap.java @@ -1,33 +1,33 @@ -package org.pitest.mutationtest.report.html; - -import java.util.Collection; -import java.util.Map; -import java.util.TreeMap; - -public class PackageSummaryMap { - - private final Map packageSummaryData = new TreeMap<>(); - - private PackageSummaryData getPackageSummaryData(final String packageName) { - PackageSummaryData psData; - if (this.packageSummaryData.containsKey(packageName)) { - psData = this.packageSummaryData.get(packageName); - } else { - psData = new PackageSummaryData(packageName); - this.packageSummaryData.put(packageName, psData); - } - return psData; - } - - public PackageSummaryData update(final String packageName, - final MutationTestSummaryData data) { - final PackageSummaryData psd = getPackageSummaryData(packageName); - psd.addSummaryData(data); - return psd; - } - - public Collection values() { - return this.packageSummaryData.values(); - } - -} +package org.pitest.mutationtest.report.html; + +import java.util.Collection; +import java.util.Map; +import java.util.TreeMap; + +public class PackageSummaryMap { + + private final Map packageSummaryData = new TreeMap<>(); + + private PackageSummaryData getPackageSummaryData(final String packageName) { + PackageSummaryData psData; + if (this.packageSummaryData.containsKey(packageName)) { + psData = this.packageSummaryData.get(packageName); + } else { + psData = new PackageSummaryData(packageName); + this.packageSummaryData.put(packageName, psData); + } + return psData; + } + + public PackageSummaryData update(final String packageName, + final MutationTestSummaryData data) { + final PackageSummaryData psd = getPackageSummaryData(packageName); + psd.addSummaryData(data); + return psd; + } + + public Collection values() { + return this.packageSummaryData.values(); + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/ResultComparator.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/ResultComparator.java index 2dcec745a..ba515b866 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/ResultComparator.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/ResultComparator.java @@ -1,48 +1,48 @@ -package org.pitest.mutationtest.report.html; - -import static org.pitest.mutationtest.DetectionStatus.KILLED; -import static org.pitest.mutationtest.DetectionStatus.MEMORY_ERROR; -import static org.pitest.mutationtest.DetectionStatus.NON_VIABLE; -import static org.pitest.mutationtest.DetectionStatus.NOT_STARTED; -import static org.pitest.mutationtest.DetectionStatus.NO_COVERAGE; -import static org.pitest.mutationtest.DetectionStatus.RUN_ERROR; -import static org.pitest.mutationtest.DetectionStatus.STARTED; -import static org.pitest.mutationtest.DetectionStatus.SURVIVED; -import static org.pitest.mutationtest.DetectionStatus.TIMED_OUT; - -import java.io.Serializable; -import java.util.Comparator; -import java.util.EnumMap; - -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; - -class ResultComparator implements Comparator, Serializable { - - private static final long serialVersionUID = 1L; - private static final EnumMap RANK = new EnumMap<>( - DetectionStatus.class); - - static { - RANK.put(KILLED, 4); - RANK.put(SURVIVED, 0); - RANK.put(TIMED_OUT, 2); - RANK.put(NON_VIABLE, 3); - RANK.put(MEMORY_ERROR, 1); - RANK.put(NOT_STARTED, 1); - RANK.put(STARTED, 1); - RANK.put(RUN_ERROR, 0); - RANK.put(NO_COVERAGE, 0); - } - - @Override - public int compare(MutationResult o1, MutationResult o2) { - return getRanking(o1.getStatus()) - getRanking(o2.getStatus()); - - } - - private int getRanking(DetectionStatus status) { - return RANK.get(status); - } - -} +package org.pitest.mutationtest.report.html; + +import static org.pitest.mutationtest.DetectionStatus.KILLED; +import static org.pitest.mutationtest.DetectionStatus.MEMORY_ERROR; +import static org.pitest.mutationtest.DetectionStatus.NON_VIABLE; +import static org.pitest.mutationtest.DetectionStatus.NOT_STARTED; +import static org.pitest.mutationtest.DetectionStatus.NO_COVERAGE; +import static org.pitest.mutationtest.DetectionStatus.RUN_ERROR; +import static org.pitest.mutationtest.DetectionStatus.STARTED; +import static org.pitest.mutationtest.DetectionStatus.SURVIVED; +import static org.pitest.mutationtest.DetectionStatus.TIMED_OUT; + +import java.io.Serializable; +import java.util.Comparator; +import java.util.EnumMap; + +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; + +class ResultComparator implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + private static final EnumMap RANK = new EnumMap<>( + DetectionStatus.class); + + static { + RANK.put(KILLED, 4); + RANK.put(SURVIVED, 0); + RANK.put(TIMED_OUT, 2); + RANK.put(NON_VIABLE, 3); + RANK.put(MEMORY_ERROR, 1); + RANK.put(NOT_STARTED, 1); + RANK.put(STARTED, 1); + RANK.put(RUN_ERROR, 0); + RANK.put(NO_COVERAGE, 0); + } + + @Override + public int compare(MutationResult o1, MutationResult o2) { + return getRanking(o1.getStatus()) - getRanking(o2.getStatus()); + + } + + private int getRanking(DetectionStatus status) { + return RANK.get(status); + } + +} diff --git a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/SourceFile.java b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/SourceFile.java index 890de28b0..b976213d6 100644 --- a/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/SourceFile.java +++ b/pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/SourceFile.java @@ -1,44 +1,44 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import java.util.List; - -public class SourceFile { - - private final String fileName; - private final List lines; - private final List groups; - - public SourceFile(final String fileName, final List lines, - final List groups) { - this.fileName = fileName; - this.lines = lines; - this.groups = groups; - } - - public String getFileName() { - return this.fileName; - } - - public List getLines() { - return this.lines; - } - - public List getGroups() { - return this.groups; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import java.util.List; + +public class SourceFile { + + private final String fileName; + private final List lines; + private final List groups; + + public SourceFile(final String fileName, final List lines, + final List groups) { + this.fileName = fileName; + this.lines = lines; + this.groups = groups; + } + + public String getFileName() { + return this.fileName; + } + + public List getLines() { + return this.lines; + } + + public List getGroups() { + return this.groups; + } + +} diff --git a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/ConfidenceMapTest.java b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/ConfidenceMapTest.java index f7e51b597..305e648bb 100644 --- a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/ConfidenceMapTest.java +++ b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/ConfidenceMapTest.java @@ -1,56 +1,56 @@ -package org.pitest.mutationtest.report.html; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.pitest.mutationtest.DetectionStatus; - -public class ConfidenceMapTest { - - @Test - public void shouldHaveHighConfidenceForKilled() { - assertTrue(ConfidenceMap.hasHighConfidence(DetectionStatus.KILLED)); - } - - @Test - public void shouldHaveHighConfidenceForSurvived() { - assertTrue(ConfidenceMap.hasHighConfidence(DetectionStatus.SURVIVED)); - } - - @Test - public void shouldHaveHighConfidenceForNonViable() { - assertTrue(ConfidenceMap.hasHighConfidence(DetectionStatus.NON_VIABLE)); - } - - @Test - public void shouldHaveHighConfidenceForNoCoverage() { - assertTrue(ConfidenceMap.hasHighConfidence(DetectionStatus.NO_COVERAGE)); - } - - @Test - public void shouldHaveLowConfidenceForTimedOut() { - assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.TIMED_OUT)); - } - - @Test - public void shouldHaveLowConfidenceForMemoryError() { - assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.MEMORY_ERROR)); - } - - @Test - public void shouldHaveLowConfidenceForNotStarted() { - assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.NOT_STARTED)); - } - - @Test - public void shouldHaveLowConfidenceForStarted() { - assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.STARTED)); - } - - @Test - public void shouldHaveLowConfidenceForRunError() { - assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.RUN_ERROR)); - } - -} +package org.pitest.mutationtest.report.html; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.pitest.mutationtest.DetectionStatus; + +public class ConfidenceMapTest { + + @Test + public void shouldHaveHighConfidenceForKilled() { + assertTrue(ConfidenceMap.hasHighConfidence(DetectionStatus.KILLED)); + } + + @Test + public void shouldHaveHighConfidenceForSurvived() { + assertTrue(ConfidenceMap.hasHighConfidence(DetectionStatus.SURVIVED)); + } + + @Test + public void shouldHaveHighConfidenceForNonViable() { + assertTrue(ConfidenceMap.hasHighConfidence(DetectionStatus.NON_VIABLE)); + } + + @Test + public void shouldHaveHighConfidenceForNoCoverage() { + assertTrue(ConfidenceMap.hasHighConfidence(DetectionStatus.NO_COVERAGE)); + } + + @Test + public void shouldHaveLowConfidenceForTimedOut() { + assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.TIMED_OUT)); + } + + @Test + public void shouldHaveLowConfidenceForMemoryError() { + assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.MEMORY_ERROR)); + } + + @Test + public void shouldHaveLowConfidenceForNotStarted() { + assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.NOT_STARTED)); + } + + @Test + public void shouldHaveLowConfidenceForStarted() { + assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.STARTED)); + } + + @Test + public void shouldHaveLowConfidenceForRunError() { + assertFalse(ConfidenceMap.hasHighConfidence(DetectionStatus.RUN_ERROR)); + } + +} diff --git a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/InputStreamLineIterableTest.java b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/InputStreamLineIterableTest.java index ed41193ac..d7f28d68a 100644 --- a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/InputStreamLineIterableTest.java +++ b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/InputStreamLineIterableTest.java @@ -1,40 +1,40 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.StringReader; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.functional.FCollection; - -public class InputStreamLineIterableTest { - - private InputStreamLineIterable testee; - - @Before - public void setUp() { - final StringReader input = new StringReader("1\n2\n3\n"); - this.testee = new InputStreamLineIterable(input); - } - - @Test - public void shouldReadAllInput() { - assertThat(FCollection.map(testee, s -> s)).containsExactly("1", "2", "3"); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.StringReader; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.functional.FCollection; + +public class InputStreamLineIterableTest { + + private InputStreamLineIterable testee; + + @Before + public void setUp() { + final StringReader input = new StringReader("1\n2\n3\n"); + this.testee = new InputStreamLineIterable(input); + } + + @Test + public void shouldReadAllInput() { + assertThat(FCollection.map(testee, s -> s)).containsExactly("1", "2", "3"); + } + +} diff --git a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationHtmlReportListenerTest.java b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationHtmlReportListenerTest.java index 97d867306..8360c37c3 100644 --- a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationHtmlReportListenerTest.java +++ b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationHtmlReportListenerTest.java @@ -1,100 +1,100 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.report.html; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.Reader; -import java.io.Writer; -import java.util.Collection; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.CoverageDatabase; -import java.util.Optional; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.SourceLocator; -import org.pitest.mutationtest.report.MutationTestResultMother; -import org.pitest.util.ResultOutputStrategy; - -public class MutationHtmlReportListenerTest { - - private MutationHtmlReportListener testee; - - @Mock - private CoverageDatabase coverageDb; - - @Mock - private ResultOutputStrategy outputStrategy; - - @Mock - private SourceLocator sourceLocator; - - @Mock - private Writer writer; - - @Mock - private ClassInfo classInfo; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - when(this.outputStrategy.createWriterForFile(any(String.class))) - .thenReturn(this.writer); - when(this.classInfo.getName()).thenReturn(ClassName.fromString("foo")); - when(this.coverageDb.getClassInfo(any(Collection.class))).thenReturn( - Collections.singleton(this.classInfo)); - - this.testee = new MutationHtmlReportListener(this.coverageDb, - this.outputStrategy, Collections.emptyList(), this.sourceLocator); - } - - @Test - public void shouldCreateAnIndexFile() { - this.testee.onRunEnd(); - verify(this.outputStrategy).createWriterForFile("index.html"); - } - - @Test - public void shouldCreateACssFile() { - this.testee.onRunEnd(); - verify(this.outputStrategy).createWriterForFile("style.css"); - } - - @Test - public void shouldTryToLocateSourceFilesFromMutatedClasses() { - final String fileName = "foo.java"; - final MutationResult mr = new MutationResult( - MutationTestResultMother.createDetails(fileName), - new MutationStatusTestPair(1, DetectionStatus.KILLED, "testName")); - when(this.sourceLocator.locate(any(Collection.class), any(String.class))) - .thenReturn(Optional. empty()); - this.testee.handleMutationResult(MutationTestResultMother - .createClassResults(mr)); - verify(this.sourceLocator).locate(any(Collection.class), eq(fileName)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report.html; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.Reader; +import java.io.Writer; +import java.util.Collection; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.CoverageDatabase; +import java.util.Optional; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.SourceLocator; +import org.pitest.mutationtest.report.MutationTestResultMother; +import org.pitest.util.ResultOutputStrategy; + +public class MutationHtmlReportListenerTest { + + private MutationHtmlReportListener testee; + + @Mock + private CoverageDatabase coverageDb; + + @Mock + private ResultOutputStrategy outputStrategy; + + @Mock + private SourceLocator sourceLocator; + + @Mock + private Writer writer; + + @Mock + private ClassInfo classInfo; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + when(this.outputStrategy.createWriterForFile(any(String.class))) + .thenReturn(this.writer); + when(this.classInfo.getName()).thenReturn(ClassName.fromString("foo")); + when(this.coverageDb.getClassInfo(any(Collection.class))).thenReturn( + Collections.singleton(this.classInfo)); + + this.testee = new MutationHtmlReportListener(this.coverageDb, + this.outputStrategy, Collections.emptyList(), this.sourceLocator); + } + + @Test + public void shouldCreateAnIndexFile() { + this.testee.onRunEnd(); + verify(this.outputStrategy).createWriterForFile("index.html"); + } + + @Test + public void shouldCreateACssFile() { + this.testee.onRunEnd(); + verify(this.outputStrategy).createWriterForFile("style.css"); + } + + @Test + public void shouldTryToLocateSourceFilesFromMutatedClasses() { + final String fileName = "foo.java"; + final MutationResult mr = new MutationResult( + MutationTestResultMother.createDetails(fileName), + new MutationStatusTestPair(1, DetectionStatus.KILLED, "testName")); + when(this.sourceLocator.locate(any(Collection.class), any(String.class))) + .thenReturn(Optional. empty()); + this.testee.handleMutationResult(MutationTestResultMother + .createClassResults(mr)); + verify(this.sourceLocator).locate(any(Collection.class), eq(fileName)); + } + +} diff --git a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataFileNameComparatorTest.java b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataFileNameComparatorTest.java index 116b3e743..015d06ff8 100644 --- a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataFileNameComparatorTest.java +++ b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataFileNameComparatorTest.java @@ -1,34 +1,34 @@ -package org.pitest.mutationtest.report.html; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; -import org.pitest.classinfo.ClassInfo; -import org.pitest.mutationtest.MutationResult; - -public class MutationTestSummaryDataFileNameComparatorTest { - - @Test - public void shouldSortDataByFileName() { - final MutationTestSummaryDataFileNameComparator testee = new MutationTestSummaryDataFileNameComparator(); - final MutationTestSummaryData ab = makeSummaryData("ab"); - final MutationTestSummaryData aa = makeSummaryData("aa"); - final MutationTestSummaryData z = makeSummaryData("z"); - final List list = Arrays.asList(z, aa, ab); - Collections.sort(list, testee); - final List expected = Arrays.asList(aa, ab, z); - assertEquals(expected, list); - } - - private MutationTestSummaryData makeSummaryData(final String fileName) { - return new MutationTestSummaryData(fileName, - Collections. emptyList(), - Collections. emptyList(), Collections. emptyList(), - 0); - } - -} +package org.pitest.mutationtest.report.html; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; +import org.pitest.classinfo.ClassInfo; +import org.pitest.mutationtest.MutationResult; + +public class MutationTestSummaryDataFileNameComparatorTest { + + @Test + public void shouldSortDataByFileName() { + final MutationTestSummaryDataFileNameComparator testee = new MutationTestSummaryDataFileNameComparator(); + final MutationTestSummaryData ab = makeSummaryData("ab"); + final MutationTestSummaryData aa = makeSummaryData("aa"); + final MutationTestSummaryData z = makeSummaryData("z"); + final List list = Arrays.asList(z, aa, ab); + Collections.sort(list, testee); + final List expected = Arrays.asList(aa, ab, z); + assertEquals(expected, list); + } + + private MutationTestSummaryData makeSummaryData(final String fileName) { + return new MutationTestSummaryData(fileName, + Collections. emptyList(), + Collections. emptyList(), Collections. emptyList(), + 0); + } + +} diff --git a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataTest.java b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataTest.java index 8bc671ef0..27c9a2b61 100644 --- a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataTest.java +++ b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTestSummaryDataTest.java @@ -1,116 +1,116 @@ -package org.pitest.mutationtest.report.html; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; - -import org.junit.Test; -import org.mockito.Mockito; -import org.pitest.classinfo.ClassInfo; -import org.pitest.mutationtest.MutationResult; - -public class MutationTestSummaryDataTest { - - private MutationTestSummaryData testee; - - private static final String FILE_NAME = "foo.java"; - - @Test - public void shouldReturnCorrectNumberOfFilesWhenAnalysedInOneUnit() { - final ClassInfo clazz = makeClass(); - this.testee = buildSummaryData(clazz); - assertEquals(1, this.testee.getTotals().getNumberOfFiles()); - } - - @Test - public void shouldReturnCorrectNumberOfLinesWhenAnalysedInOneUnit() { - final int lines = 100; - final ClassInfo clazz = makeClass(lines); - this.testee = buildSummaryData(clazz); - assertEquals(lines, this.testee.getTotals().getNumberOfLines()); - } - - @Test - public void shouldReturnCorrectNumberOfCoveredLinesWhenAnalysedInOneUnit() { - final int linesCovered = 100; - final ClassInfo clazz = makeClass(200); - this.testee = buildSummaryData(clazz, linesCovered); - assertEquals(linesCovered, this.testee.getTotals() - .getNumberOfLinesCovered()); - } - - @Test - public void shouldReturnCorrectNumberOfFilesWhenOneClassAnalysedInTwoUnits() { - final ClassInfo clazz = makeClass(); - this.testee = buildSummaryData(clazz); - final MutationTestSummaryData additonalDataForSameClass = buildSummaryData(clazz); - this.testee.add(additonalDataForSameClass); - assertEquals(1, this.testee.getTotals().getNumberOfFiles()); - } - - @Test - public void shouldReturnCorrectNumberOfLinesWhenAnalysedInTwoUnit() { - final int lines = 100; - final ClassInfo clazz = makeClass(lines); - this.testee = buildSummaryData(clazz); - final MutationTestSummaryData additonalDataForSameClass = buildSummaryData(clazz); - this.testee.add(additonalDataForSameClass); - assertEquals(lines, this.testee.getTotals().getNumberOfLines()); - } - - @Test - public void shouldReturnCorrectNumberOfCoveredLinesWhenAnalysedInTwoUnits() { - final int linesCovered = 100; - final ClassInfo clazz = makeClass(200); - this.testee = buildSummaryData(clazz, linesCovered); - final MutationTestSummaryData additonalDataForSameClass = buildSummaryData( - clazz, linesCovered); - this.testee.add(additonalDataForSameClass); - assertEquals(linesCovered, this.testee.getTotals() - .getNumberOfLinesCovered()); - } - - @Test - public void shouldReturnCorrectNumberOfLinesWhenCombiningResultsForDifferentClasses() { - this.testee = buildSummaryData(makeClass(100)); - final MutationTestSummaryData addiitonalDataForSameClass = buildSummaryData(makeClass(200)); - this.testee.add(addiitonalDataForSameClass); - assertEquals(100 + 200, this.testee.getTotals().getNumberOfLines()); - } - - @Test - public void shouldReturnCorrectNumberOfLinesCoveredWhenCombiningResultsForDifferentClasses() { - this.testee = buildSummaryData(makeClass(100), 300); - final MutationTestSummaryData addiitonalDataForSameClass = buildSummaryData( - makeClass(200), 100); - this.testee.add(addiitonalDataForSameClass); - assertEquals(300 + 100, this.testee.getTotals().getNumberOfLinesCovered()); - } - - private ClassInfo makeClass() { - return makeClass(100); - } - - private ClassInfo makeClass(final int numberOfLines) { - final ClassInfo clazz = Mockito.mock(ClassInfo.class); - when(clazz.getNumberOfCodeLines()).thenReturn(numberOfLines); - return clazz; - } - - private MutationTestSummaryData buildSummaryData(final ClassInfo clazz) { - return buildSummaryData(clazz, 0); - } - - private MutationTestSummaryData buildSummaryData(final ClassInfo clazz, - final int linesCovered) { - final Collection classes = Arrays.asList(clazz); - final Collection results = Collections.emptyList(); - final Collection mutators = Collections.emptyList(); - return new MutationTestSummaryData(FILE_NAME, results, mutators, classes, - linesCovered); - } - -} +package org.pitest.mutationtest.report.html; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; + +import org.junit.Test; +import org.mockito.Mockito; +import org.pitest.classinfo.ClassInfo; +import org.pitest.mutationtest.MutationResult; + +public class MutationTestSummaryDataTest { + + private MutationTestSummaryData testee; + + private static final String FILE_NAME = "foo.java"; + + @Test + public void shouldReturnCorrectNumberOfFilesWhenAnalysedInOneUnit() { + final ClassInfo clazz = makeClass(); + this.testee = buildSummaryData(clazz); + assertEquals(1, this.testee.getTotals().getNumberOfFiles()); + } + + @Test + public void shouldReturnCorrectNumberOfLinesWhenAnalysedInOneUnit() { + final int lines = 100; + final ClassInfo clazz = makeClass(lines); + this.testee = buildSummaryData(clazz); + assertEquals(lines, this.testee.getTotals().getNumberOfLines()); + } + + @Test + public void shouldReturnCorrectNumberOfCoveredLinesWhenAnalysedInOneUnit() { + final int linesCovered = 100; + final ClassInfo clazz = makeClass(200); + this.testee = buildSummaryData(clazz, linesCovered); + assertEquals(linesCovered, this.testee.getTotals() + .getNumberOfLinesCovered()); + } + + @Test + public void shouldReturnCorrectNumberOfFilesWhenOneClassAnalysedInTwoUnits() { + final ClassInfo clazz = makeClass(); + this.testee = buildSummaryData(clazz); + final MutationTestSummaryData additonalDataForSameClass = buildSummaryData(clazz); + this.testee.add(additonalDataForSameClass); + assertEquals(1, this.testee.getTotals().getNumberOfFiles()); + } + + @Test + public void shouldReturnCorrectNumberOfLinesWhenAnalysedInTwoUnit() { + final int lines = 100; + final ClassInfo clazz = makeClass(lines); + this.testee = buildSummaryData(clazz); + final MutationTestSummaryData additonalDataForSameClass = buildSummaryData(clazz); + this.testee.add(additonalDataForSameClass); + assertEquals(lines, this.testee.getTotals().getNumberOfLines()); + } + + @Test + public void shouldReturnCorrectNumberOfCoveredLinesWhenAnalysedInTwoUnits() { + final int linesCovered = 100; + final ClassInfo clazz = makeClass(200); + this.testee = buildSummaryData(clazz, linesCovered); + final MutationTestSummaryData additonalDataForSameClass = buildSummaryData( + clazz, linesCovered); + this.testee.add(additonalDataForSameClass); + assertEquals(linesCovered, this.testee.getTotals() + .getNumberOfLinesCovered()); + } + + @Test + public void shouldReturnCorrectNumberOfLinesWhenCombiningResultsForDifferentClasses() { + this.testee = buildSummaryData(makeClass(100)); + final MutationTestSummaryData addiitonalDataForSameClass = buildSummaryData(makeClass(200)); + this.testee.add(addiitonalDataForSameClass); + assertEquals(100 + 200, this.testee.getTotals().getNumberOfLines()); + } + + @Test + public void shouldReturnCorrectNumberOfLinesCoveredWhenCombiningResultsForDifferentClasses() { + this.testee = buildSummaryData(makeClass(100), 300); + final MutationTestSummaryData addiitonalDataForSameClass = buildSummaryData( + makeClass(200), 100); + this.testee.add(addiitonalDataForSameClass); + assertEquals(300 + 100, this.testee.getTotals().getNumberOfLinesCovered()); + } + + private ClassInfo makeClass() { + return makeClass(100); + } + + private ClassInfo makeClass(final int numberOfLines) { + final ClassInfo clazz = Mockito.mock(ClassInfo.class); + when(clazz.getNumberOfCodeLines()).thenReturn(numberOfLines); + return clazz; + } + + private MutationTestSummaryData buildSummaryData(final ClassInfo clazz) { + return buildSummaryData(clazz, 0); + } + + private MutationTestSummaryData buildSummaryData(final ClassInfo clazz, + final int linesCovered) { + final Collection classes = Arrays.asList(clazz); + final Collection results = Collections.emptyList(); + final Collection mutators = Collections.emptyList(); + return new MutationTestSummaryData(FILE_NAME, results, mutators, classes, + linesCovered); + } + +} diff --git a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTotalsTest.java b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTotalsTest.java index e38684183..63f2537c3 100644 --- a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTotalsTest.java +++ b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/MutationTotalsTest.java @@ -1,81 +1,81 @@ -package org.pitest.mutationtest.report.html; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -public class MutationTotalsTest { - - private MutationTotals testee; - - @Before - public void setUp() { - this.testee = new MutationTotals(); - } - - @Test - public void shouldCorrectlyCalculateLineCoverageWhenNoLinesPresent() { - assertEquals(100, this.testee.getLineCoverage()); - } - - @Test - public void shouldCorrectlyCalculateLineCoverageWhenNoLinesCovered() { - this.testee.addLines(100); - assertEquals(0, this.testee.getLineCoverage()); - } - - @Test - public void shouldCorrectlyCalculateLineCoverageWhenAllLinesCovered() { - this.testee.addLines(100); - this.testee.addLinesCovered(100); - assertEquals(100, this.testee.getLineCoverage()); - } - - @Test - public void shouldCorrectlyCalculateLineCoverageWhenPartiallyCovered() { - this.testee.addLines(63); - this.testee.addLinesCovered(20); - assertEquals(32, this.testee.getLineCoverage()); - } - - @Test - public void shouldCorrectlyCalculateMutationCoverageWhenNoMutationsPresent() { - assertEquals(100, this.testee.getMutationCoverage()); - } - - @Test - public void shouldCorrectlyCalculateMutationCoverageWhenNoMutationsDetected() { - this.testee.addMutations(100); - assertEquals(0, this.testee.getMutationCoverage()); - } - - @Test - public void shouldCorrectlyCalculateMutationsCoverageWhenAllMutationsDetected() { - this.testee.addMutations(100); - this.testee.addMutationsDetetcted(100); - assertEquals(100, this.testee.getMutationCoverage()); - } - - @Test - public void shouldCorrectlyCalculateMutationCoverageWhenSomeMutationUndetected() { - this.testee.addMutations(63); - this.testee.addMutationsDetetcted(20); - assertEquals(32, this.testee.getMutationCoverage()); - } - - @Test - public void shouldAccumulateAddedValues() { - final MutationTotals extra = new MutationTotals(); - extra.addFiles(2); - extra.addLines(8); - extra.addLinesCovered(4); - extra.addMutations(9); - extra.addMutationsDetetcted(3); - this.testee.add(extra); - assertEquals(2, this.testee.getNumberOfFiles()); - assertEquals(50, this.testee.getLineCoverage()); - assertEquals(33, this.testee.getMutationCoverage()); - } - -} +package org.pitest.mutationtest.report.html; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class MutationTotalsTest { + + private MutationTotals testee; + + @Before + public void setUp() { + this.testee = new MutationTotals(); + } + + @Test + public void shouldCorrectlyCalculateLineCoverageWhenNoLinesPresent() { + assertEquals(100, this.testee.getLineCoverage()); + } + + @Test + public void shouldCorrectlyCalculateLineCoverageWhenNoLinesCovered() { + this.testee.addLines(100); + assertEquals(0, this.testee.getLineCoverage()); + } + + @Test + public void shouldCorrectlyCalculateLineCoverageWhenAllLinesCovered() { + this.testee.addLines(100); + this.testee.addLinesCovered(100); + assertEquals(100, this.testee.getLineCoverage()); + } + + @Test + public void shouldCorrectlyCalculateLineCoverageWhenPartiallyCovered() { + this.testee.addLines(63); + this.testee.addLinesCovered(20); + assertEquals(32, this.testee.getLineCoverage()); + } + + @Test + public void shouldCorrectlyCalculateMutationCoverageWhenNoMutationsPresent() { + assertEquals(100, this.testee.getMutationCoverage()); + } + + @Test + public void shouldCorrectlyCalculateMutationCoverageWhenNoMutationsDetected() { + this.testee.addMutations(100); + assertEquals(0, this.testee.getMutationCoverage()); + } + + @Test + public void shouldCorrectlyCalculateMutationsCoverageWhenAllMutationsDetected() { + this.testee.addMutations(100); + this.testee.addMutationsDetetcted(100); + assertEquals(100, this.testee.getMutationCoverage()); + } + + @Test + public void shouldCorrectlyCalculateMutationCoverageWhenSomeMutationUndetected() { + this.testee.addMutations(63); + this.testee.addMutationsDetetcted(20); + assertEquals(32, this.testee.getMutationCoverage()); + } + + @Test + public void shouldAccumulateAddedValues() { + final MutationTotals extra = new MutationTotals(); + extra.addFiles(2); + extra.addLines(8); + extra.addLinesCovered(4); + extra.addMutations(9); + extra.addMutationsDetetcted(3); + this.testee.add(extra); + assertEquals(2, this.testee.getNumberOfFiles()); + assertEquals(50, this.testee.getLineCoverage()); + assertEquals(33, this.testee.getMutationCoverage()); + } + +} diff --git a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/PackageSummaryDataTest.java b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/PackageSummaryDataTest.java index ff4b1f441..c91d8e5a8 100644 --- a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/PackageSummaryDataTest.java +++ b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/PackageSummaryDataTest.java @@ -1,43 +1,43 @@ -package org.pitest.mutationtest.report.html; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; -import org.pitest.classinfo.ClassInfo; -import org.pitest.mutationtest.MutationResult; - -public class PackageSummaryDataTest { - - @Test - public void shouldReturnSummaryDataInAlphabeticOrder() { - final PackageSummaryData testee = new PackageSummaryData("foo"); - final MutationTestSummaryData a = makeSummaryData("a"); - final MutationTestSummaryData z = makeSummaryData("z"); - testee.addSummaryData(z); - testee.addSummaryData(a); - assertEquals(Arrays.asList(a, z), testee.getSummaryData()); - - } - - @Test - public void shouldSortByPackageName() { - final PackageSummaryData aa = new PackageSummaryData("aa"); - final PackageSummaryData ab = new PackageSummaryData("ab"); - final PackageSummaryData c = new PackageSummaryData("c"); - final List actual = Arrays.asList(c, aa, ab); - Collections.sort(actual); - assertEquals(Arrays.asList(aa, ab, c), actual); - } - - private MutationTestSummaryData makeSummaryData(final String fileName) { - return new MutationTestSummaryData(fileName, - Collections. emptyList(), - Collections. emptyList(), Collections. emptyList(), - 0); - } - -} +package org.pitest.mutationtest.report.html; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; +import org.pitest.classinfo.ClassInfo; +import org.pitest.mutationtest.MutationResult; + +public class PackageSummaryDataTest { + + @Test + public void shouldReturnSummaryDataInAlphabeticOrder() { + final PackageSummaryData testee = new PackageSummaryData("foo"); + final MutationTestSummaryData a = makeSummaryData("a"); + final MutationTestSummaryData z = makeSummaryData("z"); + testee.addSummaryData(z); + testee.addSummaryData(a); + assertEquals(Arrays.asList(a, z), testee.getSummaryData()); + + } + + @Test + public void shouldSortByPackageName() { + final PackageSummaryData aa = new PackageSummaryData("aa"); + final PackageSummaryData ab = new PackageSummaryData("ab"); + final PackageSummaryData c = new PackageSummaryData("c"); + final List actual = Arrays.asList(c, aa, ab); + Collections.sort(actual); + assertEquals(Arrays.asList(aa, ab, c), actual); + } + + private MutationTestSummaryData makeSummaryData(final String fileName) { + return new MutationTestSummaryData(fileName, + Collections. emptyList(), + Collections. emptyList(), Collections. emptyList(), + 0); + } + +} diff --git a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/ResultComparatorTest.java b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/ResultComparatorTest.java index 6d042d1fa..237fc507e 100644 --- a/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/ResultComparatorTest.java +++ b/pitest-html-report/src/test/java/org/pitest/mutationtest/report/html/ResultComparatorTest.java @@ -1,34 +1,34 @@ -package org.pitest.mutationtest.report.html; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationResult; -import org.pitest.mutationtest.MutationStatusTestPair; - -public class ResultComparatorTest { - - private final ResultComparator testee = new ResultComparator(); - - @Test - public void shouldSortInDesiredOrder() { - final List mrs = Arrays.asList( - make(DetectionStatus.TIMED_OUT), make(DetectionStatus.SURVIVED), - make(DetectionStatus.NO_COVERAGE), make(DetectionStatus.KILLED)); - Collections.sort(mrs, this.testee); - assertEquals(DetectionStatus.SURVIVED,mrs.get(0).getStatus()); - assertEquals(DetectionStatus.NO_COVERAGE,mrs.get(1).getStatus()); - assertEquals(DetectionStatus.TIMED_OUT,mrs.get(2).getStatus()); - assertEquals(DetectionStatus.KILLED,mrs.get(3).getStatus()); - } - - private MutationResult make(final DetectionStatus status) { - return new MutationResult(null, new MutationStatusTestPair(0, status)); - } - -} +package org.pitest.mutationtest.report.html; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationResult; +import org.pitest.mutationtest.MutationStatusTestPair; + +public class ResultComparatorTest { + + private final ResultComparator testee = new ResultComparator(); + + @Test + public void shouldSortInDesiredOrder() { + final List mrs = Arrays.asList( + make(DetectionStatus.TIMED_OUT), make(DetectionStatus.SURVIVED), + make(DetectionStatus.NO_COVERAGE), make(DetectionStatus.KILLED)); + Collections.sort(mrs, this.testee); + assertEquals(DetectionStatus.SURVIVED,mrs.get(0).getStatus()); + assertEquals(DetectionStatus.NO_COVERAGE,mrs.get(1).getStatus()); + assertEquals(DetectionStatus.TIMED_OUT,mrs.get(2).getStatus()); + assertEquals(DetectionStatus.KILLED,mrs.get(3).getStatus()); + } + + private MutationResult make(final DetectionStatus status) { + return new MutationResult(null, new MutationStatusTestPair(0, status)); + } + +} diff --git a/pitest-java8-verification/pom.xml b/pitest-java8-verification/pom.xml index 61522132f..7e30b3d81 100644 --- a/pitest-java8-verification/pom.xml +++ b/pitest-java8-verification/pom.xml @@ -1,70 +1,70 @@ - - - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - 4.0.0 - - pitest-java8-verification - Checks pitest against Java8 features - (pitest project is itself Java 5-based only). - - - - - - - maven-deploy-plugin - - true - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - maven-compiler-plugin - - 1.8 - 1.8 - - - - maven-failsafe-plugin - - - - integration-test - verify - - - - - - - - - - junit - junit - ${junit.version} - test - - - org.pitest - pitest-entry - ${project.version} - test - - - org.pitest - pitest-entry - test-jar - ${project.version} - test - - - + + + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + 4.0.0 + + pitest-java8-verification + Checks pitest against Java8 features + (pitest project is itself Java 5-based only). + + + + + + + maven-deploy-plugin + + true + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + maven-compiler-plugin + + 1.8 + 1.8 + + + + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + + + + junit + junit + ${junit.version} + test + + + org.pitest + pitest-entry + ${project.version} + test + + + org.pitest + pitest-entry + test-jar + ${project.version} + test + + + diff --git a/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityInsideSwitchTestee.java b/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityInsideSwitchTestee.java index 335f49ea6..9ea6ac31e 100644 --- a/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityInsideSwitchTestee.java +++ b/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityInsideSwitchTestee.java @@ -1,28 +1,28 @@ -package com.example.java7; - -public class HasIfOnAStringEqualityInsideSwitchTestee { - public String ifStringInsideSwitch(final String input, final String input2) { - final String result; - - switch (input) { - case "a": - if (input2.equals("a")) { - result = "A"; - } else { - result = "AX"; - } - break; - case "b": - result = "B"; - break; - case "c": - result = "C"; - break; - default: - throw new IllegalArgumentException("Unsupported input"); - } - - return result; - } - -} +package com.example.java7; + +public class HasIfOnAStringEqualityInsideSwitchTestee { + public String ifStringInsideSwitch(final String input, final String input2) { + final String result; + + switch (input) { + case "a": + if (input2.equals("a")) { + result = "A"; + } else { + result = "AX"; + } + break; + case "b": + result = "B"; + break; + case "c": + result = "C"; + break; + default: + throw new IllegalArgumentException("Unsupported input"); + } + + return result; + } + +} diff --git a/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityInsideSwitchTesteeTest.java b/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityInsideSwitchTesteeTest.java index 522d2071d..c34e4af78 100644 --- a/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityInsideSwitchTesteeTest.java +++ b/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityInsideSwitchTesteeTest.java @@ -1,76 +1,76 @@ -package com.example.java7; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -public class HasIfOnAStringEqualityInsideSwitchTesteeTest { - - private final HasIfOnAStringEqualityInsideSwitchTestee testee = new HasIfOnAStringEqualityInsideSwitchTestee(); - - @Test - public void stringSwitchShouldReturnA() throws Exception { - // given - final String input = "a"; - final String input2 = "a"; - - // when - final String result = testee.ifStringInsideSwitch(input, input2); - - // then - assertThat(result).isEqualTo("A"); - } - - @Test - public void stringSwitchShouldReturnAX() throws Exception { - // given - final String input = "a"; - final String input2 = "other"; - - // when - final String result = testee.ifStringInsideSwitch(input, input2); - - // then - assertThat(result).isEqualTo("AX"); - } - - @Test - public void stringSwitchShouldReturnB() throws Exception { - // given - final String input = "b"; - final String input2 = "x"; - - // when - final String result = testee.ifStringInsideSwitch(input, input2); - - // then - assertThat(result).isEqualTo("B"); - } - - @Test - public void stringSwitchShouldReturnC() throws Exception { - // given - final String input = "c"; - final String input2 = "x"; - - // when - final String result = testee.ifStringInsideSwitch(input, input2); - - // then - assertThat(result).isEqualTo("C"); - } - - @Test(expected = IllegalArgumentException.class) - public void stringSwitchShouldThrowIllegalArgumentException() - throws Exception { - // given - final String input = "x"; - final String input2 = "x"; - - // when - testee.ifStringInsideSwitch(input, input2); - - // then - // exception - } -} +package com.example.java7; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class HasIfOnAStringEqualityInsideSwitchTesteeTest { + + private final HasIfOnAStringEqualityInsideSwitchTestee testee = new HasIfOnAStringEqualityInsideSwitchTestee(); + + @Test + public void stringSwitchShouldReturnA() throws Exception { + // given + final String input = "a"; + final String input2 = "a"; + + // when + final String result = testee.ifStringInsideSwitch(input, input2); + + // then + assertThat(result).isEqualTo("A"); + } + + @Test + public void stringSwitchShouldReturnAX() throws Exception { + // given + final String input = "a"; + final String input2 = "other"; + + // when + final String result = testee.ifStringInsideSwitch(input, input2); + + // then + assertThat(result).isEqualTo("AX"); + } + + @Test + public void stringSwitchShouldReturnB() throws Exception { + // given + final String input = "b"; + final String input2 = "x"; + + // when + final String result = testee.ifStringInsideSwitch(input, input2); + + // then + assertThat(result).isEqualTo("B"); + } + + @Test + public void stringSwitchShouldReturnC() throws Exception { + // given + final String input = "c"; + final String input2 = "x"; + + // when + final String result = testee.ifStringInsideSwitch(input, input2); + + // then + assertThat(result).isEqualTo("C"); + } + + @Test(expected = IllegalArgumentException.class) + public void stringSwitchShouldThrowIllegalArgumentException() + throws Exception { + // given + final String input = "x"; + final String input2 = "x"; + + // when + testee.ifStringInsideSwitch(input, input2); + + // then + // exception + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityTestee.java b/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityTestee.java index 78df12a20..846a7e8f6 100644 --- a/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityTestee.java +++ b/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityTestee.java @@ -1,20 +1,20 @@ -package com.example.java7; - -public class HasIfOnAStringEqualityTestee { - public String ifString(final String input) { - final String result; - - if (input.equals("a")) { - result = "A"; - } else if (input.equals("b")) { - result = "B"; - } else if (input.equals("c")) { - result = "C"; - } else { - throw new IllegalArgumentException("Unsupported input"); - } - - return result; - } - -} +package com.example.java7; + +public class HasIfOnAStringEqualityTestee { + public String ifString(final String input) { + final String result; + + if (input.equals("a")) { + result = "A"; + } else if (input.equals("b")) { + result = "B"; + } else if (input.equals("c")) { + result = "C"; + } else { + throw new IllegalArgumentException("Unsupported input"); + } + + return result; + } + +} diff --git a/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityTesteeTest.java b/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityTesteeTest.java index e408ef664..600dedb71 100644 --- a/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityTesteeTest.java +++ b/pitest-java8-verification/src/test/java/com/example/java7/HasIfOnAStringEqualityTesteeTest.java @@ -1,58 +1,58 @@ -package com.example.java7; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -public class HasIfOnAStringEqualityTesteeTest { - - private final HasIfOnAStringEqualityTestee testee = new HasIfOnAStringEqualityTestee(); - - @Test - public void ifStringShouldReturnA() throws Exception { - // given - final String input = "a"; - - // when - final String result = testee.ifString(input); - - // then - assertThat(result).isEqualTo("A"); - } - - @Test - public void ifStringShouldReturnB() throws Exception { - // given - final String input = "b"; - - // when - final String result = testee.ifString(input); - - // then - assertThat(result).isEqualTo("B"); - } - - @Test - public void ifStringShouldReturnC() throws Exception { - // given - final String input = "c"; - - // when - final String result = testee.ifString(input); - - // then - assertThat(result).isEqualTo("C"); - } - - @Test(expected = IllegalArgumentException.class) - public void ifStringShouldThrowIllegalArgumentException() throws Exception { - // given - final String input = "x"; - - // when - testee.ifString(input); - - // then - // exception - } -} +package com.example.java7; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class HasIfOnAStringEqualityTesteeTest { + + private final HasIfOnAStringEqualityTestee testee = new HasIfOnAStringEqualityTestee(); + + @Test + public void ifStringShouldReturnA() throws Exception { + // given + final String input = "a"; + + // when + final String result = testee.ifString(input); + + // then + assertThat(result).isEqualTo("A"); + } + + @Test + public void ifStringShouldReturnB() throws Exception { + // given + final String input = "b"; + + // when + final String result = testee.ifString(input); + + // then + assertThat(result).isEqualTo("B"); + } + + @Test + public void ifStringShouldReturnC() throws Exception { + // given + final String input = "c"; + + // when + final String result = testee.ifString(input); + + // then + assertThat(result).isEqualTo("C"); + } + + @Test(expected = IllegalArgumentException.class) + public void ifStringShouldThrowIllegalArgumentException() throws Exception { + // given + final String input = "x"; + + // when + testee.ifString(input); + + // then + // exception + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java7/HasSwitchOnStringTestee.java b/pitest-java8-verification/src/test/java/com/example/java7/HasSwitchOnStringTestee.java index fd38a244c..368c1578c 100644 --- a/pitest-java8-verification/src/test/java/com/example/java7/HasSwitchOnStringTestee.java +++ b/pitest-java8-verification/src/test/java/com/example/java7/HasSwitchOnStringTestee.java @@ -1,62 +1,62 @@ -package com.example.java7; - -public class HasSwitchOnStringTestee { - - public String switchIntegerAndThenSwitchString(final Integer input) { - final String partial; - - switch (input) { - case 1: - partial = "A"; - break; - case 2: - partial = "B"; - break; - case 3: - partial = "C"; - break; - default: - throw new IllegalArgumentException("Unsupported input"); - } - - final String result; - - switch (partial) { - case "A": - result = "A1"; - break; - case "B": - result = "B1"; - break; - case "C": - result = "C1"; - break; - default: - throw new IllegalArgumentException("Unsupported input"); - } - - return result; - } - - public String switchString(final String input) { - - final String result; - - switch (input) { - case "a": - result = "A"; - break; - case "b": - result = "B"; - break; - case "c": - result = "C"; - break; - default: - throw new IllegalArgumentException("Unsupported input"); - } - - return result; - } - -} +package com.example.java7; + +public class HasSwitchOnStringTestee { + + public String switchIntegerAndThenSwitchString(final Integer input) { + final String partial; + + switch (input) { + case 1: + partial = "A"; + break; + case 2: + partial = "B"; + break; + case 3: + partial = "C"; + break; + default: + throw new IllegalArgumentException("Unsupported input"); + } + + final String result; + + switch (partial) { + case "A": + result = "A1"; + break; + case "B": + result = "B1"; + break; + case "C": + result = "C1"; + break; + default: + throw new IllegalArgumentException("Unsupported input"); + } + + return result; + } + + public String switchString(final String input) { + + final String result; + + switch (input) { + case "a": + result = "A"; + break; + case "b": + result = "B"; + break; + case "c": + result = "C"; + break; + default: + throw new IllegalArgumentException("Unsupported input"); + } + + return result; + } + +} diff --git a/pitest-java8-verification/src/test/java/com/example/java7/HasSwitchOnStringTesteeTest.java b/pitest-java8-verification/src/test/java/com/example/java7/HasSwitchOnStringTesteeTest.java index 8589ab2e3..04b197109 100644 --- a/pitest-java8-verification/src/test/java/com/example/java7/HasSwitchOnStringTesteeTest.java +++ b/pitest-java8-verification/src/test/java/com/example/java7/HasSwitchOnStringTesteeTest.java @@ -1,110 +1,110 @@ -package com.example.java7; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -public class HasSwitchOnStringTesteeTest { - - private final HasSwitchOnStringTestee testee = new HasSwitchOnStringTestee(); - - @Test - public void stringSwitchShouldReturnA() throws Exception { - // given - final String input = "a"; - - // when - final String result = testee.switchString(input); - - // then - assertThat(result).isEqualTo("A"); - } - - @Test - public void stringSwitchShouldReturnB() throws Exception { - // given - final String input = "b"; - - // when - final String result = testee.switchString(input); - - // then - assertThat(result).isEqualTo("B"); - } - - @Test - public void stringSwitchShouldReturnC() throws Exception { - // given - final String input = "c"; - - // when - final String result = testee.switchString(input); - - // then - assertThat(result).isEqualTo("C"); - } - - @Test(expected = IllegalArgumentException.class) - public void stringSwitchShouldThrowIllegalArgumentException() - throws Exception { - // given - final String input = "x"; - - // when - testee.switchString(input); - - // then - // exception - } - - @Test - public void switchIntegerAndThenSwitchStringShouldReturnA1() - throws Exception { - // given - final int input = 1; - - // when - final String result = testee.switchIntegerAndThenSwitchString(input); - - // then - assertThat(result).isEqualTo("A1"); - } - - @Test - public void switchIntegerAndThenSwitchStringShouldReturnB1() - throws Exception { - // given - final int input = 2; - - // when - final String result = testee.switchIntegerAndThenSwitchString(input); - - // then - assertThat(result).isEqualTo("B1"); - } - - @Test - public void switchIntegerAndThenSwitchStringShouldReturnC1() - throws Exception { - // given - final int input = 3; - - // when - final String result = testee.switchIntegerAndThenSwitchString(input); - - // then - assertThat(result).isEqualTo("C1"); - } - - @Test(expected = IllegalArgumentException.class) - public void switchIntegerAndThenSwitchStringShouldThrowIllegalArgumentException() - throws Exception { - // given - final int input = 4; - - // when - testee.switchIntegerAndThenSwitchString(input); - - // then - } -} +package com.example.java7; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class HasSwitchOnStringTesteeTest { + + private final HasSwitchOnStringTestee testee = new HasSwitchOnStringTestee(); + + @Test + public void stringSwitchShouldReturnA() throws Exception { + // given + final String input = "a"; + + // when + final String result = testee.switchString(input); + + // then + assertThat(result).isEqualTo("A"); + } + + @Test + public void stringSwitchShouldReturnB() throws Exception { + // given + final String input = "b"; + + // when + final String result = testee.switchString(input); + + // then + assertThat(result).isEqualTo("B"); + } + + @Test + public void stringSwitchShouldReturnC() throws Exception { + // given + final String input = "c"; + + // when + final String result = testee.switchString(input); + + // then + assertThat(result).isEqualTo("C"); + } + + @Test(expected = IllegalArgumentException.class) + public void stringSwitchShouldThrowIllegalArgumentException() + throws Exception { + // given + final String input = "x"; + + // when + testee.switchString(input); + + // then + // exception + } + + @Test + public void switchIntegerAndThenSwitchStringShouldReturnA1() + throws Exception { + // given + final int input = 1; + + // when + final String result = testee.switchIntegerAndThenSwitchString(input); + + // then + assertThat(result).isEqualTo("A1"); + } + + @Test + public void switchIntegerAndThenSwitchStringShouldReturnB1() + throws Exception { + // given + final int input = 2; + + // when + final String result = testee.switchIntegerAndThenSwitchString(input); + + // then + assertThat(result).isEqualTo("B1"); + } + + @Test + public void switchIntegerAndThenSwitchStringShouldReturnC1() + throws Exception { + // given + final int input = 3; + + // when + final String result = testee.switchIntegerAndThenSwitchString(input); + + // then + assertThat(result).isEqualTo("C1"); + } + + @Test(expected = IllegalArgumentException.class) + public void switchIntegerAndThenSwitchStringShouldThrowIllegalArgumentException() + throws Exception { + // given + final int input = 4; + + // when + testee.switchIntegerAndThenSwitchString(input); + + // then + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java8/AnonymousClass.java b/pitest-java8-verification/src/test/java/com/example/java8/AnonymousClass.java index b4ad4c3f3..2f2597276 100644 --- a/pitest-java8-verification/src/test/java/com/example/java8/AnonymousClass.java +++ b/pitest-java8-verification/src/test/java/com/example/java8/AnonymousClass.java @@ -1,21 +1,21 @@ -package com.example.java8; - -/** - * @author iirekm@gmail.com - */ -public class AnonymousClass { - public int foo() { - final int[] result = new int[1]; - Runnable r = new Runnable() { - @Override - public void run() { - int i = 1; - i++; - i++; - result[0] = i; - } - }; - r.run(); - return result[0]; - } -} +package com.example.java8; + +/** + * @author iirekm@gmail.com + */ +public class AnonymousClass { + public int foo() { + final int[] result = new int[1]; + Runnable r = new Runnable() { + @Override + public void run() { + int i = 1; + i++; + i++; + result[0] = i; + } + }; + r.run(); + return result[0]; + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java8/AnonymousClassTest.java b/pitest-java8-verification/src/test/java/com/example/java8/AnonymousClassTest.java index 8880904a7..7fc812f67 100644 --- a/pitest-java8-verification/src/test/java/com/example/java8/AnonymousClassTest.java +++ b/pitest-java8-verification/src/test/java/com/example/java8/AnonymousClassTest.java @@ -1,17 +1,17 @@ -package com.example.java8; - -import org.junit.Test; - -import com.example.java8.AnonymousClass; - -import static org.junit.Assert.assertEquals; - -/** - * @author iirekm@gmail.com - */ -public class AnonymousClassTest { - @Test - public void works() { - assertEquals(3, new AnonymousClass().foo()); - } -} +package com.example.java8; + +import org.junit.Test; + +import com.example.java8.AnonymousClass; + +import static org.junit.Assert.assertEquals; + +/** + * @author iirekm@gmail.com + */ +public class AnonymousClassTest { + @Test + public void works() { + assertEquals(3, new AnonymousClass().foo()); + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java8/Java8Class.java b/pitest-java8-verification/src/test/java/com/example/java8/Java8Class.java index a71f0dc85..40886ff17 100644 --- a/pitest-java8-verification/src/test/java/com/example/java8/Java8Class.java +++ b/pitest-java8-verification/src/test/java/com/example/java8/Java8Class.java @@ -1,13 +1,13 @@ -package com.example.java8; - -/** - * @author iirekm@gmail.com - */ -public class Java8Class { - public int foo() { - int i = 1; - i++; - i++; - return i; - } -} +package com.example.java8; + +/** + * @author iirekm@gmail.com + */ +public class Java8Class { + public int foo() { + int i = 1; + i++; + i++; + return i; + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java8/Java8ClassTest.java b/pitest-java8-verification/src/test/java/com/example/java8/Java8ClassTest.java index 664c61f2c..4b38612b1 100644 --- a/pitest-java8-verification/src/test/java/com/example/java8/Java8ClassTest.java +++ b/pitest-java8-verification/src/test/java/com/example/java8/Java8ClassTest.java @@ -1,15 +1,15 @@ -package com.example.java8; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author iirekm@gmail.com - */ -public class Java8ClassTest { - @Test - public void works() { - assertEquals(3, new Java8Class().foo()); - } -} +package com.example.java8; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author iirekm@gmail.com + */ +public class Java8ClassTest { + @Test + public void works() { + assertEquals(3, new Java8Class().foo()); + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java8/Java8Interface.java b/pitest-java8-verification/src/test/java/com/example/java8/Java8Interface.java index 76c8ebd40..6d8bf63fd 100644 --- a/pitest-java8-verification/src/test/java/com/example/java8/Java8Interface.java +++ b/pitest-java8-verification/src/test/java/com/example/java8/Java8Interface.java @@ -1,13 +1,13 @@ -package com.example.java8; - -/** - * @author iirekm@gmail.com - */ -public interface Java8Interface { - default int foo() { - int i = 1; - i++; - i++; - return i; - } -} +package com.example.java8; + +/** + * @author iirekm@gmail.com + */ +public interface Java8Interface { + default int foo() { + int i = 1; + i++; + i++; + return i; + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java8/Java8InterfaceTest.java b/pitest-java8-verification/src/test/java/com/example/java8/Java8InterfaceTest.java index 658ecd42b..ada0fd2e3 100644 --- a/pitest-java8-verification/src/test/java/com/example/java8/Java8InterfaceTest.java +++ b/pitest-java8-verification/src/test/java/com/example/java8/Java8InterfaceTest.java @@ -1,15 +1,15 @@ -package com.example.java8; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author iirekm@gmail.com - */ -public class Java8InterfaceTest { - @Test - public void works() { - assertEquals(3, new Java8Interface() {}.foo()); - } -} +package com.example.java8; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author iirekm@gmail.com + */ +public class Java8InterfaceTest { + @Test + public void works() { + assertEquals(3, new Java8Interface() {}.foo()); + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java8/Java8LambdaExpression.java b/pitest-java8-verification/src/test/java/com/example/java8/Java8LambdaExpression.java index c62a1945b..050671cea 100644 --- a/pitest-java8-verification/src/test/java/com/example/java8/Java8LambdaExpression.java +++ b/pitest-java8-verification/src/test/java/com/example/java8/Java8LambdaExpression.java @@ -1,18 +1,18 @@ -package com.example.java8; - -/** - * @author iirekm@gmail.com - */ -public class Java8LambdaExpression { - public int foo() { - final int[] result = new int[1]; - Runnable r = () -> { - int i = 1; - i++; - i++; - result[0] = i; - }; - r.run(); - return result[0]; - } -} +package com.example.java8; + +/** + * @author iirekm@gmail.com + */ +public class Java8LambdaExpression { + public int foo() { + final int[] result = new int[1]; + Runnable r = () -> { + int i = 1; + i++; + i++; + result[0] = i; + }; + r.run(); + return result[0]; + } +} diff --git a/pitest-java8-verification/src/test/java/com/example/java8/Java8LambdaExpressionTest.java b/pitest-java8-verification/src/test/java/com/example/java8/Java8LambdaExpressionTest.java index 7228aa952..3bce543f5 100644 --- a/pitest-java8-verification/src/test/java/com/example/java8/Java8LambdaExpressionTest.java +++ b/pitest-java8-verification/src/test/java/com/example/java8/Java8LambdaExpressionTest.java @@ -1,15 +1,15 @@ -package com.example.java8; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author iirekm@gmail.com - */ -public class Java8LambdaExpressionTest { - @Test - public void works() { - assertEquals(3, new Java8LambdaExpression().foo()); - } -} +package com.example.java8; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author iirekm@gmail.com + */ +public class Java8LambdaExpressionTest { + @Test + public void works() { + assertEquals(3, new Java8LambdaExpression().foo()); + } +} diff --git a/pitest-java8-verification/src/test/java/org/pitest/java7/verification/VerifyJava7IT.java b/pitest-java8-verification/src/test/java/org/pitest/java7/verification/VerifyJava7IT.java index 436a03f28..b760f07a3 100644 --- a/pitest-java8-verification/src/test/java/org/pitest/java7/verification/VerifyJava7IT.java +++ b/pitest-java8-verification/src/test/java/org/pitest/java7/verification/VerifyJava7IT.java @@ -1,40 +1,40 @@ -package org.pitest.java7.verification; - -import static org.pitest.mutationtest.DetectionStatus.KILLED; -import static java.util.Arrays.asList; - -import org.junit.Test; -import org.pitest.mutationtest.ReportTestBase; - -public class VerifyJava7IT extends ReportTestBase { - - @Test - public void shouldMutateIfElseOnAStringEqualityWithREMOVE_CONDITIONALS() { - setMutators("REMOVE_CONDITIONALS"); - this.data.setTargetClasses( - asList("com.example.java7.HasIfOnAStringEqualityTestee*")); - this.data.setVerbose(true); - createAndRun(); - verifyResults(KILLED, KILLED, KILLED, KILLED, KILLED, KILLED); - } - - @Test - public void shouldMutateIfElseOnAStringEqualityWithREMOVE_CONDITIONALSWhenInsideSwitchOnString() { - setMutators("REMOVE_CONDITIONALS"); - this.data.setTargetClasses(asList( - "com.example.java7.HasIfOnAStringEqualityInsideSwitchTestee*")); - this.data.setVerbose(true); - createAndRun(); - verifyResults(KILLED, KILLED); - } - - @Test - public void shouldNotMutateSwitchOnAStringWithREMOVE_CONDITIONALS() { - setMutators("REMOVE_CONDITIONALS"); - this.data.setTargetClasses( - asList("com.example.java7.HasSwitchOnStringTestee*")); - this.data.setVerbose(true); - createAndRun(); - verifyResults(); - } -} +package org.pitest.java7.verification; + +import static org.pitest.mutationtest.DetectionStatus.KILLED; +import static java.util.Arrays.asList; + +import org.junit.Test; +import org.pitest.mutationtest.ReportTestBase; + +public class VerifyJava7IT extends ReportTestBase { + + @Test + public void shouldMutateIfElseOnAStringEqualityWithREMOVE_CONDITIONALS() { + setMutators("REMOVE_CONDITIONALS"); + this.data.setTargetClasses( + asList("com.example.java7.HasIfOnAStringEqualityTestee*")); + this.data.setVerbose(true); + createAndRun(); + verifyResults(KILLED, KILLED, KILLED, KILLED, KILLED, KILLED); + } + + @Test + public void shouldMutateIfElseOnAStringEqualityWithREMOVE_CONDITIONALSWhenInsideSwitchOnString() { + setMutators("REMOVE_CONDITIONALS"); + this.data.setTargetClasses(asList( + "com.example.java7.HasIfOnAStringEqualityInsideSwitchTestee*")); + this.data.setVerbose(true); + createAndRun(); + verifyResults(KILLED, KILLED); + } + + @Test + public void shouldNotMutateSwitchOnAStringWithREMOVE_CONDITIONALS() { + setMutators("REMOVE_CONDITIONALS"); + this.data.setTargetClasses( + asList("com.example.java7.HasSwitchOnStringTestee*")); + this.data.setVerbose(true); + createAndRun(); + verifyResults(); + } +} diff --git a/pitest-java8-verification/src/test/java/org/pitest/java8/verification/VerifyJava8IT.java b/pitest-java8-verification/src/test/java/org/pitest/java8/verification/VerifyJava8IT.java index b6f6698e2..6ea39d420 100644 --- a/pitest-java8-verification/src/test/java/org/pitest/java8/verification/VerifyJava8IT.java +++ b/pitest-java8-verification/src/test/java/org/pitest/java8/verification/VerifyJava8IT.java @@ -1,67 +1,67 @@ -package org.pitest.java8.verification; - -import static org.pitest.mutationtest.DetectionStatus.KILLED; -import static java.util.Arrays.asList; - -import org.junit.Test; -import org.pitest.mutationtest.ReportTestBase; - -import com.example.java8.AnonymousClassTest; -import com.example.java8.Java8ClassTest; -import com.example.java8.Java8InterfaceTest; -import com.example.java8.Java8LambdaExpressionTest; - - -public class VerifyJava8IT extends ReportTestBase { - - /** - * @author iirekm@gmail.com - */ - @Test - public void worksWithJava8Bytecode() { - this.data.setTargetTests(predicateFor(Java8ClassTest.class)); - this.data.setTargetClasses(asList("com.example.java8.Java8Class*")); - setMutators("INCREMENTS"); - createAndRun(); - verifyResults(KILLED, KILLED); - } - - /** - * @author iirekm@gmail.com - */ - @Test - public void worksWithJava8DefaultInterfaceMethods() { - this.data.setTargetTests(predicateFor(Java8InterfaceTest.class)); - this.data.setTargetClasses(asList("com.example.java8.Java8Interface*")); - setMutators("INCREMENTS"); - createAndRun(); - verifyResults(KILLED, KILLED); - } - - /** - * @author iirekm@gmail.com - * - * Initial step for Java 8 lambda expressions: check if pure anonymous classes work. - */ - @Test - public void worksWithAnonymousClasses() { - this.data.setTargetTests(predicateFor(AnonymousClassTest.class)); - this.data.setTargetClasses(asList("com.example.java8.AnonymousClass*")); - setMutators("INCREMENTS"); - createAndRun(); - verifyResults(KILLED, KILLED); - } - - /** - * @author iirekm@gmail.com - */ - @Test - public void worksWithJava8LambdaExpressions() { - this.data.setTargetTests(predicateFor(Java8LambdaExpressionTest.class)); - this.data.setTargetClasses(asList("com.example.java8.Java8LambdaExpression*")); - setMutators("INCREMENTS"); - createAndRun(); - verifyResults(KILLED, KILLED); - } - -} +package org.pitest.java8.verification; + +import static org.pitest.mutationtest.DetectionStatus.KILLED; +import static java.util.Arrays.asList; + +import org.junit.Test; +import org.pitest.mutationtest.ReportTestBase; + +import com.example.java8.AnonymousClassTest; +import com.example.java8.Java8ClassTest; +import com.example.java8.Java8InterfaceTest; +import com.example.java8.Java8LambdaExpressionTest; + + +public class VerifyJava8IT extends ReportTestBase { + + /** + * @author iirekm@gmail.com + */ + @Test + public void worksWithJava8Bytecode() { + this.data.setTargetTests(predicateFor(Java8ClassTest.class)); + this.data.setTargetClasses(asList("com.example.java8.Java8Class*")); + setMutators("INCREMENTS"); + createAndRun(); + verifyResults(KILLED, KILLED); + } + + /** + * @author iirekm@gmail.com + */ + @Test + public void worksWithJava8DefaultInterfaceMethods() { + this.data.setTargetTests(predicateFor(Java8InterfaceTest.class)); + this.data.setTargetClasses(asList("com.example.java8.Java8Interface*")); + setMutators("INCREMENTS"); + createAndRun(); + verifyResults(KILLED, KILLED); + } + + /** + * @author iirekm@gmail.com + * + * Initial step for Java 8 lambda expressions: check if pure anonymous classes work. + */ + @Test + public void worksWithAnonymousClasses() { + this.data.setTargetTests(predicateFor(AnonymousClassTest.class)); + this.data.setTargetClasses(asList("com.example.java8.AnonymousClass*")); + setMutators("INCREMENTS"); + createAndRun(); + verifyResults(KILLED, KILLED); + } + + /** + * @author iirekm@gmail.com + */ + @Test + public void worksWithJava8LambdaExpressions() { + this.data.setTargetTests(predicateFor(Java8LambdaExpressionTest.class)); + this.data.setTargetClasses(asList("com.example.java8.Java8LambdaExpression*")); + setMutators("INCREMENTS"); + createAndRun(); + verifyResults(KILLED, KILLED); + } + +} diff --git a/pitest-maven-verification/pom.xml b/pitest-maven-verification/pom.xml index ac8065b1d..9c7fd2179 100644 --- a/pitest-maven-verification/pom.xml +++ b/pitest-maven-verification/pom.xml @@ -1,111 +1,111 @@ - - - 4.0.0 - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - pitest-maven-verification - jar - pitest-maven-verification - Pitest Maven Mojo integration tests. - http://pitest.org - - - - - - maven-deploy-plugin - - true - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - - maven-surefire-plugin - - true - - - - maven-failsafe-plugin - - - - integration-test - verify - - - - - - - - - org.pitest - pitest-maven - ${project.version} - - - - org.apache.maven - maven-plugin-api - ${maven.version} - - - org.apache.maven - maven-project - ${maven.version} - - - org.apache.maven - maven-artifact - ${maven.version} - - - org.apache.maven - maven-toolchain - ${maven.version} - - - org.slf4j - slf4j-nop - - - org.slf4j - slf4j-jdk14 - - - org.slf4j - jcl-over-slf4j - - - - - org.slf4j - slf4j-simple - ${slf4j.version} - - - - - org.apache.maven.shared - maven-plugin-testing-harness - 1.1 - test - - - org.apache.maven.shared - maven-verifier - ${maven-verifier} - test - - - - + + + 4.0.0 + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + pitest-maven-verification + jar + pitest-maven-verification + Pitest Maven Mojo integration tests. + http://pitest.org + + + + + + maven-deploy-plugin + + true + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + + maven-surefire-plugin + + true + + + + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + + + org.pitest + pitest-maven + ${project.version} + + + + org.apache.maven + maven-plugin-api + ${maven.version} + + + org.apache.maven + maven-project + ${maven.version} + + + org.apache.maven + maven-artifact + ${maven.version} + + + org.apache.maven + maven-toolchain + ${maven.version} + + + org.slf4j + slf4j-nop + + + org.slf4j + slf4j-jdk14 + + + org.slf4j + jcl-over-slf4j + + + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + + + org.apache.maven.shared + maven-plugin-testing-harness + 1.1 + test + + + org.apache.maven.shared + maven-verifier + ${maven-verifier} + test + + + + diff --git a/pitest-maven-verification/src/test/java/org/pitest/PitMojoIT.java b/pitest-maven-verification/src/test/java/org/pitest/PitMojoIT.java index dd76d92dd..159cf4fa4 100644 --- a/pitest-maven-verification/src/test/java/org/pitest/PitMojoIT.java +++ b/pitest-maven-verification/src/test/java/org/pitest/PitMojoIT.java @@ -1,518 +1,518 @@ -/* - * Copyright 2011 Henry Coles and Stefan Penndorf - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.pitest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import org.apache.commons.io.FileUtils; -import org.apache.maven.it.VerificationException; -import org.apache.maven.it.Verifier; -import org.apache.maven.it.util.ResourceExtractor; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.rules.TestName; -import org.pitest.support.DirectoriesOnlyWalker; -import org.pitest.testapi.execute.Pitest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Stefan Penndorf - */ -public class PitMojoIT { - private static Logger LOGGER = LoggerFactory.getLogger(PitMojoIT.class); - private static String VERSION = getVersion(); - - @Rule - public TestName testName = new TestName(); - - @Rule - public TemporaryFolder testFolder = new TemporaryFolder(); - - private Verifier verifier; - private long startTime; - - @Before - public void beforeEachTest() { - LOGGER.info("running test '{}'", testName.getMethodName()); - startTime = System.currentTimeMillis(); - } - - @After - public void afterEachTest() { - LOGGER.info("duration of test '{}' {}ms", testName.getMethodName(), - System.currentTimeMillis() - startTime); - } - - @Test - public void shouldSetUserDirToArtefactWorkingDirectory() throws Exception { - prepare("/pit-33-setUserDir"); - - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - } - - @Test(timeout=60000) - public void shouldNotHangWhenLargeAmountsOfConsoleOutput() throws Exception { - File testDir = prepare("/pit-process-hang"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - // checkout output looks sane, but main point is that test completed - assertThat(readResults(testDir)) - .contains( - "SomeCode.java"); - } - - @Test - public void shouldProduceConsistantCoverageData() throws Exception { - File testDir = prepare("/pit-deterministic-coverage"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String firstRun = readCoverage(testDir); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String secondRun = readCoverage(testDir); - assertEquals(firstRun, secondRun); - } - - @Test - public void shouldWorkWithTestNG() throws Exception { - File testDir = prepare("/pit-testng"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String actual = readResults(testDir); - assertThat(actual) - .contains( - "Covered.java"); - assertThat(actual) - .contains( - "Covered.java"); - assertThat(actual).doesNotContain("status='RUN_ERROR'"); - } - - @Test - public void shouldWorkWithTestNGAndJMockit() throws Exception { - File testDir = prepare("/pit-testng-jmockit"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String actual = readResults(testDir); - assertThat(actual) - .contains( - "Covered.java"); - assertThat(actual) - .contains( - "Covered.java"); - assertThat(actual).doesNotContain("status='RUN_ERROR'"); - } - - @Test - public void shouldExcludeSpecifiedJUnitCategories() throws Exception { - File testDir = prepare("/pit-junit-categories"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String actual = readResults(testDir); - String coverage = readCoverage(testDir); - assertThat(coverage).doesNotContain("NotCovered"); - assertThat(coverage).contains("Covered"); - assertThat(actual) - .contains( - "NotCovered.java"); - assertThat(actual) - .doesNotContain( - "NotCovered.java"); - assertThat(actual) - .contains( - "Covered.java"); - } - - @Test - //@Ignore("test is flakey, possibly due to real non deterministic issue with powermock") - public void shouldWorkWithPowerMock() throws Exception { - skipOnJava9(); - File testDir = prepare("/pit-powermock"); - verifier.addCliOption("-DtimeoutConstant=10000"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String actual = readResults(testDir); - assertThat(actual) - .contains( - "PowerMockAgentCallFoo.java"); - assertThat(actual) - .contains( - "PowerMockCallsOwnMethod.java"); - assertThat(actual) - .contains( - "PowerMockCallFoo.java"); - assertThat(actual).doesNotContain("status='RUN_ERROR'"); - assertThat(actual).doesNotContain("PowerMockCallsOwnMethod.javacom.example.PowerMockCallsOwnMethodbranchedCode"); - } - - @Test - public void shouldCorrectlyTargetTestsWhenMultipleBlocksIncludeALine() - throws Exception { - File testDir = prepare("/pit-158-coverage"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String actual = readResults(testDir); - assertThat(actual) - .contains( - "MyRequest.java"); - } - - /* - * Verifies that configuring report generation to be skipped does actually - * prevent the site report from being generated. - */ - @Test - public void shouldSkipSiteReportGeneration() throws Exception { - File testDir = prepareSiteTest("/pit-site-skip"); - File siteParentDir = buildFilePath(testDir, "target", "site"); - - verifier.executeGoal("site"); - - assertThat(siteParentDir).exists(); - assertThat(buildFilePath(siteParentDir, "pit-reports")).doesNotExist(); - assertThat(buildFilePath(siteParentDir, "index.html")).exists(); - assertThat(buildFilePath(siteParentDir, "project-reports.html")) - .doesNotExist(); - } - - /* - * Verifies that running PIT with timestampedReports set to false will - * correctly copy the HTML report to the site reports directory. - */ - @Test - public void shouldGenerateSiteReportWithNonTimestampedHtmlReport() - throws Exception { - File testDir = prepareSiteTest("/pit-site-non-timestamped"); - - verifier.executeGoal("site"); - verifyPitReportTest(testDir); - } - - /* - * Verifies that running PIT with timestampedReports set to true will copy the - * contents of the latest timestamped report - */ - @Test - public void shouldGenerateSiteReportWithSingleTimestampedHtmlReport() - throws Exception { - File testDir = prepareSiteTest("/pit-site-timestamped", "201505212116"); - - verifier.executeGoal("site"); - verifyPitReportTest(testDir); - } - - /* - * Verifies that, when multiple timestamped PIT reports have been generated, - * only the latest report is copied to the site reports directory. This test - * sets the earlier directory (201503292032) as the last modified. This tests - * to make sure the last modified date is used instead of just using the - * folder name. - */ - @Test - public void shouldCopyLatestTimestampedReportWhenMultipleTimestampedReportsExist() - throws Exception { - File testDir = prepareSiteTest("/pit-site-multiple-timestamped", - "201503292032"); - - verifier.executeGoal("site"); - verifyPitReportTest(testDir); - } - - /* - * Verifies that in the case where pit has generated reports with both - * timestampedReports=true and timestampedReports=false, the latest report run - * is copied and no timestamped report subdirectories are copied - */ - @Test - public void shouldCopyLatestTimestampedOrNonTimestampedReportWhenBothExist() - throws Exception { - File testDir = prepareSiteTest("/pit-site-combined", ""); - - verifier.executeGoal("site"); - verifyPitReportTest(testDir); - } - - /* - * Verifies that the build fails when running the report goal without first - * running the mutationCoverage goal - */ - @Test - public void shouldFailIfNoPITReportAvailable() throws Exception { - prepare("/pit-site-reportonly"); - - try { - verifier.executeGoal("site"); - fail("should fail"); - } catch (VerificationException e) { - assertThat(e.getMessage()) - .containsSequence( - "could not find reports directory"); - } - } - - /* - * verifies that overriding defaults has the expected results - */ - @Test - public void shouldCorrectlyHandleOverrides() throws Exception { - File testDir = prepareSiteTest("/pit-site-custom-config"); - File targetDir = buildFilePath(testDir, "target"); - File expectedSiteReportDir = buildFilePath(testDir, "target", "site", - "foobar"); - - FileUtils.moveDirectory(buildFilePath(targetDir, "pit-reports"), - buildFilePath(targetDir, "new-report-location")); - - verifier.executeGoal("site"); - - String projectReportsHtmlContents = FileUtils - .readFileToString(buildFilePath(testDir, "target", "site", - "project-reports.html")); - assertTrue( - "did not find expected anchor tag to pit site report", - projectReportsHtmlContents - .contains("my-test-pit-report-name")); - assertTrue("expected site report directory [" + expectedSiteReportDir - + "] does not exist but should exist", expectedSiteReportDir.exists()); - - assertFalse( - "expected default site report directory exists but should not exist since the report location parameter was overridden", - buildFilePath(testDir, "target", "site", "pit-reports").exists()); - } - - @Test - public void shouldReadExclusionsFromSurefireConfig() throws Exception { - File testDir = prepare("/pit-surefire-excludes"); - verifier.addCliOption("-DskipTests"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String actual = readResults(testDir); - assertThat(actual) - .contains( - "NotCovered.java"); - } - - @Test - public void shouldWorkWithGWTMockito() throws Exception { - skipOnJava9(); - File testDir = prepare("/pit-183-gwtmockito"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String actual = readResults(testDir); - assertThat(actual) - .contains( - "MyWidget.java"); - assertThat(actual) - .contains( - "MyWidget.java"); - assertThat(actual).doesNotContain("status='RUN_ERROR'"); - } - - private void skipOnJava9() { - assumeFalse(System.getProperty("java.version").startsWith("9")); - } - - @Test - public void shouldWorkWithYatspec() throws Exception { - File testDir = prepare("/pit-263-yatspec"); - verifier.executeGoal("test"); - verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); - - String actual = readResults(testDir); - assertThat(actual) - .contains( - "SomeClass.java"); - assertThat(actual).doesNotContain("status='NO_COVERAGE'"); - assertThat(actual).doesNotContain("status='RUN_ERROR'"); - } - - private static String readResults(File testDir) throws IOException { - File mutationReport = new File(testDir.getAbsoluteFile() + File.separator - + "target" + File.separator + "pit-reports" + File.separator - + "mutations.xml"); - return FileUtils.readFileToString(mutationReport); - } - - private static String readCoverage(File testDir) throws IOException { - File coverage = new File(testDir.getAbsoluteFile() + File.separator - + "target" + File.separator + "pit-reports" + File.separator - + "linecoverage.xml"); - return FileUtils.readFileToString(coverage); - } - - private File prepare(String testPath) throws IOException, - VerificationException { - String path = ResourceExtractor.extractResourcePath(getClass(), testPath, - testFolder.getRoot(), true).getAbsolutePath(); - - verifier = new Verifier(path); - verifier.setAutoclean(false); - verifier.setDebug(true); - verifier.getCliOptions().add("-Dpit.version=" + VERSION); - verifier.getCliOptions().add( - "-Dthreads=" + (Runtime.getRuntime().availableProcessors())); - - return new File(testFolder.getRoot().getAbsolutePath() + testPath); - } - - private static String getVersion() { - String path = "/version.prop"; - InputStream stream = Pitest.class.getResourceAsStream(path); - Properties props = new Properties(); - try { - props.load(stream); - stream.close(); - return (String) props.get("version"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Creates a new {@link File} object building off an existing {@link File} - * object and appending subfolders. - * - * For example, if this function is called with these arguments: - * buildFile(new File("/foo/bar"), "subdir1", "subdir2", "file1.txt"); - * The returned {@link File} object would represent the path: - * /foo/bar/subdir1/subdir/file1.txt - * - * @param base - * {@link File} representing the starting location - * @param pathParts - * {@link String} varags containing the subfolders to append to the - * base, this argument should contain at least one value and none of - * its values should be blank or null. - * - * @return {@link File} - */ - private File buildFilePath(File base, String... pathParts) { - StringBuilder path = new StringBuilder(base.getAbsolutePath()); - - for (String part : pathParts) { - path.append(File.separator).append(part); - } - - return new File(path.toString()); - } - - /** - * Sets up a test of the reporting mojo simulating multiple runs of mvn - * install (as in the case where timestampedReports is set to true). First - * calls {@link #prepareSiteTest(String)} then walks all directories starting - * at target/pit-reports setting their last modified time to 0 (epoch time). - * Finally, the directory specified in the {@code latestDir} parameter has its - * last modified time set to {@link System#currentTimeMillis()}. - * - * @param testPath - * {@link String} see {@link #prepareSiteTest(String)} - * @param latestDir - * {@link String} containing the subdirectory of target/pit-reports - * that should be set as the latest, pass an empty string to indicate - * the target/pit-reports directory should be the latest - * - * @return {@link File} representing the temporary folder that was set up for - * this execution of the test - * @throws Exception - */ - private File prepareSiteTest(String testPath, String latestDir) - throws Exception { - File testDir = prepareSiteTest(testPath); - // location where the target directory would be if a mvn clean install was executed - File testTargetDir = this.buildFilePath(testDir, "target", "pit-reports"); - DirectoriesOnlyWalker walker = new DirectoriesOnlyWalker(); - - for (File f : walker.locateDirectories(testTargetDir)) { - f.setLastModified(0L); - } - - assertThat( - buildFilePath(testTargetDir, latestDir).setLastModified( - System.currentTimeMillis())).isTrue(); - - return testDir; - } - - /** - * Sets up a test of the reporting mojo by simulating what a mvn clean install - * would do. After this function is executed, the maven site can be generated - * by executing the site goal. - * - * The provided {@code testPath} must have this folder structure set up - * underneath it: src/test/resources/pit-reports The contents of this - * directory will be moved to the target directory simulating a mvn clean - * install. - * - * @param testPath - * {@link String} location of the test to set up, this path is - * relative to ${basedir}/src/test/resources - * - * @return {@link File} representing the temporary folder that was set up for - * this execution of the test - * @throws Exception - */ - private File prepareSiteTest(String testPath) throws Exception { - File tempTestExecutionDir = prepare(testPath); - File targetDir = this.buildFilePath(tempTestExecutionDir, "target", - "pit-reports"); - - FileUtils.copyDirectory( - buildFilePath(tempTestExecutionDir, "src", "test", "resources", - "pit-reports"), targetDir); - - return tempTestExecutionDir; - } - - private void verifyPitReportTest(File testDir) throws Exception { - File pitReportSiteDir = buildFilePath(testDir, "target", "site", - "pit-reports"); - - assertThat(pitReportSiteDir).exists(); - assertThat(this.buildFilePath(pitReportSiteDir, "marker_expected.txt")) - .exists(); - - String projectReportsHtmlContents = FileUtils - .readFileToString(buildFilePath(testDir, "target", "site", - "project-reports.html")); - assertTrue( - "did not find expected anchor tag to pit site report", - projectReportsHtmlContents - .contains("PIT Test Report")); - } - -} +/* + * Copyright 2011 Henry Coles and Stefan Penndorf + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.pitest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeFalse; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.io.FileUtils; +import org.apache.maven.it.VerificationException; +import org.apache.maven.it.Verifier; +import org.apache.maven.it.util.ResourceExtractor; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.rules.TestName; +import org.pitest.support.DirectoriesOnlyWalker; +import org.pitest.testapi.execute.Pitest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Stefan Penndorf + */ +public class PitMojoIT { + private static Logger LOGGER = LoggerFactory.getLogger(PitMojoIT.class); + private static String VERSION = getVersion(); + + @Rule + public TestName testName = new TestName(); + + @Rule + public TemporaryFolder testFolder = new TemporaryFolder(); + + private Verifier verifier; + private long startTime; + + @Before + public void beforeEachTest() { + LOGGER.info("running test '{}'", testName.getMethodName()); + startTime = System.currentTimeMillis(); + } + + @After + public void afterEachTest() { + LOGGER.info("duration of test '{}' {}ms", testName.getMethodName(), + System.currentTimeMillis() - startTime); + } + + @Test + public void shouldSetUserDirToArtefactWorkingDirectory() throws Exception { + prepare("/pit-33-setUserDir"); + + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + } + + @Test(timeout=60000) + public void shouldNotHangWhenLargeAmountsOfConsoleOutput() throws Exception { + File testDir = prepare("/pit-process-hang"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + // checkout output looks sane, but main point is that test completed + assertThat(readResults(testDir)) + .contains( + "SomeCode.java"); + } + + @Test + public void shouldProduceConsistantCoverageData() throws Exception { + File testDir = prepare("/pit-deterministic-coverage"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String firstRun = readCoverage(testDir); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String secondRun = readCoverage(testDir); + assertEquals(firstRun, secondRun); + } + + @Test + public void shouldWorkWithTestNG() throws Exception { + File testDir = prepare("/pit-testng"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String actual = readResults(testDir); + assertThat(actual) + .contains( + "Covered.java"); + assertThat(actual) + .contains( + "Covered.java"); + assertThat(actual).doesNotContain("status='RUN_ERROR'"); + } + + @Test + public void shouldWorkWithTestNGAndJMockit() throws Exception { + File testDir = prepare("/pit-testng-jmockit"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String actual = readResults(testDir); + assertThat(actual) + .contains( + "Covered.java"); + assertThat(actual) + .contains( + "Covered.java"); + assertThat(actual).doesNotContain("status='RUN_ERROR'"); + } + + @Test + public void shouldExcludeSpecifiedJUnitCategories() throws Exception { + File testDir = prepare("/pit-junit-categories"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String actual = readResults(testDir); + String coverage = readCoverage(testDir); + assertThat(coverage).doesNotContain("NotCovered"); + assertThat(coverage).contains("Covered"); + assertThat(actual) + .contains( + "NotCovered.java"); + assertThat(actual) + .doesNotContain( + "NotCovered.java"); + assertThat(actual) + .contains( + "Covered.java"); + } + + @Test + //@Ignore("test is flakey, possibly due to real non deterministic issue with powermock") + public void shouldWorkWithPowerMock() throws Exception { + skipOnJava9(); + File testDir = prepare("/pit-powermock"); + verifier.addCliOption("-DtimeoutConstant=10000"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String actual = readResults(testDir); + assertThat(actual) + .contains( + "PowerMockAgentCallFoo.java"); + assertThat(actual) + .contains( + "PowerMockCallsOwnMethod.java"); + assertThat(actual) + .contains( + "PowerMockCallFoo.java"); + assertThat(actual).doesNotContain("status='RUN_ERROR'"); + assertThat(actual).doesNotContain("PowerMockCallsOwnMethod.javacom.example.PowerMockCallsOwnMethodbranchedCode"); + } + + @Test + public void shouldCorrectlyTargetTestsWhenMultipleBlocksIncludeALine() + throws Exception { + File testDir = prepare("/pit-158-coverage"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String actual = readResults(testDir); + assertThat(actual) + .contains( + "MyRequest.java"); + } + + /* + * Verifies that configuring report generation to be skipped does actually + * prevent the site report from being generated. + */ + @Test + public void shouldSkipSiteReportGeneration() throws Exception { + File testDir = prepareSiteTest("/pit-site-skip"); + File siteParentDir = buildFilePath(testDir, "target", "site"); + + verifier.executeGoal("site"); + + assertThat(siteParentDir).exists(); + assertThat(buildFilePath(siteParentDir, "pit-reports")).doesNotExist(); + assertThat(buildFilePath(siteParentDir, "index.html")).exists(); + assertThat(buildFilePath(siteParentDir, "project-reports.html")) + .doesNotExist(); + } + + /* + * Verifies that running PIT with timestampedReports set to false will + * correctly copy the HTML report to the site reports directory. + */ + @Test + public void shouldGenerateSiteReportWithNonTimestampedHtmlReport() + throws Exception { + File testDir = prepareSiteTest("/pit-site-non-timestamped"); + + verifier.executeGoal("site"); + verifyPitReportTest(testDir); + } + + /* + * Verifies that running PIT with timestampedReports set to true will copy the + * contents of the latest timestamped report + */ + @Test + public void shouldGenerateSiteReportWithSingleTimestampedHtmlReport() + throws Exception { + File testDir = prepareSiteTest("/pit-site-timestamped", "201505212116"); + + verifier.executeGoal("site"); + verifyPitReportTest(testDir); + } + + /* + * Verifies that, when multiple timestamped PIT reports have been generated, + * only the latest report is copied to the site reports directory. This test + * sets the earlier directory (201503292032) as the last modified. This tests + * to make sure the last modified date is used instead of just using the + * folder name. + */ + @Test + public void shouldCopyLatestTimestampedReportWhenMultipleTimestampedReportsExist() + throws Exception { + File testDir = prepareSiteTest("/pit-site-multiple-timestamped", + "201503292032"); + + verifier.executeGoal("site"); + verifyPitReportTest(testDir); + } + + /* + * Verifies that in the case where pit has generated reports with both + * timestampedReports=true and timestampedReports=false, the latest report run + * is copied and no timestamped report subdirectories are copied + */ + @Test + public void shouldCopyLatestTimestampedOrNonTimestampedReportWhenBothExist() + throws Exception { + File testDir = prepareSiteTest("/pit-site-combined", ""); + + verifier.executeGoal("site"); + verifyPitReportTest(testDir); + } + + /* + * Verifies that the build fails when running the report goal without first + * running the mutationCoverage goal + */ + @Test + public void shouldFailIfNoPITReportAvailable() throws Exception { + prepare("/pit-site-reportonly"); + + try { + verifier.executeGoal("site"); + fail("should fail"); + } catch (VerificationException e) { + assertThat(e.getMessage()) + .containsSequence( + "could not find reports directory"); + } + } + + /* + * verifies that overriding defaults has the expected results + */ + @Test + public void shouldCorrectlyHandleOverrides() throws Exception { + File testDir = prepareSiteTest("/pit-site-custom-config"); + File targetDir = buildFilePath(testDir, "target"); + File expectedSiteReportDir = buildFilePath(testDir, "target", "site", + "foobar"); + + FileUtils.moveDirectory(buildFilePath(targetDir, "pit-reports"), + buildFilePath(targetDir, "new-report-location")); + + verifier.executeGoal("site"); + + String projectReportsHtmlContents = FileUtils + .readFileToString(buildFilePath(testDir, "target", "site", + "project-reports.html")); + assertTrue( + "did not find expected anchor tag to pit site report", + projectReportsHtmlContents + .contains("my-test-pit-report-name")); + assertTrue("expected site report directory [" + expectedSiteReportDir + + "] does not exist but should exist", expectedSiteReportDir.exists()); + + assertFalse( + "expected default site report directory exists but should not exist since the report location parameter was overridden", + buildFilePath(testDir, "target", "site", "pit-reports").exists()); + } + + @Test + public void shouldReadExclusionsFromSurefireConfig() throws Exception { + File testDir = prepare("/pit-surefire-excludes"); + verifier.addCliOption("-DskipTests"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String actual = readResults(testDir); + assertThat(actual) + .contains( + "NotCovered.java"); + } + + @Test + public void shouldWorkWithGWTMockito() throws Exception { + skipOnJava9(); + File testDir = prepare("/pit-183-gwtmockito"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String actual = readResults(testDir); + assertThat(actual) + .contains( + "MyWidget.java"); + assertThat(actual) + .contains( + "MyWidget.java"); + assertThat(actual).doesNotContain("status='RUN_ERROR'"); + } + + private void skipOnJava9() { + assumeFalse(System.getProperty("java.version").startsWith("9")); + } + + @Test + public void shouldWorkWithYatspec() throws Exception { + File testDir = prepare("/pit-263-yatspec"); + verifier.executeGoal("test"); + verifier.executeGoal("org.pitest:pitest-maven:mutationCoverage"); + + String actual = readResults(testDir); + assertThat(actual) + .contains( + "SomeClass.java"); + assertThat(actual).doesNotContain("status='NO_COVERAGE'"); + assertThat(actual).doesNotContain("status='RUN_ERROR'"); + } + + private static String readResults(File testDir) throws IOException { + File mutationReport = new File(testDir.getAbsoluteFile() + File.separator + + "target" + File.separator + "pit-reports" + File.separator + + "mutations.xml"); + return FileUtils.readFileToString(mutationReport); + } + + private static String readCoverage(File testDir) throws IOException { + File coverage = new File(testDir.getAbsoluteFile() + File.separator + + "target" + File.separator + "pit-reports" + File.separator + + "linecoverage.xml"); + return FileUtils.readFileToString(coverage); + } + + private File prepare(String testPath) throws IOException, + VerificationException { + String path = ResourceExtractor.extractResourcePath(getClass(), testPath, + testFolder.getRoot(), true).getAbsolutePath(); + + verifier = new Verifier(path); + verifier.setAutoclean(false); + verifier.setDebug(true); + verifier.getCliOptions().add("-Dpit.version=" + VERSION); + verifier.getCliOptions().add( + "-Dthreads=" + (Runtime.getRuntime().availableProcessors())); + + return new File(testFolder.getRoot().getAbsolutePath() + testPath); + } + + private static String getVersion() { + String path = "/version.prop"; + InputStream stream = Pitest.class.getResourceAsStream(path); + Properties props = new Properties(); + try { + props.load(stream); + stream.close(); + return (String) props.get("version"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Creates a new {@link File} object building off an existing {@link File} + * object and appending subfolders. + * + * For example, if this function is called with these arguments: + * buildFile(new File("/foo/bar"), "subdir1", "subdir2", "file1.txt"); + * The returned {@link File} object would represent the path: + * /foo/bar/subdir1/subdir/file1.txt + * + * @param base + * {@link File} representing the starting location + * @param pathParts + * {@link String} varags containing the subfolders to append to the + * base, this argument should contain at least one value and none of + * its values should be blank or null. + * + * @return {@link File} + */ + private File buildFilePath(File base, String... pathParts) { + StringBuilder path = new StringBuilder(base.getAbsolutePath()); + + for (String part : pathParts) { + path.append(File.separator).append(part); + } + + return new File(path.toString()); + } + + /** + * Sets up a test of the reporting mojo simulating multiple runs of mvn + * install (as in the case where timestampedReports is set to true). First + * calls {@link #prepareSiteTest(String)} then walks all directories starting + * at target/pit-reports setting their last modified time to 0 (epoch time). + * Finally, the directory specified in the {@code latestDir} parameter has its + * last modified time set to {@link System#currentTimeMillis()}. + * + * @param testPath + * {@link String} see {@link #prepareSiteTest(String)} + * @param latestDir + * {@link String} containing the subdirectory of target/pit-reports + * that should be set as the latest, pass an empty string to indicate + * the target/pit-reports directory should be the latest + * + * @return {@link File} representing the temporary folder that was set up for + * this execution of the test + * @throws Exception + */ + private File prepareSiteTest(String testPath, String latestDir) + throws Exception { + File testDir = prepareSiteTest(testPath); + // location where the target directory would be if a mvn clean install was executed + File testTargetDir = this.buildFilePath(testDir, "target", "pit-reports"); + DirectoriesOnlyWalker walker = new DirectoriesOnlyWalker(); + + for (File f : walker.locateDirectories(testTargetDir)) { + f.setLastModified(0L); + } + + assertThat( + buildFilePath(testTargetDir, latestDir).setLastModified( + System.currentTimeMillis())).isTrue(); + + return testDir; + } + + /** + * Sets up a test of the reporting mojo by simulating what a mvn clean install + * would do. After this function is executed, the maven site can be generated + * by executing the site goal. + * + * The provided {@code testPath} must have this folder structure set up + * underneath it: src/test/resources/pit-reports The contents of this + * directory will be moved to the target directory simulating a mvn clean + * install. + * + * @param testPath + * {@link String} location of the test to set up, this path is + * relative to ${basedir}/src/test/resources + * + * @return {@link File} representing the temporary folder that was set up for + * this execution of the test + * @throws Exception + */ + private File prepareSiteTest(String testPath) throws Exception { + File tempTestExecutionDir = prepare(testPath); + File targetDir = this.buildFilePath(tempTestExecutionDir, "target", + "pit-reports"); + + FileUtils.copyDirectory( + buildFilePath(tempTestExecutionDir, "src", "test", "resources", + "pit-reports"), targetDir); + + return tempTestExecutionDir; + } + + private void verifyPitReportTest(File testDir) throws Exception { + File pitReportSiteDir = buildFilePath(testDir, "target", "site", + "pit-reports"); + + assertThat(pitReportSiteDir).exists(); + assertThat(this.buildFilePath(pitReportSiteDir, "marker_expected.txt")) + .exists(); + + String projectReportsHtmlContents = FileUtils + .readFileToString(buildFilePath(testDir, "target", "site", + "project-reports.html")); + assertTrue( + "did not find expected anchor tag to pit site report", + projectReportsHtmlContents + .contains("PIT Test Report")); + } + +} diff --git a/pitest-maven-verification/src/test/java/org/pitest/support/DirectoriesOnlyWalker.java b/pitest-maven-verification/src/test/java/org/pitest/support/DirectoriesOnlyWalker.java index 14162f562..83e6eb98b 100644 --- a/pitest-maven-verification/src/test/java/org/pitest/support/DirectoriesOnlyWalker.java +++ b/pitest-maven-verification/src/test/java/org/pitest/support/DirectoriesOnlyWalker.java @@ -1,60 +1,60 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.support; - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import org.apache.commons.io.DirectoryWalker; -import org.apache.commons.io.filefilter.FileFilterUtils; - -/** - * Builds a list of all directories contained within a provided directory. The starting directory is also contained - * within the list of directories.

- * - * - * DirectoriesOnlyWalker walker = new DirectoriesOnlyWalker();
- * List directories = walker.locateDirectories(someDirectory); - *
- */ -public class DirectoriesOnlyWalker extends DirectoryWalker { - - public DirectoriesOnlyWalker() { - super(FileFilterUtils.directoryFileFilter(), -1); - } - - public List locateDirectories(File startDir) { - List foundDirs = new LinkedList<>(); - - try { - this.walk(startDir, foundDirs); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return foundDirs; - } - - @Override - protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException { - results.add(directory); - - return super.handleDirectory(directory, depth, results); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.support; + +import java.io.File; +import java.io.IOException; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import org.apache.commons.io.DirectoryWalker; +import org.apache.commons.io.filefilter.FileFilterUtils; + +/** + * Builds a list of all directories contained within a provided directory. The starting directory is also contained + * within the list of directories.

+ * + * + * DirectoriesOnlyWalker walker = new DirectoriesOnlyWalker();
+ * List directories = walker.locateDirectories(someDirectory); + *
+ */ +public class DirectoriesOnlyWalker extends DirectoryWalker { + + public DirectoriesOnlyWalker() { + super(FileFilterUtils.directoryFileFilter(), -1); + } + + public List locateDirectories(File startDir) { + List foundDirs = new LinkedList<>(); + + try { + this.walk(startDir, foundDirs); + } catch (IOException e) { + throw new RuntimeException(e); + } + + return foundDirs; + } + + @Override + protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException { + results.add(directory); + + return super.handleDirectory(directory, depth, results); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-158-coverage/pom.xml b/pitest-maven-verification/src/test/resources/pit-158-coverage/pom.xml index d8e16a30c..e28a0d9c9 100644 --- a/pitest-maven-verification/src/test/resources/pit-158-coverage/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-158-coverage/pom.xml @@ -1,57 +1,57 @@ - - - 4.0.0 - com.example - pitest-sample - 0.1-SNAPSHOT - pit #158 coverage issue - - - UTF-8 - - - - - com.google.guava - guava - 18.0 - - - - junit - junit - 4.8.2 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - true - XML - false - true - - VOID_METHOD_CALLS - - - - - - - + + + 4.0.0 + com.example + pitest-sample + 0.1-SNAPSHOT + pit #158 coverage issue + + + UTF-8 + + + + + com.google.guava + guava + 18.0 + + + + junit + junit + 4.8.2 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + true + XML + false + true + + VOID_METHOD_CALLS + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-158-coverage/src/main/java/com/example/MyRequest.java b/pitest-maven-verification/src/test/resources/pit-158-coverage/src/main/java/com/example/MyRequest.java index 44c531b97..d1420d523 100644 --- a/pitest-maven-verification/src/test/resources/pit-158-coverage/src/main/java/com/example/MyRequest.java +++ b/pitest-maven-verification/src/test/resources/pit-158-coverage/src/main/java/com/example/MyRequest.java @@ -1,23 +1,23 @@ -package com.example; - -import java.io.Serializable; -import com.google.common.base.Preconditions; - -public class MyRequest implements Serializable { - - private static final long serialVersionUID = -3548858114709541512L; - private Long userId; - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - public void validate() throws IllegalStateException { - Preconditions.checkState(userId != null); - } - +package com.example; + +import java.io.Serializable; +import com.google.common.base.Preconditions; + +public class MyRequest implements Serializable { + + private static final long serialVersionUID = -3548858114709541512L; + private Long userId; + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public void validate() throws IllegalStateException { + Preconditions.checkState(userId != null); + } + } \ No newline at end of file diff --git a/pitest-maven-verification/src/test/resources/pit-158-coverage/src/test/java/com/example/MyRequestTest.java b/pitest-maven-verification/src/test/resources/pit-158-coverage/src/test/java/com/example/MyRequestTest.java index 4147bb90e..3158eafe2 100644 --- a/pitest-maven-verification/src/test/resources/pit-158-coverage/src/test/java/com/example/MyRequestTest.java +++ b/pitest-maven-verification/src/test/resources/pit-158-coverage/src/test/java/com/example/MyRequestTest.java @@ -1,32 +1,32 @@ -package com.example; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.example.MyRequest; - -public class MyRequestTest { - - @Test - public void testValidateEmpty() { - try { - MyRequest req = new MyRequest(); - req.validate(); - fail(); - } catch(IllegalStateException ex) { - // pass - } - } - - @Test - public void testValidateOk() { - final Long userId = 99L; - MyRequest req = new MyRequest(); - req.setUserId(userId); - req.validate(); - - assertEquals(userId, req.getUserId()); - } +package com.example; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import com.example.MyRequest; + +public class MyRequestTest { + + @Test + public void testValidateEmpty() { + try { + MyRequest req = new MyRequest(); + req.validate(); + fail(); + } catch(IllegalStateException ex) { + // pass + } + } + + @Test + public void testValidateOk() { + final Long userId = 99L; + MyRequest req = new MyRequest(); + req.setUserId(userId); + req.validate(); + + assertEquals(userId, req.getUserId()); + } } \ No newline at end of file diff --git a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/pom.xml b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/pom.xml index a864c13c4..302e2b437 100644 --- a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/pom.xml @@ -1,63 +1,63 @@ - - 4.0.0 - - com.google.gwt.gwtmockito - gwtmockito-parent - 1.1.5 - - - sample - gwtmockito-sample - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - true - XML - 6 - false - sample* - true - - - - - - - - - com.google.gwt - gwt-user - - - - junit - junit - test - - - org.mockito - mockito-all - test - - - com.google.gwt.gwtmockito - gwtmockito - test - - - - + + 4.0.0 + + com.google.gwt.gwtmockito + gwtmockito-parent + 1.1.5 + + + sample + gwtmockito-sample + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + true + XML + 6 + false + sample* + true + + + + + + + + + com.google.gwt + gwt-user + + + + junit + junit + test + + + org.mockito + mockito-all + test + + + com.google.gwt.gwtmockito + gwtmockito + test + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyService.java b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyService.java index 4ec775469..8341a1e1e 100644 --- a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyService.java +++ b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyService.java @@ -1,7 +1,7 @@ -package sample; - -import com.google.gwt.user.client.rpc.RemoteService; - -public interface MyService extends RemoteService { - String getData(); -} +package sample; + +import com.google.gwt.user.client.rpc.RemoteService; + +public interface MyService extends RemoteService { + String getData(); +} diff --git a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyServiceAsync.java b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyServiceAsync.java index ad2f59a5b..86f4c7e1e 100644 --- a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyServiceAsync.java +++ b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyServiceAsync.java @@ -1,7 +1,7 @@ -package sample; - -import com.google.gwt.user.client.rpc.AsyncCallback; - -public interface MyServiceAsync { - void getData(AsyncCallback callback); -} +package sample; + +import com.google.gwt.user.client.rpc.AsyncCallback; + +public interface MyServiceAsync { + void getData(AsyncCallback callback); +} diff --git a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyWidget.java b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyWidget.java index 147263251..a43076010 100644 --- a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyWidget.java +++ b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/main/java/sample/MyWidget.java @@ -1,79 +1,79 @@ -/* - * Copyright 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package sample; - -import com.google.gwt.core.shared.GWT; -import com.google.gwt.uibinder.client.UiBinder; -import com.google.gwt.uibinder.client.UiField; -import com.google.gwt.user.client.Element; -import com.google.gwt.user.client.rpc.AsyncCallback; -import com.google.gwt.user.client.ui.Composite; -import com.google.gwt.user.client.ui.HasText; -import com.google.gwt.user.client.ui.Widget; - -/** - * A sample widget that would be hard to test without GwtMockito. - */ -public class MyWidget extends Composite { - - interface MyUiBinder extends UiBinder { - - } - private static final MyUiBinder UI_BINDER = GWT.create(MyUiBinder.class); - - public interface DataProvider { - String getData(); - } - - @UiField HasText name; - @UiField HasText data; - - private final DataProvider dataProvider; - - public MyWidget() { - dataProvider = GWT.create(DataProvider.class); - doStuffInJavaScript(); - initWidget(UI_BINDER.createAndBindUi(this)); - } - - public void setName(String firstName, String lastName) { - name.setText(firstName + " " + lastName); - } - - public void updateData() { - data.setText(dataProvider.getData()); - } - - public void loadDataFromRpc() { - MyServiceAsync service = GWT.create(MyService.class); - service.getData(new AsyncCallback() { - @Override - public void onSuccess(String result) { - data.setText(result); - } - - @Override - public void onFailure(Throwable caught) { - - } - }); - } - - native Element doStuffInJavaScript() /*-{ - $wnd.console.log("some message"); - return $doc; - }-*/; -} +/* + * Copyright 2013 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package sample; + +import com.google.gwt.core.shared.GWT; +import com.google.gwt.uibinder.client.UiBinder; +import com.google.gwt.uibinder.client.UiField; +import com.google.gwt.user.client.Element; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.gwt.user.client.ui.Composite; +import com.google.gwt.user.client.ui.HasText; +import com.google.gwt.user.client.ui.Widget; + +/** + * A sample widget that would be hard to test without GwtMockito. + */ +public class MyWidget extends Composite { + + interface MyUiBinder extends UiBinder { + + } + private static final MyUiBinder UI_BINDER = GWT.create(MyUiBinder.class); + + public interface DataProvider { + String getData(); + } + + @UiField HasText name; + @UiField HasText data; + + private final DataProvider dataProvider; + + public MyWidget() { + dataProvider = GWT.create(DataProvider.class); + doStuffInJavaScript(); + initWidget(UI_BINDER.createAndBindUi(this)); + } + + public void setName(String firstName, String lastName) { + name.setText(firstName + " " + lastName); + } + + public void updateData() { + data.setText(dataProvider.getData()); + } + + public void loadDataFromRpc() { + MyServiceAsync service = GWT.create(MyService.class); + service.getData(new AsyncCallback() { + @Override + public void onSuccess(String result) { + data.setText(result); + } + + @Override + public void onFailure(Throwable caught) { + + } + }); + } + + native Element doStuffInJavaScript() /*-{ + $wnd.console.log("some message"); + return $doc; + }-*/; +} diff --git a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/test/java/sample/MyWidgetTest.java b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/test/java/sample/MyWidgetTest.java index ae7f9ac39..cebff7820 100644 --- a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/test/java/sample/MyWidgetTest.java +++ b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/test/java/sample/MyWidgetTest.java @@ -1,109 +1,109 @@ -/* - * Copyright 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package sample; - -import static com.google.gwtmockito.AsyncAnswers.returnSuccess; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.gwt.user.client.rpc.AsyncCallback; -import com.google.gwt.user.client.ui.HasText; -import com.google.gwtmockito.GwtMock; -import com.google.gwtmockito.GwtMockito; -import com.google.gwtmockito.GwtMockitoTestRunner; -import com.google.gwtmockito.fakes.FakeProvider; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import sample.MyWidget.DataProvider; - -/** - * Test for {@link MyWidget} using {@link GwtMockitoTestRunner}. - */ -@RunWith(GwtMockitoTestRunner.class) -public class MyWidgetTest { - - @GwtMock private DataProvider dataProvider; - @GwtMock private MyServiceAsync myService; - - private MyWidget widget; - - @Before - public void setUp() { - widget = new MyWidget(); - } - - @Test - public void testSetName() { - widget.setName("John", "Smith"); - - // Since name is a @UiField, it will be automatically filled with a mock - // that we can verify here. - verify(widget.name).setText("John Smith"); - } - - @Test - public void testUpdateData() { - // Since dataProvider is declared as a @GwtMock, any calls to - // GWT.create(dataProvider.class) will return dataProvider. - when(dataProvider.getData()).thenReturn("data"); - - widget.updateData(); - - verify(widget.data).setText("data"); - } - - @Test - public void testSetNameWithFakes() { - // If we don't want to use mocks, we can instead provide fake - // implementations to be created. Normally you would do this in setUp. - GwtMockito.useProviderForType(HasText.class, new FakeProvider() { - @Override - public HasText getFake(Class type) { - return new HasText() { - private String text; - - @Override - public void setText(String text) { - this.text = text; - } - - @Override - public String getText() { - return text; - } - }; - } - }); - widget = new MyWidget(); - - widget.setName("John", "Smith"); - assertEquals("John Smith", widget.name.getText()); - } - - @Test - @SuppressWarnings("unchecked") - public void testMockRpcs() { - doAnswer(returnSuccess("some data")).when(myService).getData(any(AsyncCallback.class)); - widget.loadDataFromRpc(); - verify(widget.data).setText("some data"); - } -} +/* + * Copyright 2013 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package sample; + +import static com.google.gwtmockito.AsyncAnswers.returnSuccess; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.gwt.user.client.ui.HasText; +import com.google.gwtmockito.GwtMock; +import com.google.gwtmockito.GwtMockito; +import com.google.gwtmockito.GwtMockitoTestRunner; +import com.google.gwtmockito.fakes.FakeProvider; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import sample.MyWidget.DataProvider; + +/** + * Test for {@link MyWidget} using {@link GwtMockitoTestRunner}. + */ +@RunWith(GwtMockitoTestRunner.class) +public class MyWidgetTest { + + @GwtMock private DataProvider dataProvider; + @GwtMock private MyServiceAsync myService; + + private MyWidget widget; + + @Before + public void setUp() { + widget = new MyWidget(); + } + + @Test + public void testSetName() { + widget.setName("John", "Smith"); + + // Since name is a @UiField, it will be automatically filled with a mock + // that we can verify here. + verify(widget.name).setText("John Smith"); + } + + @Test + public void testUpdateData() { + // Since dataProvider is declared as a @GwtMock, any calls to + // GWT.create(dataProvider.class) will return dataProvider. + when(dataProvider.getData()).thenReturn("data"); + + widget.updateData(); + + verify(widget.data).setText("data"); + } + + @Test + public void testSetNameWithFakes() { + // If we don't want to use mocks, we can instead provide fake + // implementations to be created. Normally you would do this in setUp. + GwtMockito.useProviderForType(HasText.class, new FakeProvider() { + @Override + public HasText getFake(Class type) { + return new HasText() { + private String text; + + @Override + public void setText(String text) { + this.text = text; + } + + @Override + public String getText() { + return text; + } + }; + } + }); + widget = new MyWidget(); + + widget.setName("John", "Smith"); + assertEquals("John Smith", widget.name.getText()); + } + + @Test + @SuppressWarnings("unchecked") + public void testMockRpcs() { + doAnswer(returnSuccess("some data")).when(myService).getData(any(AsyncCallback.class)); + widget.loadDataFromRpc(); + verify(widget.data).setText("some data"); + } +} diff --git a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/test/java/sample/MyWidgetTestWithoutRunner.java b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/test/java/sample/MyWidgetTestWithoutRunner.java index c16a9cb4d..613a1c6c4 100644 --- a/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/test/java/sample/MyWidgetTestWithoutRunner.java +++ b/pitest-maven-verification/src/test/resources/pit-183-gwtmockito/src/test/java/sample/MyWidgetTestWithoutRunner.java @@ -1,113 +1,113 @@ -/* - * Copyright 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package sample; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.gwt.user.client.Element; -import com.google.gwt.user.client.ui.HasText; -import com.google.gwt.user.client.ui.Widget; -import com.google.gwtmockito.GwtMock; -import com.google.gwtmockito.GwtMockito; -import com.google.gwtmockito.GwtMockitoTestRunner; -import com.google.gwtmockito.fakes.FakeProvider; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import sample.MyWidget.DataProvider; - -/** - * Test for {@link MyWidget} that doesn't use {@link GwtMockitoTestRunner}. Most - * things will still work, though it gets a bit more verbose. Most tests should - * look like {@link MyWidgetTest} instead. - */ -@RunWith(JUnit4.class) -public class MyWidgetTestWithoutRunner { - - @GwtMock private DataProvider dataProvider; - - private MyWidget widget; - - @Before - public void setUp() { - GwtMockito.initMocks(this); - widget = new MyWidget() { - @Override - protected void initWidget(Widget widget) { - // initWidget must be disarmed when testing widget to avoid - // UnsatisfiedLinkErrors - } - - @Override - Element doStuffInJavaScript() { - // JSNI methods must be explicitly overridden or factored out to avoid - // UnsatisfiedLinkErrors - return null; - } - }; - } - - /* - * The remaining test cases look the same as they do in MyWidgetTest. - */ - - @Test - public void testSetName() { - widget.setName("John", "Smith"); - verify(widget.name).setText("John Smith"); - } - - @Test - public void testUpdateData() { - when(dataProvider.getData()).thenReturn("data"); - widget.updateData(); - verify(widget.data).setText("data"); - } - - @Test - public void testSetNameWithFakes() { - GwtMockito.useProviderForType(HasText.class, new FakeProvider() { - @Override - public HasText getFake(Class type) { - return new HasText() { - private String text; - - @Override - public void setText(String text) { - this.text = text; - } - - @Override - public String getText() { - return text; - } - }; - } - }); - widget = new MyWidget() { - @Override protected void initWidget(Widget widget) {} - @Override Element doStuffInJavaScript() { return null; } - }; - - widget.setName("John", "Smith"); - assertEquals("John Smith", widget.name.getText()); - } -} +/* + * Copyright 2013 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package sample; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gwt.user.client.Element; +import com.google.gwt.user.client.ui.HasText; +import com.google.gwt.user.client.ui.Widget; +import com.google.gwtmockito.GwtMock; +import com.google.gwtmockito.GwtMockito; +import com.google.gwtmockito.GwtMockitoTestRunner; +import com.google.gwtmockito.fakes.FakeProvider; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import sample.MyWidget.DataProvider; + +/** + * Test for {@link MyWidget} that doesn't use {@link GwtMockitoTestRunner}. Most + * things will still work, though it gets a bit more verbose. Most tests should + * look like {@link MyWidgetTest} instead. + */ +@RunWith(JUnit4.class) +public class MyWidgetTestWithoutRunner { + + @GwtMock private DataProvider dataProvider; + + private MyWidget widget; + + @Before + public void setUp() { + GwtMockito.initMocks(this); + widget = new MyWidget() { + @Override + protected void initWidget(Widget widget) { + // initWidget must be disarmed when testing widget to avoid + // UnsatisfiedLinkErrors + } + + @Override + Element doStuffInJavaScript() { + // JSNI methods must be explicitly overridden or factored out to avoid + // UnsatisfiedLinkErrors + return null; + } + }; + } + + /* + * The remaining test cases look the same as they do in MyWidgetTest. + */ + + @Test + public void testSetName() { + widget.setName("John", "Smith"); + verify(widget.name).setText("John Smith"); + } + + @Test + public void testUpdateData() { + when(dataProvider.getData()).thenReturn("data"); + widget.updateData(); + verify(widget.data).setText("data"); + } + + @Test + public void testSetNameWithFakes() { + GwtMockito.useProviderForType(HasText.class, new FakeProvider() { + @Override + public HasText getFake(Class type) { + return new HasText() { + private String text; + + @Override + public void setText(String text) { + this.text = text; + } + + @Override + public String getText() { + return text; + } + }; + } + }); + widget = new MyWidget() { + @Override protected void initWidget(Widget widget) {} + @Override Element doStuffInJavaScript() { return null; } + }; + + widget.setName("John", "Smith"); + assertEquals("John Smith", widget.name.getText()); + } +} diff --git a/pitest-maven-verification/src/test/resources/pit-263-yatspec/pom.xml b/pitest-maven-verification/src/test/resources/pit-263-yatspec/pom.xml index 305b1597c..e9c5429f4 100644 --- a/pitest-maven-verification/src/test/resources/pit-263-yatspec/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-263-yatspec/pom.xml @@ -1,60 +1,60 @@ - - 4.0.0 - - - sample - pit-yatspec - DEV-SNAPSHOT - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - true - - XML - - false - - sample* - - true - - - - - - - - repo.bodar.com - http://repo.bodar.com - - - - - - junit - junit - 4.12 - test - - - com.googlecode.yatspec - yatspec - 1.23 - test - - - + + 4.0.0 + + + sample + pit-yatspec + DEV-SNAPSHOT + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + true + + XML + + false + + sample* + + true + + + + + + + + repo.bodar.com + http://repo.bodar.com + + + + + + junit + junit + 4.12 + test + + + com.googlecode.yatspec + yatspec + 1.23 + test + + + diff --git a/pitest-maven-verification/src/test/resources/pit-263-yatspec/src/main/java/sample/SomeClass.java b/pitest-maven-verification/src/test/resources/pit-263-yatspec/src/main/java/sample/SomeClass.java index a395cbd8b..9ad0048b7 100644 --- a/pitest-maven-verification/src/test/resources/pit-263-yatspec/src/main/java/sample/SomeClass.java +++ b/pitest-maven-verification/src/test/resources/pit-263-yatspec/src/main/java/sample/SomeClass.java @@ -1,12 +1,12 @@ -package sample; - -public class SomeClass { - - public int theAnswer(String question) { - if ("life the universe and everything".equals(question)) { - return 42; - } else { - return -1; - } - } -} +package sample; + +public class SomeClass { + + public int theAnswer(String question) { + if ("life the universe and everything".equals(question)) { + return 42; + } else { + return -1; + } + } +} diff --git a/pitest-maven-verification/src/test/resources/pit-263-yatspec/src/test/java/sample/SomeClassTest.java b/pitest-maven-verification/src/test/resources/pit-263-yatspec/src/test/java/sample/SomeClassTest.java index 52da6021f..7d466035c 100644 --- a/pitest-maven-verification/src/test/resources/pit-263-yatspec/src/test/java/sample/SomeClassTest.java +++ b/pitest-maven-verification/src/test/resources/pit-263-yatspec/src/test/java/sample/SomeClassTest.java @@ -1,22 +1,22 @@ -package sample; - -import com.googlecode.yatspec.junit.Row; -import com.googlecode.yatspec.junit.Table; -import com.googlecode.yatspec.junit.TableRunner; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.assertEquals; - -@RunWith(TableRunner.class) -public class SomeClassTest { - - @Table({ - @Row({"life the universe and everything", "42"}), - @Row({"everything else", "-1"}) - }) - @Test - public void testTheAnswer(String question, String answer) { - assertEquals(new SomeClass().theAnswer(question), Integer.parseInt(answer)); - } +package sample; + +import com.googlecode.yatspec.junit.Row; +import com.googlecode.yatspec.junit.Table; +import com.googlecode.yatspec.junit.TableRunner; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.assertEquals; + +@RunWith(TableRunner.class) +public class SomeClassTest { + + @Table({ + @Row({"life the universe and everything", "42"}), + @Row({"everything else", "-1"}) + }) + @Test + public void testTheAnswer(String question, String answer) { + assertEquals(new SomeClass().theAnswer(question), Integer.parseInt(answer)); + } } \ No newline at end of file diff --git a/pitest-maven-verification/src/test/resources/pit-33-setUserDir/pom.xml b/pitest-maven-verification/src/test/resources/pit-33-setUserDir/pom.xml index d41142d05..ce08f1758 100644 --- a/pitest-maven-verification/src/test/resources/pit-33-setUserDir/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-33-setUserDir/pom.xml @@ -1,47 +1,47 @@ - - 4.0.0 - org.example - 33-setUserDir - pom - 1.0-SNAPSHOT - pit #33 setUserDir - - - junit - junit - ${junit.version} - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - org.example* - false - true - - - - - - - - 4.8.1 - - - pit-33-setUserDir-subModule - + + 4.0.0 + org.example + 33-setUserDir + pom + 1.0-SNAPSHOT + pit #33 setUserDir + + + junit + junit + ${junit.version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + org.example* + false + true + + + + + + + + 4.8.1 + + + pit-33-setUserDir-subModule + \ No newline at end of file diff --git a/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/pom.xml b/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/pom.xml index 5bcc649d3..81a193e47 100644 --- a/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/pom.xml @@ -1,47 +1,47 @@ - - 4.0.0 - org.example - deterministic-coverage - jar - 1.0-SNAPSHOT - deterministic-coverage - - - junit - junit - ${junit.version} - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - true - 1 - false - com.example* - true - - - - - - - - 4.8.1 - - - + + 4.0.0 + org.example + deterministic-coverage + jar + 1.0-SNAPSHOT + deterministic-coverage + + + junit + junit + ${junit.version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + true + 1 + false + com.example* + true + + + + + + + + 4.8.1 + + + diff --git a/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/src/main/java/com/example/CoveredByMultipleThreads.java b/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/src/main/java/com/example/CoveredByMultipleThreads.java index a4c3e2913..11de3188f 100644 --- a/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/src/main/java/com/example/CoveredByMultipleThreads.java +++ b/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/src/main/java/com/example/CoveredByMultipleThreads.java @@ -1,25 +1,25 @@ -package com.example; - -public class CoveredByMultipleThreads { - - public int lotsOfLinesOfCode(int i) { - if ( i == 0 ) { - return 1; - } - - if ( i == 2 ) { - return 42; - } - - for ( int j = 0; j != 100; j++ ) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - return i; - } - -} +package com.example; + +public class CoveredByMultipleThreads { + + public int lotsOfLinesOfCode(int i) { + if ( i == 0 ) { + return 1; + } + + if ( i == 2 ) { + return 42; + } + + for ( int j = 0; j != 100; j++ ) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + return i; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/src/test/java/com/example/MultiThreadedTest.java b/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/src/test/java/com/example/MultiThreadedTest.java index 43b485aa6..5bc00a01c 100644 --- a/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/src/test/java/com/example/MultiThreadedTest.java +++ b/pitest-maven-verification/src/test/resources/pit-deterministic-coverage/src/test/java/com/example/MultiThreadedTest.java @@ -1,45 +1,45 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(value = Parameterized.class) -public class MultiThreadedTest { - - private final int i; - - @Parameters - public static Collection data() { - Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 }, { 5 } ,{ 6 }, { 7 }, { 8 } }; - return Arrays.asList(data); - } - - public MultiThreadedTest(int i) { - this.i = i; - } - - @Test - public void test() throws InterruptedException { - Thread t = new Thread(aTest()); - t.start(); - t.join(); - } - - - - private Runnable aTest() { - return new Runnable() { - public void run() { - CoveredByMultipleThreads testee = new CoveredByMultipleThreads(); - testee.lotsOfLinesOfCode(i); - } - - }; - }; - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(value = Parameterized.class) +public class MultiThreadedTest { + + private final int i; + + @Parameters + public static Collection data() { + Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 }, { 5 } ,{ 6 }, { 7 }, { 8 } }; + return Arrays.asList(data); + } + + public MultiThreadedTest(int i) { + this.i = i; + } + + @Test + public void test() throws InterruptedException { + Thread t = new Thread(aTest()); + t.start(); + t.join(); + } + + + + private Runnable aTest() { + return new Runnable() { + public void run() { + CoveredByMultipleThreads testee = new CoveredByMultipleThreads(); + testee.lotsOfLinesOfCode(i); + } + + }; + }; + +} diff --git a/pitest-maven-verification/src/test/resources/pit-junit-categories/pom.xml b/pitest-maven-verification/src/test/resources/pit-junit-categories/pom.xml index fba814adc..789f6a8e1 100644 --- a/pitest-maven-verification/src/test/resources/pit-junit-categories/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-junit-categories/pom.xml @@ -1,48 +1,48 @@ - - 4.0.0 - org.example - junit-categories-check - jar - 1.0-SNAPSHOT - junit-categories - - - junit - junit - 4.12 - test - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - - com.example.ExcludeMe - - true - XML - 6 - false - com.example.* - com.example* - true - - - - - - + + 4.0.0 + org.example + junit-categories-check + jar + 1.0-SNAPSHOT + junit-categories + + + junit + junit + 4.12 + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + + com.example.ExcludeMe + + true + XML + 6 + false + com.example.* + com.example* + true + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/main/java/com/example/Covered.java b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/main/java/com/example/Covered.java index ea7b74b51..446ba6033 100644 --- a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/main/java/com/example/Covered.java +++ b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/main/java/com/example/Covered.java @@ -1,13 +1,13 @@ -package com.example; - -public class Covered { - - public static int someCode(int i) { - if ( i == 0 ) { - return 1; - } - - return 1; - } - -} +package com.example; + +public class Covered { + + public static int someCode(int i) { + if ( i == 0 ) { + return 1; + } + + return 1; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/main/java/com/example/NotCovered.java b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/main/java/com/example/NotCovered.java index ac93a193e..8a750afbe 100644 --- a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/main/java/com/example/NotCovered.java +++ b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/main/java/com/example/NotCovered.java @@ -1,17 +1,17 @@ -package com.example; - -public class NotCovered { - - public static int someCode(int i) { - if ( i == 0 ) { - return 1; - } - - if ( i == 2 ) { - return 42; - } - - return i; - } - -} +package com.example; + +public class NotCovered { + + public static int someCode(int i) { + if ( i == 0 ) { + return 1; + } + + if ( i == 2 ) { + return 42; + } + + return i; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ATest.java b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ATest.java index 8a389aafd..e59229e7b 100644 --- a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ATest.java +++ b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ATest.java @@ -1,23 +1,23 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import static org.junit.Assert.assertEquals; - -@Category(ExcludeMe.class) -public class ATest { - - @Test - public void aTest() { - assertEquals(1, NotCovered.someCode(0)); - } - - @Test - public void anotherTest() { - assertEquals(42, NotCovered.someCode(2)); - } - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import static org.junit.Assert.assertEquals; + +@Category(ExcludeMe.class) +public class ATest { + + @Test + public void aTest() { + assertEquals(1, NotCovered.someCode(0)); + } + + @Test + public void anotherTest() { + assertEquals(42, NotCovered.someCode(2)); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/AnotherTest.java b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/AnotherTest.java index 7a5871b53..0cdb19188 100644 --- a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/AnotherTest.java +++ b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/AnotherTest.java @@ -1,21 +1,21 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class AnotherTest { - - @Test - public void aTest() { - assertEquals(1, Covered.someCode(0)); - } - - @Test - public void anotherTest() { - assertEquals(1, Covered.someCode(1)); - } - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AnotherTest { + + @Test + public void aTest() { + assertEquals(1, Covered.someCode(0)); + } + + @Test + public void anotherTest() { + assertEquals(1, Covered.someCode(1)); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ExcludeMe.java b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ExcludeMe.java index eca1954ef..be166b0de 100644 --- a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ExcludeMe.java +++ b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ExcludeMe.java @@ -1,4 +1,4 @@ -package com.example; - -public interface ExcludeMe { -} +package com.example; + +public interface ExcludeMe { +} diff --git a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ExcludedByInheritenceTest.java b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ExcludedByInheritenceTest.java index 56a65b625..e2d6996ea 100644 --- a/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ExcludedByInheritenceTest.java +++ b/pitest-maven-verification/src/test/resources/pit-junit-categories/src/test/java/com/example/ExcludedByInheritenceTest.java @@ -1,20 +1,20 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class ExcludedByInheritenceTest extends ATest { - @Test - public void aTest() { - assertEquals(1, NotCovered.someCode(0)); - } - - @Test - public void anotherTest() { - assertEquals(42, NotCovered.someCode(2)); - } - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ExcludedByInheritenceTest extends ATest { + @Test + public void aTest() { + assertEquals(1, NotCovered.someCode(0)); + } + + @Test + public void anotherTest() { + assertEquals(42, NotCovered.someCode(2)); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-powermock/pom.xml b/pitest-maven-verification/src/test/resources/pit-powermock/pom.xml index e125e3c09..b632e4220 100644 --- a/pitest-maven-verification/src/test/resources/pit-powermock/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-powermock/pom.xml @@ -1,76 +1,76 @@ - - 4.0.0 - org.example - pitest-powermock - jar - 1.0-SNAPSHOT - pitest-powermock-verification - - - junit - junit - ${junit.version} - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito - ${powermock.version} - test - - - org.powermock - powermock-module-junit4-rule-agent - ${powermock.version} - test - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - -noverify - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.7 - 1.7 - - - - org.pitest - pitest-maven - ${pit.version} - - - -noverify - - XML - false - com.example* - true - 4000 - - - - - - - - 4.12 - 1.7.3 - - - + + 4.0.0 + org.example + pitest-powermock + jar + 1.0-SNAPSHOT + pitest-powermock-verification + + + junit + junit + ${junit.version} + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito + ${powermock.version} + test + + + org.powermock + powermock-module-junit4-rule-agent + ${powermock.version} + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + -noverify + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.7 + 1.7 + + + + org.pitest + pitest-maven + ${pit.version} + + + -noverify + + XML + false + com.example* + true + 4000 + + + + + + + + 4.12 + 1.7.3 + + + diff --git a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockAgentCallFoo.java b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockAgentCallFoo.java index 490f9681f..e1427c01e 100644 --- a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockAgentCallFoo.java +++ b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockAgentCallFoo.java @@ -1,8 +1,8 @@ -package com.example; - -public class PowerMockAgentCallFoo { - - public void call() { - PowerMockAgentFoo.foo(); - } +package com.example; + +public class PowerMockAgentCallFoo { + + public void call() { + PowerMockAgentFoo.foo(); + } } \ No newline at end of file diff --git a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockAgentFoo.java b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockAgentFoo.java index 0a8b7c10d..f484c079b 100644 --- a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockAgentFoo.java +++ b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockAgentFoo.java @@ -1,7 +1,7 @@ -package com.example; - -public class PowerMockAgentFoo { - public static void foo() { - System.out.println("static method called"); - } -} +package com.example; + +public class PowerMockAgentFoo { + public static void foo() { + System.out.println("static method called"); + } +} diff --git a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockCallFoo.java b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockCallFoo.java index 13643a1d8..22e3c49c8 100644 --- a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockCallFoo.java +++ b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockCallFoo.java @@ -1,8 +1,8 @@ -package com.example; - -public class PowerMockCallFoo { - - public void call() { - PowerMockFoo.foo(); - } -} +package com.example; + +public class PowerMockCallFoo { + + public void call() { + PowerMockFoo.foo(); + } +} diff --git a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockCallsOwnMethod.java b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockCallsOwnMethod.java index c76a0779e..8e64105d2 100644 --- a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockCallsOwnMethod.java +++ b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockCallsOwnMethod.java @@ -1,19 +1,19 @@ -package com.example; - -public class PowerMockCallsOwnMethod { - public void call() { - foo(); - } - - public static void foo() { - - } - - public int branchedCode(int anInt) { - int ret = 10; - if (anInt > 0) { - ret = ret + anInt; - } - return ret; - } -} +package com.example; + +public class PowerMockCallsOwnMethod { + public void call() { + foo(); + } + + public static void foo() { + + } + + public int branchedCode(int anInt) { + int ret = 10; + if (anInt > 0) { + ret = ret + anInt; + } + return ret; + } +} diff --git a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockFoo.java b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockFoo.java index adc815588..40a67426f 100644 --- a/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockFoo.java +++ b/pitest-maven-verification/src/test/resources/pit-powermock/src/main/java/com/example/PowerMockFoo.java @@ -1,7 +1,7 @@ -package com.example; - -public class PowerMockFoo { - public static void foo() { - System.out.println("static method called"); - } +package com.example; + +public class PowerMockFoo { + public static void foo() { + System.out.println("static method called"); + } } \ No newline at end of file diff --git a/pitest-maven-verification/src/test/resources/pit-powermock/src/test/java/com/example/PowerMockAgentTest.java b/pitest-maven-verification/src/test/resources/pit-powermock/src/test/java/com/example/PowerMockAgentTest.java index 00cb95998..d36276152 100644 --- a/pitest-maven-verification/src/test/resources/pit-powermock/src/test/java/com/example/PowerMockAgentTest.java +++ b/pitest-maven-verification/src/test/resources/pit-powermock/src/test/java/com/example/PowerMockAgentTest.java @@ -1,40 +1,40 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -import org.junit.Rule; -import org.junit.Test; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.rule.PowerMockRule; - -@PrepareForTest({ PowerMockAgentFoo.class }) -public class PowerMockAgentTest { - - @Rule - public PowerMockRule rule = new PowerMockRule(); - - @Test - public void testReplaceStaticCallToOtherClass() { - PowerMockito.mockStatic(PowerMockAgentFoo.class); - - new PowerMockAgentCallFoo().call(); - - PowerMockito.verifyStatic(); - PowerMockAgentFoo.foo(); - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +import org.junit.Rule; +import org.junit.Test; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.rule.PowerMockRule; + +@PrepareForTest({ PowerMockAgentFoo.class }) +public class PowerMockAgentTest { + + @Rule + public PowerMockRule rule = new PowerMockRule(); + + @Test + public void testReplaceStaticCallToOtherClass() { + PowerMockito.mockStatic(PowerMockAgentFoo.class); + + new PowerMockAgentCallFoo().call(); + + PowerMockito.verifyStatic(); + PowerMockAgentFoo.foo(); + + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-powermock/src/test/java/com/example/PowerMockTest.java b/pitest-maven-verification/src/test/resources/pit-powermock/src/test/java/com/example/PowerMockTest.java index 8fba4dd42..f228c3dff 100644 --- a/pitest-maven-verification/src/test/resources/pit-powermock/src/test/java/com/example/PowerMockTest.java +++ b/pitest-maven-verification/src/test/resources/pit-powermock/src/test/java/com/example/PowerMockTest.java @@ -1,66 +1,66 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.junit.Assert.assertEquals; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ PowerMockFoo.class, PowerMockCallsOwnMethod.class }) -@PowerMockIgnore("org.pitest.*") -public class PowerMockTest { - - @Test - public void testReplaceStaticCallToOtherClass() { - PowerMockito.mockStatic(PowerMockFoo.class); - - new PowerMockCallFoo().call(); - - PowerMockito.verifyStatic(); - PowerMockFoo.foo(); - - } - - @Test - public void testReplaceStaticCallToMutatedClass() { - PowerMockito.mockStatic(PowerMockCallsOwnMethod.class); - - new PowerMockCallsOwnMethod().call(); - - PowerMockito.verifyStatic(); - PowerMockCallsOwnMethod.foo(); - - } - - @Test - public void testMutationInBranchedCode() { - PowerMockCallsOwnMethod testee = new PowerMockCallsOwnMethod(); - assertEquals(10,testee.branchedCode(0)); - assertEquals(12,testee.branchedCode(2)); - assertEquals(11,testee.branchedCode(1)); - } - -} - - - - - +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PowerMockFoo.class, PowerMockCallsOwnMethod.class }) +@PowerMockIgnore("org.pitest.*") +public class PowerMockTest { + + @Test + public void testReplaceStaticCallToOtherClass() { + PowerMockito.mockStatic(PowerMockFoo.class); + + new PowerMockCallFoo().call(); + + PowerMockito.verifyStatic(); + PowerMockFoo.foo(); + + } + + @Test + public void testReplaceStaticCallToMutatedClass() { + PowerMockito.mockStatic(PowerMockCallsOwnMethod.class); + + new PowerMockCallsOwnMethod().call(); + + PowerMockito.verifyStatic(); + PowerMockCallsOwnMethod.foo(); + + } + + @Test + public void testMutationInBranchedCode() { + PowerMockCallsOwnMethod testee = new PowerMockCallsOwnMethod(); + assertEquals(10,testee.branchedCode(0)); + assertEquals(12,testee.branchedCode(2)); + assertEquals(11,testee.branchedCode(1)); + } + +} + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-process-hang/pom.xml b/pitest-maven-verification/src/test/resources/pit-process-hang/pom.xml index f574abc65..3b41e3a5f 100644 --- a/pitest-maven-verification/src/test/resources/pit-process-hang/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-process-hang/pom.xml @@ -1,52 +1,52 @@ - - - 4.0.0 - com.example - pitest-sample - 0.1-SNAPSHOT - pit process hang - - - UTF-8 - - - - - junit - junit - 4.8.2 - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - true - XML - false - true - - VOID_METHOD_CALLS - - - - - - - + + + 4.0.0 + com.example + pitest-sample + 0.1-SNAPSHOT + pit process hang + + + UTF-8 + + + + + junit + junit + 4.8.2 + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + true + XML + false + true + + VOID_METHOD_CALLS + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-process-hang/src/main/java/com/example/SomeCode.java b/pitest-maven-verification/src/test/resources/pit-process-hang/src/main/java/com/example/SomeCode.java index 7e0f11755..edf4e4772 100644 --- a/pitest-maven-verification/src/test/resources/pit-process-hang/src/main/java/com/example/SomeCode.java +++ b/pitest-maven-verification/src/test/resources/pit-process-hang/src/main/java/com/example/SomeCode.java @@ -1,11 +1,11 @@ -package com.example; - -public class SomeCode { - - public void generateLotsOfOutput() { - for ( int i = 0; i != 10000; i++) { - System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA " + i); - } - } - -} +package com.example; + +public class SomeCode { + + public void generateLotsOfOutput() { + for ( int i = 0; i != 10000; i++) { + System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA " + i); + } + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-process-hang/src/test/java/com/example/SomeCodeTest.java b/pitest-maven-verification/src/test/resources/pit-process-hang/src/test/java/com/example/SomeCodeTest.java index f9d9d1130..69df8bf19 100644 --- a/pitest-maven-verification/src/test/resources/pit-process-hang/src/test/java/com/example/SomeCodeTest.java +++ b/pitest-maven-verification/src/test/resources/pit-process-hang/src/test/java/com/example/SomeCodeTest.java @@ -1,18 +1,18 @@ -package com.example; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.example.SomeCode; - -public class SomeCodeTest { - - @Test - public void testStuff() { - SomeCode req = new SomeCode(); - req.generateLotsOfOutput(); - } - -} +package com.example; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import com.example.SomeCode; + +public class SomeCodeTest { + + @Test + public void testStuff() { + SomeCode req = new SomeCode(); + req.generateLotsOfOutput(); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-site-combined/pom.xml b/pitest-maven-verification/src/test/resources/pit-site-combined/pom.xml index e73081af9..d5f8f99fc 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-combined/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-site-combined/pom.xml @@ -1,62 +1,62 @@ - - 4.0.0 - org.example - pit-site-combined - jar - 1.0-SNAPSHOT - pit-site-combined - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.4 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - - - - - - org.pitest - pitest-maven - ${pit.version} - - - - report - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - index - - - - - - - - + + 4.0.0 + org.example + pit-site-combined + jar + 1.0-SNAPSHOT + pit-site-combined + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.4 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + + + + + + org.pitest + pitest-maven + ${pit.version} + + + + report + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + index + + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-site-custom-config/pom.xml b/pitest-maven-verification/src/test/resources/pit-site-custom-config/pom.xml index 36d88e05e..e0f9f553b 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-custom-config/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-site-custom-config/pom.xml @@ -1,68 +1,68 @@ - - 4.0.0 - org.example - pit-site-custom-config - jar - 1.0-SNAPSHOT - pit-site-custom-config - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.4 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - - - - - - org.pitest - pitest-maven - ${pit.version} - - my-test-pit-report-name - my-test-pit-report-description - foobar - ${project.build.directory}/new-report-location - - - - - report - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - index - - - - - - - - + + 4.0.0 + org.example + pit-site-custom-config + jar + 1.0-SNAPSHOT + pit-site-custom-config + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.4 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + + + + + + org.pitest + pitest-maven + ${pit.version} + + my-test-pit-report-name + my-test-pit-report-description + foobar + ${project.build.directory}/new-report-location + + + + + report + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + index + + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-site-multiple-timestamped/pom.xml b/pitest-maven-verification/src/test/resources/pit-site-multiple-timestamped/pom.xml index 369f4be3f..6e5fca44e 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-multiple-timestamped/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-site-multiple-timestamped/pom.xml @@ -1,62 +1,62 @@ - - 4.0.0 - org.example - pit-site-multiple-timestamped - jar - 1.0-SNAPSHOT - pit-site-multiple-timestamped - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.4 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - - - - - - org.pitest - pitest-maven - ${pit.version} - - - - report - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - index - - - - - - - - + + 4.0.0 + org.example + pit-site-multiple-timestamped + jar + 1.0-SNAPSHOT + pit-site-multiple-timestamped + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.4 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + + + + + + org.pitest + pitest-maven + ${pit.version} + + + + report + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + index + + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-site-non-timestamped/pom.xml b/pitest-maven-verification/src/test/resources/pit-site-non-timestamped/pom.xml index 5b60dd0e4..7a11f97c6 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-non-timestamped/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-site-non-timestamped/pom.xml @@ -1,62 +1,62 @@ - - 4.0.0 - org.example - pit-site-non-timestamped - jar - 1.0-SNAPSHOT - pit-site-non-timestamped - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.4 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - - - - - - org.pitest - pitest-maven - ${pit.version} - - - - report - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - index - - - - - - - - + + 4.0.0 + org.example + pit-site-non-timestamped + jar + 1.0-SNAPSHOT + pit-site-non-timestamped + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.4 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + + + + + + org.pitest + pitest-maven + ${pit.version} + + + + report + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + index + + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-site-reportonly/pom.xml b/pitest-maven-verification/src/test/resources/pit-site-reportonly/pom.xml index dfcf6b3e2..9e899404c 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-reportonly/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-site-reportonly/pom.xml @@ -1,69 +1,69 @@ - - 4.0.0 - org.example - pit-site-reportonly - jar - 1.0-SNAPSHOT - pit-site-non-timestamped - - - junit - junit - 4.11 - test - - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.4 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - - - - - - org.pitest - pitest-maven - ${pit.version} - - - - report - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - index - - - - - - - - + + 4.0.0 + org.example + pit-site-reportonly + jar + 1.0-SNAPSHOT + pit-site-non-timestamped + + + junit + junit + 4.11 + test + + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.4 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + + + + + + org.pitest + pitest-maven + ${pit.version} + + + + report + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + index + + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-site-reportonly/src/main/java/com/example/Covered.java b/pitest-maven-verification/src/test/resources/pit-site-reportonly/src/main/java/com/example/Covered.java index ea7b74b51..446ba6033 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-reportonly/src/main/java/com/example/Covered.java +++ b/pitest-maven-verification/src/test/resources/pit-site-reportonly/src/main/java/com/example/Covered.java @@ -1,13 +1,13 @@ -package com.example; - -public class Covered { - - public static int someCode(int i) { - if ( i == 0 ) { - return 1; - } - - return 1; - } - -} +package com.example; + +public class Covered { + + public static int someCode(int i) { + if ( i == 0 ) { + return 1; + } + + return 1; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-site-reportonly/src/test/java/com/example/AnotherTest.java b/pitest-maven-verification/src/test/resources/pit-site-reportonly/src/test/java/com/example/AnotherTest.java index 7a5871b53..0cdb19188 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-reportonly/src/test/java/com/example/AnotherTest.java +++ b/pitest-maven-verification/src/test/resources/pit-site-reportonly/src/test/java/com/example/AnotherTest.java @@ -1,21 +1,21 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class AnotherTest { - - @Test - public void aTest() { - assertEquals(1, Covered.someCode(0)); - } - - @Test - public void anotherTest() { - assertEquals(1, Covered.someCode(1)); - } - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AnotherTest { + + @Test + public void aTest() { + assertEquals(1, Covered.someCode(0)); + } + + @Test + public void anotherTest() { + assertEquals(1, Covered.someCode(1)); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-site-skip/pom.xml b/pitest-maven-verification/src/test/resources/pit-site-skip/pom.xml index 18d573df9..4f3de9d96 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-skip/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-site-skip/pom.xml @@ -1,65 +1,65 @@ - - 4.0.0 - org.example - pit-site-skip - jar - 1.0-SNAPSHOT - pit-site-skip - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.4 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - - - - - - org.pitest - pitest-maven - ${pit.version} - - true - - - - - report - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - index - - - - - - - - + + 4.0.0 + org.example + pit-site-skip + jar + 1.0-SNAPSHOT + pit-site-skip + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.4 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + + + + + + org.pitest + pitest-maven + ${pit.version} + + true + + + + + report + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + index + + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-site-timestamped/pom.xml b/pitest-maven-verification/src/test/resources/pit-site-timestamped/pom.xml index f8014f2f0..f6ea9fc1f 100644 --- a/pitest-maven-verification/src/test/resources/pit-site-timestamped/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-site-timestamped/pom.xml @@ -1,62 +1,62 @@ - - 4.0.0 - org.example - pit-site-timestamped - jar - 1.0-SNAPSHOT - pit-site-timestamped - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.4 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - - - - - - org.pitest - pitest-maven - ${pit.version} - - - - report - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - index - - - - - - - - + + 4.0.0 + org.example + pit-site-timestamped + jar + 1.0-SNAPSHOT + pit-site-timestamped + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.4 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + + + + + + org.pitest + pitest-maven + ${pit.version} + + + + report + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + index + + + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/pom.xml b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/pom.xml index dc40a0b33..e9ed7f367 100644 --- a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/pom.xml @@ -1,59 +1,59 @@ - - 4.0.0 - com.example - junit-categories-check - jar - 1.0-SNAPSHOT - surefire-excludes - - - junit - junit - 4.11 - test - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18.1 - - - **/FailingTest.java - **/BadTest.java - - - - - org.pitest - pitest-maven - ${pit.version} - - true - - XML - - 1 - false - - NEGATE_CONDITIONALS - - true - - - - - - + + 4.0.0 + com.example + junit-categories-check + jar + 1.0-SNAPSHOT + surefire-excludes + + + junit + junit + 4.11 + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + + + **/FailingTest.java + **/BadTest.java + + + + + org.pitest + pitest-maven + ${pit.version} + + true + + XML + + 1 + false + + NEGATE_CONDITIONALS + + true + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/main/java/com/example/Covered.java b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/main/java/com/example/Covered.java index ea7b74b51..446ba6033 100644 --- a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/main/java/com/example/Covered.java +++ b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/main/java/com/example/Covered.java @@ -1,13 +1,13 @@ -package com.example; - -public class Covered { - - public static int someCode(int i) { - if ( i == 0 ) { - return 1; - } - - return 1; - } - -} +package com.example; + +public class Covered { + + public static int someCode(int i) { + if ( i == 0 ) { + return 1; + } + + return 1; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/main/java/com/example/NotCovered.java b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/main/java/com/example/NotCovered.java index ac93a193e..8a750afbe 100644 --- a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/main/java/com/example/NotCovered.java +++ b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/main/java/com/example/NotCovered.java @@ -1,17 +1,17 @@ -package com.example; - -public class NotCovered { - - public static int someCode(int i) { - if ( i == 0 ) { - return 1; - } - - if ( i == 2 ) { - return 42; - } - - return i; - } - -} +package com.example; + +public class NotCovered { + + public static int someCode(int i) { + if ( i == 0 ) { + return 1; + } + + if ( i == 2 ) { + return 42; + } + + return i; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/test/java/com/example/AnotherTest.java b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/test/java/com/example/AnotherTest.java index 7a5871b53..0cdb19188 100644 --- a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/test/java/com/example/AnotherTest.java +++ b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/test/java/com/example/AnotherTest.java @@ -1,21 +1,21 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class AnotherTest { - - @Test - public void aTest() { - assertEquals(1, Covered.someCode(0)); - } - - @Test - public void anotherTest() { - assertEquals(1, Covered.someCode(1)); - } - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AnotherTest { + + @Test + public void aTest() { + assertEquals(1, Covered.someCode(0)); + } + + @Test + public void anotherTest() { + assertEquals(1, Covered.someCode(1)); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/test/java/com/example/BadTest.java b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/test/java/com/example/BadTest.java index 2d93c7688..537865909 100644 --- a/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/test/java/com/example/BadTest.java +++ b/pitest-maven-verification/src/test/resources/pit-surefire-excludes/src/test/java/com/example/BadTest.java @@ -1,16 +1,16 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class BadTest { - - @Test - public void aTest() { - assertEquals(1, 2); - } - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class BadTest { + + @Test + public void aTest() { + assertEquals(1, 2); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/pom.xml b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/pom.xml index 2b77b4258..92dac56d5 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/pom.xml @@ -1,57 +1,57 @@ - - 4.0.0 - org.example - basic-testng-check - jar - 1.0-SNAPSHOT - basic-testng-check - - - org.jmockit - jmockit - 1.25 - test - - - org.testng - testng - 6.8.8 - test - - - org.hamcrest - java-hamcrest - 2.0.0.0 - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - testng - XML - 6 - false - com.example* - true - - - - - - + + 4.0.0 + org.example + basic-testng-check + jar + 1.0-SNAPSHOT + basic-testng-check + + + org.jmockit + jmockit + 1.25 + test + + + org.testng + testng + 6.8.8 + test + + + org.hamcrest + java-hamcrest + 2.0.0.0 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + testng + XML + 6 + false + com.example* + true + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/main/java/com/example/Covered.java b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/main/java/com/example/Covered.java index bc0a1fdfd..0d402ebae 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/main/java/com/example/Covered.java +++ b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/main/java/com/example/Covered.java @@ -1,17 +1,17 @@ -package com.example; - -public class Covered { - - public static int someCode(int i) { - if ( i == 0 ) { - return 1; - } - - if ( i == 2 ) { - return 42; - } - - return i; - } - -} +package com.example; + +public class Covered { + + public static int someCode(int i) { + if ( i == 0 ) { + return 1; + } + + if ( i == 2 ) { + return 42; + } + + return i; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/main/java/com/example/ValueHolder.java b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/main/java/com/example/ValueHolder.java index b6b167860..b0fed2c38 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/main/java/com/example/ValueHolder.java +++ b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/main/java/com/example/ValueHolder.java @@ -1,18 +1,18 @@ -package com.example; - -public class ValueHolder { - - private final int value; - - public ValueHolder( int value ) { - if ( value < 0 ) { - throw new IllegalArgumentException(); - } - this.value = value; - } - - public int getValue() { - return value; - } - -} +package com.example; + +public class ValueHolder { + + private final int value; + + public ValueHolder( int value ) { + if ( value < 0 ) { + throw new IllegalArgumentException(); + } + this.value = value; + } + + public int getValue() { + return value; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ATest.java b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ATest.java index 7471b70e7..99d118b5b 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ATest.java +++ b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ATest.java @@ -1,19 +1,19 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; - -import static org.testng.Assert.assertEquals; - -@org.testng.annotations.Test -public class ATest { - - public void aTest() { - assertEquals(1, Covered.someCode(0)); - } - - public void anotherTest() { - assertEquals(42, Covered.someCode(2)); - } - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; + +import static org.testng.Assert.assertEquals; + +@org.testng.annotations.Test +public class ATest { + + public void aTest() { + assertEquals(1, Covered.someCode(0)); + } + + public void anotherTest() { + assertEquals(42, Covered.someCode(2)); + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderBasicTest.java b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderBasicTest.java index 11d55fcb8..212ff26fa 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderBasicTest.java +++ b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderBasicTest.java @@ -1,14 +1,14 @@ -package com.example; - -import org.testng.annotations.Test; - -public class ValueHolderBasicTest { - - @Test - public void test() { - ValueHolder holder = new ValueHolder( 1 ); - int actual = holder.getValue(); - assert actual == 1 : "actual value is " + actual; - } - -} +package com.example; + +import org.testng.annotations.Test; + +public class ValueHolderBasicTest { + + @Test + public void test() { + ValueHolder holder = new ValueHolder( 1 ); + int actual = holder.getValue(); + assert actual == 1 : "actual value is " + actual; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderDataTest.java b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderDataTest.java index 0dabaa58e..fbb9d12e7 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderDataTest.java +++ b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderDataTest.java @@ -1,25 +1,25 @@ -package com.example; - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -public class ValueHolderDataTest { - - @Test( dataProvider = "data" ) - public void test( int expected ) { - ValueHolder holder = new ValueHolder( expected ); - int actual = holder.getValue(); - assert actual == expected : "actual value is " + actual; - } - - - @DataProvider - public static Object[][] data() { - return new Object[][] { - { 0 }, - { 1 }, - { 2 } - }; - } - -} +package com.example; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class ValueHolderDataTest { + + @Test( dataProvider = "data" ) + public void test( int expected ) { + ValueHolder holder = new ValueHolder( expected ); + int actual = holder.getValue(); + assert actual == expected : "actual value is " + actual; + } + + + @DataProvider + public static Object[][] data() { + return new Object[][] { + { 0 }, + { 1 }, + { 2 } + }; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderMockitTest.java b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderMockitTest.java index 686e13b6f..845709075 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderMockitTest.java +++ b/pitest-maven-verification/src/test/resources/pit-testng-jmockit/src/test/java/com/example/ValueHolderMockitTest.java @@ -1,19 +1,19 @@ -package com.example; - -import mockit.Expectations; -import mockit.Mocked; -import org.testng.annotations.Test; - -public class ValueHolderMockitTest { - - @Test - public void test( @Mocked final ValueHolder holder ) { - new Expectations() {{ - holder.getValue(); - result = 1; - }}; - int value = holder.getValue(); - assert value == 1 : "value is " + value; - } - -} +package com.example; + +import mockit.Expectations; +import mockit.Mocked; +import org.testng.annotations.Test; + +public class ValueHolderMockitTest { + + @Test + public void test( @Mocked final ValueHolder holder ) { + new Expectations() {{ + holder.getValue(); + result = 1; + }}; + int value = holder.getValue(); + assert value == 1 : "value is " + value; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-testng/pom.xml b/pitest-maven-verification/src/test/resources/pit-testng/pom.xml index d46904b35..f5bf2c0ea 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng/pom.xml +++ b/pitest-maven-verification/src/test/resources/pit-testng/pom.xml @@ -1,44 +1,44 @@ - - 4.0.0 - org.example - basic-testng-check - jar - 1.0-SNAPSHOT - basic-testng-check - - - org.testng - testng - 6.1.1 - test - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.4 - - 1.6 - 1.6 - - - - org.pitest - pitest-maven - ${pit.version} - - testng - XML - 6 - false - com.example* - true - - - - - - + + 4.0.0 + org.example + basic-testng-check + jar + 1.0-SNAPSHOT + basic-testng-check + + + org.testng + testng + 6.1.1 + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + + + + org.pitest + pitest-maven + ${pit.version} + + testng + XML + 6 + false + com.example* + true + + + + + + diff --git a/pitest-maven-verification/src/test/resources/pit-testng/src/main/java/com/example/Covered.java b/pitest-maven-verification/src/test/resources/pit-testng/src/main/java/com/example/Covered.java index bc0a1fdfd..0d402ebae 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng/src/main/java/com/example/Covered.java +++ b/pitest-maven-verification/src/test/resources/pit-testng/src/main/java/com/example/Covered.java @@ -1,17 +1,17 @@ -package com.example; - -public class Covered { - - public static int someCode(int i) { - if ( i == 0 ) { - return 1; - } - - if ( i == 2 ) { - return 42; - } - - return i; - } - -} +package com.example; + +public class Covered { + + public static int someCode(int i) { + if ( i == 0 ) { + return 1; + } + + if ( i == 2 ) { + return 42; + } + + return i; + } + +} diff --git a/pitest-maven-verification/src/test/resources/pit-testng/src/test/java/com/example/ATest.java b/pitest-maven-verification/src/test/resources/pit-testng/src/test/java/com/example/ATest.java index 7471b70e7..99d118b5b 100644 --- a/pitest-maven-verification/src/test/resources/pit-testng/src/test/java/com/example/ATest.java +++ b/pitest-maven-verification/src/test/resources/pit-testng/src/test/java/com/example/ATest.java @@ -1,19 +1,19 @@ -package com.example; - -import java.util.Arrays; -import java.util.Collection; - -import static org.testng.Assert.assertEquals; - -@org.testng.annotations.Test -public class ATest { - - public void aTest() { - assertEquals(1, Covered.someCode(0)); - } - - public void anotherTest() { - assertEquals(42, Covered.someCode(2)); - } - -} +package com.example; + +import java.util.Arrays; +import java.util.Collection; + +import static org.testng.Assert.assertEquals; + +@org.testng.annotations.Test +public class ATest { + + public void aTest() { + assertEquals(1, Covered.someCode(0)); + } + + public void anotherTest() { + assertEquals(42, Covered.someCode(2)); + } + +} diff --git a/pitest-maven-verification/src/test/resources/simplelogger.properties b/pitest-maven-verification/src/test/resources/simplelogger.properties index 6da16bb64..1ced88564 100644 --- a/pitest-maven-verification/src/test/resources/simplelogger.properties +++ b/pitest-maven-verification/src/test/resources/simplelogger.properties @@ -1,2 +1,2 @@ -org.slf4j.simpleLogger.showDateTime=true +org.slf4j.simpleLogger.showDateTime=true org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS \ No newline at end of file diff --git a/pitest-maven/pom.xml b/pitest-maven/pom.xml index f400d55aa..c437e177d 100644 --- a/pitest-maven/pom.xml +++ b/pitest-maven/pom.xml @@ -1,187 +1,187 @@ - - - 4.0.0 - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - pitest-maven - maven-plugin - pitest-maven - Pitest Maven Mojo. - http://pitest.org - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - maven-surefire-plugin - - org.pitest.maven.SystemTest - - - - maven-failsafe-plugin - - org.pitest.maven.SystemTest - - - - - integration-test - verify - - - - **/*.class - - - - - - - org.apache.maven.plugins - maven-plugin-plugin - 3.5 - - - default-descriptor - process-classes - - - help-goal - - helpmojo - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - -Xdoclint:none - - - - - - - - org.pitest - pitest-entry - ${project.version} - - - org.pitest - pitest-html-report - ${project.version} - - - org.pitest - pitest-aggregator - ${project.version} - - - org.apache.maven - maven-plugin-api - ${maven.version} - - - org.apache.maven.plugin-tools - maven-plugin-annotations - 3.4 - provided - - - org.apache.maven.reporting - maven-reporting-api - ${maven.version} - - - org.apache.maven.reporting - maven-reporting-impl - 2.0.4.3 - - - org.apache.maven - maven-project - ${maven.version} - - - org.apache.maven.scm - maven-scm-api - ${scm.version} - - - org.apache.maven.scm - maven-scm-manager-plexus - ${scm.version} - - - org.apache.maven.scm - maven-scm-providers-standard - ${scm.version} - pom - - - org.apache.maven.surefire - surefire-booter - ${surefire.version} - - - org.apache.maven.surefire - maven-surefire-common - ${surefire.version} - - - org.apache.maven - maven-artifact - ${maven.version} - - - org.apache.maven - maven-toolchain - ${maven.version} - - - org.slf4j - jul-to-slf4j - ${slf4j.version} - - - uk.org.lidalia - sysout-over-slf4j - 1.0.2 - - - org.slf4j - slf4j-api - ${slf4j.version} - provided - - - - - org.apache.maven.shared - maven-plugin-testing-harness - 1.1 - test - - - org.apache.maven.shared - maven-verifier - ${maven-verifier} - test - - - - - - 1.9.4 - - + + + 4.0.0 + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + pitest-maven + maven-plugin + pitest-maven + Pitest Maven Mojo. + http://pitest.org + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + maven-surefire-plugin + + org.pitest.maven.SystemTest + + + + maven-failsafe-plugin + + org.pitest.maven.SystemTest + + + + + integration-test + verify + + + + **/*.class + + + + + + + org.apache.maven.plugins + maven-plugin-plugin + 3.5 + + + default-descriptor + process-classes + + + help-goal + + helpmojo + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + -Xdoclint:none + + + + + + + + org.pitest + pitest-entry + ${project.version} + + + org.pitest + pitest-html-report + ${project.version} + + + org.pitest + pitest-aggregator + ${project.version} + + + org.apache.maven + maven-plugin-api + ${maven.version} + + + org.apache.maven.plugin-tools + maven-plugin-annotations + 3.4 + provided + + + org.apache.maven.reporting + maven-reporting-api + ${maven.version} + + + org.apache.maven.reporting + maven-reporting-impl + 2.0.4.3 + + + org.apache.maven + maven-project + ${maven.version} + + + org.apache.maven.scm + maven-scm-api + ${scm.version} + + + org.apache.maven.scm + maven-scm-manager-plexus + ${scm.version} + + + org.apache.maven.scm + maven-scm-providers-standard + ${scm.version} + pom + + + org.apache.maven.surefire + surefire-booter + ${surefire.version} + + + org.apache.maven.surefire + maven-surefire-common + ${surefire.version} + + + org.apache.maven + maven-artifact + ${maven.version} + + + org.apache.maven + maven-toolchain + ${maven.version} + + + org.slf4j + jul-to-slf4j + ${slf4j.version} + + + uk.org.lidalia + sysout-over-slf4j + 1.0.2 + + + org.slf4j + slf4j-api + ${slf4j.version} + provided + + + + + org.apache.maven.shared + maven-plugin-testing-harness + 1.1 + test + + + org.apache.maven.shared + maven-verifier + ${maven-verifier} + test + + + + + + 1.9.4 + + diff --git a/pitest-maven/src/main/java/org/pitest/maven/AbstractPitMojo.java b/pitest-maven/src/main/java/org/pitest/maven/AbstractPitMojo.java index 11f72175c..c1d5bc9da 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/AbstractPitMojo.java +++ b/pitest-maven/src/main/java/org/pitest/maven/AbstractPitMojo.java @@ -1,656 +1,656 @@ -package org.pitest.maven; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; -import org.pitest.coverage.CoverageSummary; -import java.util.Optional; -import java.util.function.Predicate; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.statistics.MutationStatistics; -import org.pitest.mutationtest.tooling.CombinedStatistics; -import org.pitest.plugin.ClientClasspathPlugin; -import org.pitest.plugin.ToolClasspathPlugin; -import org.slf4j.bridge.SLF4JBridgeHandler; - -import uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J; - -public class AbstractPitMojo extends AbstractMojo { - - private final Predicate notEmptyProject; - - protected final Predicate filter; - - protected final PluginServices plugins; - - // Concrete List types declared for all fields to work around maven 2 bug - - /** - * Test plugin to use - */ - @Parameter(property = "testPlugin", defaultValue = "") - private String testPlugin; - - /** - * Classes to include in mutation test - */ - @Parameter(property = "targetClasses") - protected ArrayList targetClasses; - - /** - * Tests to run - */ - @Parameter(property = "targetTests") - protected ArrayList targetTests; - - /** - * Methods not to mutate - */ - @Parameter(property = "excludedMethods") - private ArrayList excludedMethods; - - /** - * Classes not to mutate - */ - @Parameter(property = "excludedClasses") - private ArrayList excludedClasses; - - /** - * Classes not to run tests from - */ - @Parameter(property = "excludedTestClasses") - private ArrayList excludedTestClasses; - - - /** - * Globs to be matched against method calls. No mutations will be created on - * the same line as a match. - */ - @Parameter(property = "avoidCallsTo") - private ArrayList avoidCallsTo; - - /** - * Base directory where all reports are written to. - */ - @Parameter(defaultValue = "${project.build.directory}/pit-reports", property = "reportsDirectory") - private File reportsDirectory; - - /** - * File to write history information to for incremental analysis - */ - @Parameter(property = "historyOutputFile") - private File historyOutputFile; - - /** - * File to read history from for incremental analysis (can be same as output - * file) - */ - @Parameter(property = "historyInputFile") - private File historyInputFile; - - /** - * Convenience flag to read and write history to a local temp file. - * - * Setting this flag is the equivalent to calling maven with -DhistoryInputFile=file -DhistoryOutputFile=file - * - * Where file is a file named [groupid][artifactid][version]_pitest_history.bin in the temp directory - * - */ - @Parameter(defaultValue = "false", property = "withHistory") - private boolean withHistory; - - /** - * Maximum distance to look from test to class. Relevant when mutating static - * initializers - * - */ - @Parameter(defaultValue = "-1", property = "maxDependencyDistance") - private int maxDependencyDistance; - - /** - * Number of threads to use - */ - @Parameter(defaultValue = "1", property = "threads") - private int threads; - - /** - * Mutate static initializers - */ - @Parameter(defaultValue = "false", property = "mutateStaticInitializers") - private boolean mutateStaticInitializers; - - /** - * Detect inlined code - */ - @Parameter(defaultValue = "true", property = "detectInlinedCode") - private boolean detectInlinedCode; - - /** - * Mutation operators to apply - */ - @Parameter(property = "mutators") - private ArrayList mutators; - - /** - * Mutation operators to apply - */ - @Parameter(property = "features") - private ArrayList features; - - - /** - * Weighting to allow for timeouts - */ - @Parameter(defaultValue = "1.25", property = "timeoutFactor") - private float timeoutFactor; - - /** - * Constant factor to allow for timeouts - */ - @Parameter(defaultValue = "3000", property = "timeoutConstant") - private long timeoutConstant; - - /** - * Maximum number of mutations to allow per class - */ - @Parameter(defaultValue = "-1", property = "maxMutationsPerClass") - private int maxMutationsPerClass; - - /** - * Arguments to pass to child processes - */ - @Parameter - private ArrayList jvmArgs; - - /** - * Formats to output during analysis phase - */ - @Parameter(property = "outputFormats") - private ArrayList outputFormats; - - /** - * Output verbose logging - */ - @Parameter(defaultValue = "false", property = "verbose") - private boolean verbose; - - /** - * Throw error if no mutations found - */ - @Parameter(defaultValue = "true", property = "failWhenNoMutations") - private boolean failWhenNoMutations; - - /** - * Create timestamped subdirectory for report - */ - @Parameter(defaultValue = "true", property = "timestampedReports") - private boolean timestampedReports; - - /** - * TestNG Groups/JUnit Categories to exclude - */ - @Parameter(property = "excludedGroups") - private ArrayList excludedGroups; - - /** - * TestNG Groups/JUnit Categories to include - */ - @Parameter(property = "includedGroups") - private ArrayList includedGroups; - - /** - * Test methods that should be included for challenging the mutants - */ - @Parameter(property = "includedTestMethods") - private ArrayList includedTestMethods; - /** - * Maximum number of mutations to include in a single analysis unit. - * - * If set to 1 will analyse very slowly, but with strong (jvm per mutant) - * isolation. - * - */ - @Parameter(property = "mutationUnitSize") - private int mutationUnitSize; - - /** - * Export line coverage data - */ - @Parameter(defaultValue = "false", property = "exportLineCoverage") - private boolean exportLineCoverage; - - /** - * Mutation score threshold at which to fail build - */ - @Parameter(defaultValue = "0", property = "mutationThreshold") - private int mutationThreshold; - - /** - * Maximum surviving mutants to allow - */ - @Parameter(defaultValue = "-1", property = "maxSurviving") - private int maxSurviving = -1; - - /** - * Line coverage threshold at which to fail build - */ - @Parameter(defaultValue = "0", property = "coverageThreshold") - private int coverageThreshold; - - /** - * Path to java executable to use when running tests. Will default to - * executable in JAVA_HOME if none set. - */ - @Parameter - private String jvm; - - /** - * Engine to use when generating mutations. - */ - @Parameter(defaultValue = "gregor", property = "mutationEngine") - private String mutationEngine; - - /** - * List of additional classpath entries to use when looking for tests and - * mutable code. These will be used in addition to the classpath with which - * PIT is launched. - */ - @Parameter(property = "additionalClasspathElements") - private ArrayList additionalClasspathElements; - - /** - * List of classpath entries, formatted as "groupId:artifactId", which should - * not be included in the classpath when running mutation tests. Modelled - * after the corresponding Surefire/Failsafe property. - */ - @Parameter(property = "classpathDependencyExcludes") - private ArrayList classpathDependencyExcludes; - - /** - * - */ - @Parameter(property = "excludedRunners") - private ArrayList excludedRunners; - - /** - * When set indicates that analysis of this project should be skipped - */ - @Parameter(defaultValue = "false") - private boolean skip; - - /** - * When set will try and create settings based on surefire configuration. This - * may not give the desired result in some circumstances - */ - @Parameter(defaultValue = "true") - private boolean parseSurefireConfig; - - /** - * honours common skipTests flag in a maven run - */ - @Parameter(defaultValue = "false") - private boolean skipTests; - - /** - * Use slf4j for logging - */ - @Parameter(defaultValue = "false", property = "useSlf4j") - private boolean useSlf4j; - - /** - * Configuration properties. - * - * Value pairs may be used by pitest plugins. - * - */ - @Parameter - private Map pluginConfiguration; - - /** - * environment configuration - * - * Value pairs may be used by pitest plugins. - */ - @Parameter - private Map environmentVariables = new HashMap<>(); - - /** - * Internal: Project to interact with. - * - */ - @Parameter(property = "project", readonly = true, required = true) - protected MavenProject project; - - /** - * Internal: Map of plugin artifacts. - */ - @Parameter(property = "plugin.artifactMap", readonly = true, required = true) - private Map pluginArtifactMap; - - protected final GoalStrategy goalStrategy; - - public AbstractPitMojo() { - this(new RunPitStrategy(), new DependencyFilter(new PluginServices( - AbstractPitMojo.class.getClassLoader())), new PluginServices( - AbstractPitMojo.class.getClassLoader()), new NonEmptyProjectCheck()); - } - - public AbstractPitMojo(final GoalStrategy strategy, final Predicate filter, - final PluginServices plugins, final Predicate emptyProjectCheck) { - this.goalStrategy = strategy; - this.filter = filter; - this.plugins = plugins; - this.notEmptyProject = emptyProjectCheck; - } - - @Override - public final void execute() throws MojoExecutionException, - MojoFailureException { - - switchLogging(); - RunDecision shouldRun = shouldRun(); - - if (shouldRun.shouldRun()) { - for (final ToolClasspathPlugin each : this.plugins - .findToolClasspathPlugins()) { - this.getLog().info("Found plugin : " + each.description()); - } - - for (final ClientClasspathPlugin each : this.plugins - .findClientClasspathPlugins()) { - this.getLog().info( - "Found shared classpath plugin : " + each.description()); - } - - final Optional result = analyse(); - if (result.isPresent()) { - throwErrorIfScoreBelowThreshold(result.get().getMutationStatistics()); - throwErrorIfMoreThanMaximumSurvivors(result.get().getMutationStatistics()); - throwErrorIfCoverageBelowThreshold(result.get().getCoverageSummary()); - } - - } else { - this.getLog().info("Skipping project because:"); - for (String reason : shouldRun.getReasons()) { - this.getLog().info(" - " + reason); - } - } - } - - private void switchLogging() { - if (this.useSlf4j) { - SLF4JBridgeHandler.removeHandlersForRootLogger(); - SLF4JBridgeHandler.install(); - Logger.getLogger("PIT").addHandler(new SLF4JBridgeHandler()); - SysOutOverSLF4J.sendSystemOutAndErrToSLF4J(); - } - } - - private void throwErrorIfCoverageBelowThreshold( - final CoverageSummary coverageSummary) throws MojoFailureException { - if ((this.coverageThreshold != 0) - && (coverageSummary.getCoverage() < this.coverageThreshold)) { - throw new MojoFailureException("Line coverage of " - + coverageSummary.getCoverage() + "(" - + coverageSummary.getNumberOfCoveredLines() + "/" - + coverageSummary.getNumberOfLines() + ") is below threshold of " - + this.coverageThreshold); - } - } - - private void throwErrorIfScoreBelowThreshold(final MutationStatistics result) - throws MojoFailureException { - if ((this.mutationThreshold != 0) - && (result.getPercentageDetected() < this.mutationThreshold)) { - throw new MojoFailureException("Mutation score of " - + result.getPercentageDetected() + " is below threshold of " - + this.mutationThreshold); - } - } - - private void throwErrorIfMoreThanMaximumSurvivors(final MutationStatistics result) - throws MojoFailureException { - if ((this.maxSurviving >= 0) - && (result.getTotalSurvivingMutations() > this.maxSurviving)) { - throw new MojoFailureException("Had " - + result.getTotalSurvivingMutations() + " surviving mutants, but only " - + this.maxSurviving + " survivors allowed"); - } - } - - protected Optional analyse() throws MojoExecutionException { - final ReportOptions data = new MojoToReportOptionsConverter(this, - new SurefireConfigConverter(), this.filter).convert(); - return Optional.ofNullable(this.goalStrategy.execute(detectBaseDir(), data, - this.plugins, this.environmentVariables)); - } - - protected File detectBaseDir() { - // execution project doesn't seem to always be available. - // possibily a maven 2 vs maven 3 issue? - final MavenProject executionProject = this.project.getExecutionProject(); - if (executionProject == null) { - return null; - } - return executionProject.getBasedir(); - } - - public List getTargetClasses() { - return this.targetClasses; - } - - public List getTargetTests() { - return this.targetTests; - } - - public List getExcludedMethods() { - return this.excludedMethods; - } - - public List getExcludedClasses() { - return this.excludedClasses; - } - - public List getAvoidCallsTo() { - return this.avoidCallsTo; - } - - public File getReportsDirectory() { - return this.reportsDirectory; - } - - public int getMaxDependencyDistance() { - return this.maxDependencyDistance; - } - - public int getThreads() { - return this.threads; - } - - public boolean isMutateStaticInitializers() { - return this.mutateStaticInitializers; - } - - public List getMutators() { - return this.mutators; - } - - public float getTimeoutFactor() { - return this.timeoutFactor; - } - - public long getTimeoutConstant() { - return this.timeoutConstant; - } - - public ArrayList getExcludedTestClasses() { - return excludedTestClasses; - } - - public int getMaxMutationsPerClass() { - return this.maxMutationsPerClass; - } - - public List getJvmArgs() { - return this.jvmArgs; - } - - public List getOutputFormats() { - return this.outputFormats; - } - - public boolean isVerbose() { - return this.verbose; - } - - public MavenProject getProject() { - return this.project; - } - - public Map getPluginArtifactMap() { - return this.pluginArtifactMap; - } - - public boolean isFailWhenNoMutations() { - return this.failWhenNoMutations; - } - - public List getExcludedGroups() { - return this.excludedGroups; - } - - public List getIncludedGroups() { - return this.includedGroups; - } - - public List getIncludedTestMethods() { - return this.includedTestMethods; - } - - public int getMutationUnitSize() { - return this.mutationUnitSize; - } - - public boolean isTimestampedReports() { - return this.timestampedReports; - } - - public boolean isDetectInlinedCode() { - return this.detectInlinedCode; - } - - public void setTimestampedReports(final boolean timestampedReports) { - this.timestampedReports = timestampedReports; - } - - public File getHistoryOutputFile() { - return this.historyOutputFile; - } - - public File getHistoryInputFile() { - return this.historyInputFile; - } - - public boolean isExportLineCoverage() { - return this.exportLineCoverage; - } - - protected RunDecision shouldRun() { - RunDecision decision = new RunDecision(); - - if (this.skip) { - decision.addReason("Execution of PIT should be skipped."); - } - - if (this.skipTests) { - decision.addReason("Test execution should be skipped (-DskipTests)."); - } - - if ("pom".equalsIgnoreCase(this.project.getPackaging())) { - decision.addReason("Packaging is POM."); - } - - if (!notEmptyProject.test(project)) { - decision.addReason("Project has no tests, it is empty."); - } - - return decision; - } - - public String getMutationEngine() { - return this.mutationEngine; - } - - public String getJavaExecutable() { - return this.jvm; - } - - public void setJavaExecutable(final String javaExecutable) { - this.jvm = javaExecutable; - } - - public List getAdditionalClasspathElements() { - return this.additionalClasspathElements; - } - - public List getClasspathDependencyExcludes() { - return this.classpathDependencyExcludes; - } - - public boolean isParseSurefireConfig() { - return this.parseSurefireConfig; - } - - public Map getPluginProperties() { - return pluginConfiguration; - } - - public Map getEnvironmentVariables() { - return environmentVariables; - } - - public boolean useHistory() { - return this.withHistory; - } - - public ArrayList getExcludedRunners() { - return excludedRunners; - } - - public ArrayList getFeatures() { - return features; - } - - public String getTestPlugin() { - return testPlugin; - } - - static class RunDecision { - private List reasons = new ArrayList<>(4); - - boolean shouldRun() { - return reasons.isEmpty(); - } - - public void addReason(String reason) { - reasons.add(reason); - } - - public List getReasons() { - return Collections.unmodifiableList(reasons); - } - } - -} +package org.pitest.maven; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; +import org.pitest.coverage.CoverageSummary; +import java.util.Optional; +import java.util.function.Predicate; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.statistics.MutationStatistics; +import org.pitest.mutationtest.tooling.CombinedStatistics; +import org.pitest.plugin.ClientClasspathPlugin; +import org.pitest.plugin.ToolClasspathPlugin; +import org.slf4j.bridge.SLF4JBridgeHandler; + +import uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J; + +public class AbstractPitMojo extends AbstractMojo { + + private final Predicate notEmptyProject; + + protected final Predicate filter; + + protected final PluginServices plugins; + + // Concrete List types declared for all fields to work around maven 2 bug + + /** + * Test plugin to use + */ + @Parameter(property = "testPlugin", defaultValue = "") + private String testPlugin; + + /** + * Classes to include in mutation test + */ + @Parameter(property = "targetClasses") + protected ArrayList targetClasses; + + /** + * Tests to run + */ + @Parameter(property = "targetTests") + protected ArrayList targetTests; + + /** + * Methods not to mutate + */ + @Parameter(property = "excludedMethods") + private ArrayList excludedMethods; + + /** + * Classes not to mutate + */ + @Parameter(property = "excludedClasses") + private ArrayList excludedClasses; + + /** + * Classes not to run tests from + */ + @Parameter(property = "excludedTestClasses") + private ArrayList excludedTestClasses; + + + /** + * Globs to be matched against method calls. No mutations will be created on + * the same line as a match. + */ + @Parameter(property = "avoidCallsTo") + private ArrayList avoidCallsTo; + + /** + * Base directory where all reports are written to. + */ + @Parameter(defaultValue = "${project.build.directory}/pit-reports", property = "reportsDirectory") + private File reportsDirectory; + + /** + * File to write history information to for incremental analysis + */ + @Parameter(property = "historyOutputFile") + private File historyOutputFile; + + /** + * File to read history from for incremental analysis (can be same as output + * file) + */ + @Parameter(property = "historyInputFile") + private File historyInputFile; + + /** + * Convenience flag to read and write history to a local temp file. + * + * Setting this flag is the equivalent to calling maven with -DhistoryInputFile=file -DhistoryOutputFile=file + * + * Where file is a file named [groupid][artifactid][version]_pitest_history.bin in the temp directory + * + */ + @Parameter(defaultValue = "false", property = "withHistory") + private boolean withHistory; + + /** + * Maximum distance to look from test to class. Relevant when mutating static + * initializers + * + */ + @Parameter(defaultValue = "-1", property = "maxDependencyDistance") + private int maxDependencyDistance; + + /** + * Number of threads to use + */ + @Parameter(defaultValue = "1", property = "threads") + private int threads; + + /** + * Mutate static initializers + */ + @Parameter(defaultValue = "false", property = "mutateStaticInitializers") + private boolean mutateStaticInitializers; + + /** + * Detect inlined code + */ + @Parameter(defaultValue = "true", property = "detectInlinedCode") + private boolean detectInlinedCode; + + /** + * Mutation operators to apply + */ + @Parameter(property = "mutators") + private ArrayList mutators; + + /** + * Mutation operators to apply + */ + @Parameter(property = "features") + private ArrayList features; + + + /** + * Weighting to allow for timeouts + */ + @Parameter(defaultValue = "1.25", property = "timeoutFactor") + private float timeoutFactor; + + /** + * Constant factor to allow for timeouts + */ + @Parameter(defaultValue = "3000", property = "timeoutConstant") + private long timeoutConstant; + + /** + * Maximum number of mutations to allow per class + */ + @Parameter(defaultValue = "-1", property = "maxMutationsPerClass") + private int maxMutationsPerClass; + + /** + * Arguments to pass to child processes + */ + @Parameter + private ArrayList jvmArgs; + + /** + * Formats to output during analysis phase + */ + @Parameter(property = "outputFormats") + private ArrayList outputFormats; + + /** + * Output verbose logging + */ + @Parameter(defaultValue = "false", property = "verbose") + private boolean verbose; + + /** + * Throw error if no mutations found + */ + @Parameter(defaultValue = "true", property = "failWhenNoMutations") + private boolean failWhenNoMutations; + + /** + * Create timestamped subdirectory for report + */ + @Parameter(defaultValue = "true", property = "timestampedReports") + private boolean timestampedReports; + + /** + * TestNG Groups/JUnit Categories to exclude + */ + @Parameter(property = "excludedGroups") + private ArrayList excludedGroups; + + /** + * TestNG Groups/JUnit Categories to include + */ + @Parameter(property = "includedGroups") + private ArrayList includedGroups; + + /** + * Test methods that should be included for challenging the mutants + */ + @Parameter(property = "includedTestMethods") + private ArrayList includedTestMethods; + /** + * Maximum number of mutations to include in a single analysis unit. + * + * If set to 1 will analyse very slowly, but with strong (jvm per mutant) + * isolation. + * + */ + @Parameter(property = "mutationUnitSize") + private int mutationUnitSize; + + /** + * Export line coverage data + */ + @Parameter(defaultValue = "false", property = "exportLineCoverage") + private boolean exportLineCoverage; + + /** + * Mutation score threshold at which to fail build + */ + @Parameter(defaultValue = "0", property = "mutationThreshold") + private int mutationThreshold; + + /** + * Maximum surviving mutants to allow + */ + @Parameter(defaultValue = "-1", property = "maxSurviving") + private int maxSurviving = -1; + + /** + * Line coverage threshold at which to fail build + */ + @Parameter(defaultValue = "0", property = "coverageThreshold") + private int coverageThreshold; + + /** + * Path to java executable to use when running tests. Will default to + * executable in JAVA_HOME if none set. + */ + @Parameter + private String jvm; + + /** + * Engine to use when generating mutations. + */ + @Parameter(defaultValue = "gregor", property = "mutationEngine") + private String mutationEngine; + + /** + * List of additional classpath entries to use when looking for tests and + * mutable code. These will be used in addition to the classpath with which + * PIT is launched. + */ + @Parameter(property = "additionalClasspathElements") + private ArrayList additionalClasspathElements; + + /** + * List of classpath entries, formatted as "groupId:artifactId", which should + * not be included in the classpath when running mutation tests. Modelled + * after the corresponding Surefire/Failsafe property. + */ + @Parameter(property = "classpathDependencyExcludes") + private ArrayList classpathDependencyExcludes; + + /** + * + */ + @Parameter(property = "excludedRunners") + private ArrayList excludedRunners; + + /** + * When set indicates that analysis of this project should be skipped + */ + @Parameter(defaultValue = "false") + private boolean skip; + + /** + * When set will try and create settings based on surefire configuration. This + * may not give the desired result in some circumstances + */ + @Parameter(defaultValue = "true") + private boolean parseSurefireConfig; + + /** + * honours common skipTests flag in a maven run + */ + @Parameter(defaultValue = "false") + private boolean skipTests; + + /** + * Use slf4j for logging + */ + @Parameter(defaultValue = "false", property = "useSlf4j") + private boolean useSlf4j; + + /** + * Configuration properties. + * + * Value pairs may be used by pitest plugins. + * + */ + @Parameter + private Map pluginConfiguration; + + /** + * environment configuration + * + * Value pairs may be used by pitest plugins. + */ + @Parameter + private Map environmentVariables = new HashMap<>(); + + /** + * Internal: Project to interact with. + * + */ + @Parameter(property = "project", readonly = true, required = true) + protected MavenProject project; + + /** + * Internal: Map of plugin artifacts. + */ + @Parameter(property = "plugin.artifactMap", readonly = true, required = true) + private Map pluginArtifactMap; + + protected final GoalStrategy goalStrategy; + + public AbstractPitMojo() { + this(new RunPitStrategy(), new DependencyFilter(new PluginServices( + AbstractPitMojo.class.getClassLoader())), new PluginServices( + AbstractPitMojo.class.getClassLoader()), new NonEmptyProjectCheck()); + } + + public AbstractPitMojo(final GoalStrategy strategy, final Predicate filter, + final PluginServices plugins, final Predicate emptyProjectCheck) { + this.goalStrategy = strategy; + this.filter = filter; + this.plugins = plugins; + this.notEmptyProject = emptyProjectCheck; + } + + @Override + public final void execute() throws MojoExecutionException, + MojoFailureException { + + switchLogging(); + RunDecision shouldRun = shouldRun(); + + if (shouldRun.shouldRun()) { + for (final ToolClasspathPlugin each : this.plugins + .findToolClasspathPlugins()) { + this.getLog().info("Found plugin : " + each.description()); + } + + for (final ClientClasspathPlugin each : this.plugins + .findClientClasspathPlugins()) { + this.getLog().info( + "Found shared classpath plugin : " + each.description()); + } + + final Optional result = analyse(); + if (result.isPresent()) { + throwErrorIfScoreBelowThreshold(result.get().getMutationStatistics()); + throwErrorIfMoreThanMaximumSurvivors(result.get().getMutationStatistics()); + throwErrorIfCoverageBelowThreshold(result.get().getCoverageSummary()); + } + + } else { + this.getLog().info("Skipping project because:"); + for (String reason : shouldRun.getReasons()) { + this.getLog().info(" - " + reason); + } + } + } + + private void switchLogging() { + if (this.useSlf4j) { + SLF4JBridgeHandler.removeHandlersForRootLogger(); + SLF4JBridgeHandler.install(); + Logger.getLogger("PIT").addHandler(new SLF4JBridgeHandler()); + SysOutOverSLF4J.sendSystemOutAndErrToSLF4J(); + } + } + + private void throwErrorIfCoverageBelowThreshold( + final CoverageSummary coverageSummary) throws MojoFailureException { + if ((this.coverageThreshold != 0) + && (coverageSummary.getCoverage() < this.coverageThreshold)) { + throw new MojoFailureException("Line coverage of " + + coverageSummary.getCoverage() + "(" + + coverageSummary.getNumberOfCoveredLines() + "/" + + coverageSummary.getNumberOfLines() + ") is below threshold of " + + this.coverageThreshold); + } + } + + private void throwErrorIfScoreBelowThreshold(final MutationStatistics result) + throws MojoFailureException { + if ((this.mutationThreshold != 0) + && (result.getPercentageDetected() < this.mutationThreshold)) { + throw new MojoFailureException("Mutation score of " + + result.getPercentageDetected() + " is below threshold of " + + this.mutationThreshold); + } + } + + private void throwErrorIfMoreThanMaximumSurvivors(final MutationStatistics result) + throws MojoFailureException { + if ((this.maxSurviving >= 0) + && (result.getTotalSurvivingMutations() > this.maxSurviving)) { + throw new MojoFailureException("Had " + + result.getTotalSurvivingMutations() + " surviving mutants, but only " + + this.maxSurviving + " survivors allowed"); + } + } + + protected Optional analyse() throws MojoExecutionException { + final ReportOptions data = new MojoToReportOptionsConverter(this, + new SurefireConfigConverter(), this.filter).convert(); + return Optional.ofNullable(this.goalStrategy.execute(detectBaseDir(), data, + this.plugins, this.environmentVariables)); + } + + protected File detectBaseDir() { + // execution project doesn't seem to always be available. + // possibily a maven 2 vs maven 3 issue? + final MavenProject executionProject = this.project.getExecutionProject(); + if (executionProject == null) { + return null; + } + return executionProject.getBasedir(); + } + + public List getTargetClasses() { + return this.targetClasses; + } + + public List getTargetTests() { + return this.targetTests; + } + + public List getExcludedMethods() { + return this.excludedMethods; + } + + public List getExcludedClasses() { + return this.excludedClasses; + } + + public List getAvoidCallsTo() { + return this.avoidCallsTo; + } + + public File getReportsDirectory() { + return this.reportsDirectory; + } + + public int getMaxDependencyDistance() { + return this.maxDependencyDistance; + } + + public int getThreads() { + return this.threads; + } + + public boolean isMutateStaticInitializers() { + return this.mutateStaticInitializers; + } + + public List getMutators() { + return this.mutators; + } + + public float getTimeoutFactor() { + return this.timeoutFactor; + } + + public long getTimeoutConstant() { + return this.timeoutConstant; + } + + public ArrayList getExcludedTestClasses() { + return excludedTestClasses; + } + + public int getMaxMutationsPerClass() { + return this.maxMutationsPerClass; + } + + public List getJvmArgs() { + return this.jvmArgs; + } + + public List getOutputFormats() { + return this.outputFormats; + } + + public boolean isVerbose() { + return this.verbose; + } + + public MavenProject getProject() { + return this.project; + } + + public Map getPluginArtifactMap() { + return this.pluginArtifactMap; + } + + public boolean isFailWhenNoMutations() { + return this.failWhenNoMutations; + } + + public List getExcludedGroups() { + return this.excludedGroups; + } + + public List getIncludedGroups() { + return this.includedGroups; + } + + public List getIncludedTestMethods() { + return this.includedTestMethods; + } + + public int getMutationUnitSize() { + return this.mutationUnitSize; + } + + public boolean isTimestampedReports() { + return this.timestampedReports; + } + + public boolean isDetectInlinedCode() { + return this.detectInlinedCode; + } + + public void setTimestampedReports(final boolean timestampedReports) { + this.timestampedReports = timestampedReports; + } + + public File getHistoryOutputFile() { + return this.historyOutputFile; + } + + public File getHistoryInputFile() { + return this.historyInputFile; + } + + public boolean isExportLineCoverage() { + return this.exportLineCoverage; + } + + protected RunDecision shouldRun() { + RunDecision decision = new RunDecision(); + + if (this.skip) { + decision.addReason("Execution of PIT should be skipped."); + } + + if (this.skipTests) { + decision.addReason("Test execution should be skipped (-DskipTests)."); + } + + if ("pom".equalsIgnoreCase(this.project.getPackaging())) { + decision.addReason("Packaging is POM."); + } + + if (!notEmptyProject.test(project)) { + decision.addReason("Project has no tests, it is empty."); + } + + return decision; + } + + public String getMutationEngine() { + return this.mutationEngine; + } + + public String getJavaExecutable() { + return this.jvm; + } + + public void setJavaExecutable(final String javaExecutable) { + this.jvm = javaExecutable; + } + + public List getAdditionalClasspathElements() { + return this.additionalClasspathElements; + } + + public List getClasspathDependencyExcludes() { + return this.classpathDependencyExcludes; + } + + public boolean isParseSurefireConfig() { + return this.parseSurefireConfig; + } + + public Map getPluginProperties() { + return pluginConfiguration; + } + + public Map getEnvironmentVariables() { + return environmentVariables; + } + + public boolean useHistory() { + return this.withHistory; + } + + public ArrayList getExcludedRunners() { + return excludedRunners; + } + + public ArrayList getFeatures() { + return features; + } + + public String getTestPlugin() { + return testPlugin; + } + + static class RunDecision { + private List reasons = new ArrayList<>(4); + + boolean shouldRun() { + return reasons.isEmpty(); + } + + public void addReason(String reason) { + reasons.add(reason); + } + + public List getReasons() { + return Collections.unmodifiableList(reasons); + } + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/DependencyFilter.java b/pitest-maven/src/main/java/org/pitest/maven/DependencyFilter.java index 407757520..4b759c663 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/DependencyFilter.java +++ b/pitest-maven/src/main/java/org/pitest/maven/DependencyFilter.java @@ -1,171 +1,171 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven; - -import java.io.IOException; -import java.net.URL; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; -import java.util.jar.Attributes; -import java.util.jar.Manifest; - -import org.apache.maven.artifact.Artifact; -import java.util.function.Function; -import org.pitest.functional.FCollection; -import java.util.function.Predicate; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.plugin.ClientClasspathPlugin; -import org.pitest.util.Log; -import org.pitest.util.PitError; -import org.pitest.util.StringUtil; - -public class DependencyFilter implements Predicate { - - private final Set groups = new HashSet<>(); - - public DependencyFilter(PluginServices plugins) { - final Iterable runtimePlugins = plugins - .findClientClasspathPlugins(); - FCollection.mapTo(runtimePlugins, artifactToPair(), this.groups); - findVendorIdForGroups(); - } - - private static Function artifactToPair() { - return new Function() { - - @Override - public GroupIdPair apply(final ClientClasspathPlugin a) { - final Package p = a.getClass().getPackage(); - - final GroupIdPair g = new GroupIdPair(p.getImplementationVendor(), - p.getImplementationTitle()); - - if (g.id == null) { - reportBadPlugin("title", a); - } - - if (g.group == null) { - reportBadPlugin("vendor", a); - } - - return g; - - } - - private void reportBadPlugin(final String missingProperty, - final ClientClasspathPlugin a) { - final Class clss = a.getClass(); - throw new PitError("No implementation " + missingProperty - + " in manifest of plugin jar for " + clss + " in " - + clss.getProtectionDomain().getCodeSource().getLocation()); - } - - }; - } - - /** - * Changes the (Implementation-Vendor,Implementation-Title) pairs - * by the corresponding (Implementation-Vendor-Id, Implementation-Title) pair - * when the Implementation-Vendor-Id is available. - * Targets the fact that, by default, project.groupId is assigned to Implementation-Vendor-Id - * and project.organization.name is assigned to Implementation-Vendor on the META-INF/MANIFEST.MF file. - */ - private void findVendorIdForGroups() { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - try { - //Checks every META-INF/MANIFEST.MF file found in the classpath - Enumeration urls = loader.getResources("META-INF/MANIFEST.MF"); - while (urls.hasMoreElements()) { - URL url = urls.nextElement(); - - Manifest manifest = new Manifest(url.openStream()); - Attributes attributes = manifest.getMainAttributes(); - String vendor = attributes.getValue("Implementation-Vendor"); - String vendorId = attributes.getValue("Implementation-Vendor-Id"); - String id = attributes.getValue("Implementation-Title"); - - if (StringUtil.isNullOrEmpty(vendor) || StringUtil.isNullOrEmpty(vendorId) || StringUtil.isNullOrEmpty(id)) { - continue; - } - - GroupIdPair query = new GroupIdPair(vendor, id); - if (groups.contains(query)) { - groups.remove(query); - groups.add(new GroupIdPair(vendorId, id)); - } - } - } catch (IOException exc) { - Log.getLogger().fine("An exception was thrown while looking for manifest files. Message: " + exc.getMessage()); - } - } - - @Override - public boolean test(final Artifact a) { - final GroupIdPair p = new GroupIdPair(a.getGroupId(), a.getArtifactId()); - return this.groups.contains(p); - } - - private static class GroupIdPair { - private final String group; - private final String id; - - GroupIdPair(final String group, final String id) { - this.group = group; - this.id = id; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.group == null) ? 0 : this.group.hashCode()); - result = (prime * result) + ((this.id == null) ? 0 : this.id.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final GroupIdPair other = (GroupIdPair) obj; - if (this.group == null) { - if (other.group != null) { - return false; - } - } else if (!this.group.equals(other.group)) { - return false; - } - if (this.id == null) { - if (other.id != null) { - return false; - } - } else if (!this.id.equals(other.id)) { - return false; - } - return true; - } - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven; + +import java.io.IOException; +import java.net.URL; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import org.apache.maven.artifact.Artifact; +import java.util.function.Function; +import org.pitest.functional.FCollection; +import java.util.function.Predicate; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.plugin.ClientClasspathPlugin; +import org.pitest.util.Log; +import org.pitest.util.PitError; +import org.pitest.util.StringUtil; + +public class DependencyFilter implements Predicate { + + private final Set groups = new HashSet<>(); + + public DependencyFilter(PluginServices plugins) { + final Iterable runtimePlugins = plugins + .findClientClasspathPlugins(); + FCollection.mapTo(runtimePlugins, artifactToPair(), this.groups); + findVendorIdForGroups(); + } + + private static Function artifactToPair() { + return new Function() { + + @Override + public GroupIdPair apply(final ClientClasspathPlugin a) { + final Package p = a.getClass().getPackage(); + + final GroupIdPair g = new GroupIdPair(p.getImplementationVendor(), + p.getImplementationTitle()); + + if (g.id == null) { + reportBadPlugin("title", a); + } + + if (g.group == null) { + reportBadPlugin("vendor", a); + } + + return g; + + } + + private void reportBadPlugin(final String missingProperty, + final ClientClasspathPlugin a) { + final Class clss = a.getClass(); + throw new PitError("No implementation " + missingProperty + + " in manifest of plugin jar for " + clss + " in " + + clss.getProtectionDomain().getCodeSource().getLocation()); + } + + }; + } + + /** + * Changes the (Implementation-Vendor,Implementation-Title) pairs + * by the corresponding (Implementation-Vendor-Id, Implementation-Title) pair + * when the Implementation-Vendor-Id is available. + * Targets the fact that, by default, project.groupId is assigned to Implementation-Vendor-Id + * and project.organization.name is assigned to Implementation-Vendor on the META-INF/MANIFEST.MF file. + */ + private void findVendorIdForGroups() { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + try { + //Checks every META-INF/MANIFEST.MF file found in the classpath + Enumeration urls = loader.getResources("META-INF/MANIFEST.MF"); + while (urls.hasMoreElements()) { + URL url = urls.nextElement(); + + Manifest manifest = new Manifest(url.openStream()); + Attributes attributes = manifest.getMainAttributes(); + String vendor = attributes.getValue("Implementation-Vendor"); + String vendorId = attributes.getValue("Implementation-Vendor-Id"); + String id = attributes.getValue("Implementation-Title"); + + if (StringUtil.isNullOrEmpty(vendor) || StringUtil.isNullOrEmpty(vendorId) || StringUtil.isNullOrEmpty(id)) { + continue; + } + + GroupIdPair query = new GroupIdPair(vendor, id); + if (groups.contains(query)) { + groups.remove(query); + groups.add(new GroupIdPair(vendorId, id)); + } + } + } catch (IOException exc) { + Log.getLogger().fine("An exception was thrown while looking for manifest files. Message: " + exc.getMessage()); + } + } + + @Override + public boolean test(final Artifact a) { + final GroupIdPair p = new GroupIdPair(a.getGroupId(), a.getArtifactId()); + return this.groups.contains(p); + } + + private static class GroupIdPair { + private final String group; + private final String id; + + GroupIdPair(final String group, final String id) { + this.group = group; + this.id = id; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.group == null) ? 0 : this.group.hashCode()); + result = (prime * result) + ((this.id == null) ? 0 : this.id.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final GroupIdPair other = (GroupIdPair) obj; + if (this.group == null) { + if (other.group != null) { + return false; + } + } else if (!this.group.equals(other.group)) { + return false; + } + if (this.id == null) { + if (other.id != null) { + return false; + } + } else if (!this.id.equals(other.id)) { + return false; + } + return true; + } + + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/GoalStrategy.java b/pitest-maven/src/main/java/org/pitest/maven/GoalStrategy.java index 5cab06d8d..86df5c51d 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/GoalStrategy.java +++ b/pitest-maven/src/main/java/org/pitest/maven/GoalStrategy.java @@ -1,30 +1,30 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven; - -import java.io.File; -import java.util.Map; - -import org.apache.maven.plugin.MojoExecutionException; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.tooling.CombinedStatistics; - -public interface GoalStrategy { - - CombinedStatistics execute(File baseDir, ReportOptions options, - PluginServices plugins, Map environmentVariables) - throws MojoExecutionException; -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven; + +import java.io.File; +import java.util.Map; + +import org.apache.maven.plugin.MojoExecutionException; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.tooling.CombinedStatistics; + +public interface GoalStrategy { + + CombinedStatistics execute(File baseDir, ReportOptions options, + PluginServices plugins, Map environmentVariables) + throws MojoExecutionException; +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/MojoToReportOptionsConverter.java b/pitest-maven/src/main/java/org/pitest/maven/MojoToReportOptionsConverter.java index 278a608f1..de8322098 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/MojoToReportOptionsConverter.java +++ b/pitest-maven/src/main/java/org/pitest/maven/MojoToReportOptionsConverter.java @@ -1,329 +1,329 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.model.Plugin; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.DirectoryClassPathRoot; -import java.util.function.Function; -import org.pitest.functional.FCollection; -import java.util.function.Predicate; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.util.Glob; - -public class MojoToReportOptionsConverter { - - private final AbstractPitMojo mojo; - private final Predicate dependencyFilter; - private final Log log; - private final SurefireConfigConverter surefireConverter; - - public MojoToReportOptionsConverter(final AbstractPitMojo mojo, - SurefireConfigConverter surefireConverter, - Predicate dependencyFilter) { - this.mojo = mojo; - this.dependencyFilter = dependencyFilter; - this.log = mojo.getLog(); - this.surefireConverter = surefireConverter; - } - - public ReportOptions convert() { - - final List classPath = new ArrayList<>(); - - try { - classPath.addAll(this.mojo.getProject().getTestClasspathElements()); - } catch (final DependencyResolutionRequiredException e1) { - this.log.info(e1); - } - - addOwnDependenciesToClassPath(classPath); - - classPath.addAll(this.mojo.getAdditionalClasspathElements()); - - for (Object artifact : this.mojo.getProject().getArtifacts()) { - final Artifact dependency = (Artifact) artifact; - - if (this.mojo.getClasspathDependencyExcludes().contains( - dependency.getGroupId() + ":" + dependency.getArtifactId())) { - classPath.remove(dependency.getFile().getPath()); - } - } - - ReportOptions option = parseReportOptions(classPath); - return updateFromSurefire(option); - - } - - private ReportOptions parseReportOptions(final List classPath) { - final ReportOptions data = new ReportOptions(); - - if (this.mojo.getProject().getBuild() != null) { - this.log.info("Mutating from " - + this.mojo.getProject().getBuild().getOutputDirectory()); - data.setCodePaths(Collections.singleton(this.mojo.getProject().getBuild() - .getOutputDirectory())); - } - - data.setTestPlugin(this.mojo.getTestPlugin()); - data.setClassPathElements(classPath); - data.setDependencyAnalysisMaxDistance(this.mojo.getMaxDependencyDistance()); - data.setFailWhenNoMutations(shouldFailWhenNoMutations()); - - data.setTargetClasses(determineTargetClasses()); - data.setTargetTests(determineTargetTests()); - - data.setExcludedMethods(this.mojo - .getExcludedMethods()); - data.setExcludedClasses(this.mojo.getExcludedClasses()); - data.setExcludedTestClasses(globStringsToPredicates(this.mojo - .getExcludedTestClasses())); - data.setNumberOfThreads(this.mojo.getThreads()); - data.setExcludedRunners(this.mojo.getExcludedRunners()); - - data.setReportDir(this.mojo.getReportsDirectory().getAbsolutePath()); - data.setVerbose(this.mojo.isVerbose()); - if (this.mojo.getJvmArgs() != null) { - data.addChildJVMArgs(this.mojo.getJvmArgs()); - } - - data.setMutators(determineMutators()); - data.setFeatures(determineFeatures()); - data.setTimeoutConstant(this.mojo.getTimeoutConstant()); - data.setTimeoutFactor(this.mojo.getTimeoutFactor()); - if (hasValue(this.mojo.getAvoidCallsTo())) { - data.setLoggingClasses(this.mojo.getAvoidCallsTo()); - } - - final List sourceRoots = new ArrayList<>(); - sourceRoots.addAll(this.mojo.getProject().getCompileSourceRoots()); - sourceRoots.addAll(this.mojo.getProject().getTestCompileSourceRoots()); - - data.setSourceDirs(stringsTofiles(sourceRoots)); - - data.addOutputFormats(determineOutputFormats()); - - setTestGroups(data); - - data.setMutationUnitSize(this.mojo.getMutationUnitSize()); - data.setShouldCreateTimestampedReports(this.mojo.isTimestampedReports()); - data.setDetectInlinedCode(this.mojo.isDetectInlinedCode()); - - determineHistory(data); - - data.setExportLineCoverage(this.mojo.isExportLineCoverage()); - data.setMutationEngine(this.mojo.getMutationEngine()); - data.setJavaExecutable(this.mojo.getJavaExecutable()); - data.setFreeFormProperties(createPluginProperties()); - data.setIncludedTestMethods(this.mojo.getIncludedTestMethods()); - - return data; - } - - - private void determineHistory(final ReportOptions data) { - if (this.mojo.useHistory()) { - useHistoryFileInTempDir(data); - } else { - data.setHistoryInputLocation(this.mojo.getHistoryInputFile()); - data.setHistoryOutputLocation(this.mojo.getHistoryOutputFile()); - } - } - - private void useHistoryFileInTempDir(final ReportOptions data) { - String tempDir = System.getProperty("java.io.tmpdir"); - MavenProject project = this.mojo.project; - String name = project.getGroupId() + "." - + project.getArtifactId() + "." - + project.getVersion() + "_pitest_history.bin"; - File historyFile = new File(tempDir, name); - log.info("Will read and write history at " + historyFile); - if (this.mojo.getHistoryInputFile() == null) { - data.setHistoryInputLocation(historyFile); - } - if (this.mojo.getHistoryOutputFile() == null) { - data.setHistoryOutputLocation(historyFile); - } - } - - private ReportOptions updateFromSurefire(ReportOptions option) { - Collection plugins = lookupPlugin("org.apache.maven.plugins:maven-surefire-plugin"); - if (!this.mojo.isParseSurefireConfig()) { - return option; - } else if (plugins.isEmpty()) { - this.log.warn("Could not find surefire configuration in pom"); - return option; - } - - Plugin surefire = plugins.iterator().next(); - if (surefire != null) { - return this.surefireConverter.update(option, - (Xpp3Dom) surefire.getConfiguration()); - } else { - return option; - } - - } - - private Collection lookupPlugin(String key) { - List plugins = this.mojo.getProject().getBuildPlugins(); - return FCollection.filter(plugins, hasKey(key)); - } - - private static Predicate hasKey(final String key) { - return new Predicate() { - @Override - public boolean test(Plugin a) { - return a.getKey().equals(key); - } - }; - } - - private boolean shouldFailWhenNoMutations() { - return this.mojo.isFailWhenNoMutations(); - } - - private void setTestGroups(final ReportOptions data) { - final TestGroupConfig conf = new TestGroupConfig( - this.mojo.getExcludedGroups(), this.mojo.getIncludedGroups()); - data.setGroupConfig(conf); - } - - private void addOwnDependenciesToClassPath(final List classPath) { - for (final Artifact dependency : filteredDependencies()) { - this.log.info("Adding " + dependency.getGroupId() + ":" - + dependency.getArtifactId() + " to SUT classpath"); - classPath.add(dependency.getFile().getAbsolutePath()); - } - } - - private Collection> globStringsToPredicates( - final List excludedMethods) { - return FCollection.map(excludedMethods, Glob.toGlobPredicate()); - } - - private Collection> determineTargetTests() { - return FCollection.map(this.mojo.getTargetTests(), Glob.toGlobPredicate()); - } - - private Collection filteredDependencies() { - return FCollection.filter(this.mojo.getPluginArtifactMap().values(), - this.dependencyFilter); - } - - private Collection determineMutators() { - if (this.mojo.getMutators() != null) { - return this.mojo.getMutators(); - } else { - return Collections.emptyList(); - } - } - - private Collection determineFeatures() { - if (this.mojo.getFeatures() != null) { - return this.mojo.getFeatures(); - } else { - return Collections.emptyList(); - } - } - - private Collection determineTargetClasses() { - return useConfiguredTargetClassesOrFindOccupiedPackages(this.mojo.getTargetClasses()); - } - - private Collection useConfiguredTargetClassesOrFindOccupiedPackages( - final Collection filters) { - if (!hasValue(filters)) { - this.mojo.getLog().info("Defaulting target classes to match packages in build directory"); - return findOccupiedPackages(); - } else { - return filters; - } - } - - - private Collection findOccupiedPackages() { - String outputDirName = this.mojo.getProject().getBuild() - .getOutputDirectory(); - File outputDir = new File(outputDirName); - if (outputDir.exists()) { - DirectoryClassPathRoot root = new DirectoryClassPathRoot(outputDir); - Set occupiedPackages = new HashSet<>(); - FCollection.mapTo(root.classNames(), classToPackageGlob(), - occupiedPackages); - return occupiedPackages; - } - return Collections.emptyList(); - } - - private static Function classToPackageGlob() { - return new Function() { - @Override - public String apply(String a) { - return ClassName.fromString(a).getPackage().asJavaName() + ".*"; - } - }; - } - - private Collection stringsTofiles(final List sourceRoots) { - return FCollection.map(sourceRoots, stringToFile()); - } - - private Function stringToFile() { - return new Function() { - @Override - public File apply(final String a) { - return new File(a); - } - }; - } - - private Collection determineOutputFormats() { - if (hasValue(this.mojo.getOutputFormats())) { - return this.mojo.getOutputFormats(); - } else { - return Arrays.asList("HTML"); - } - } - - private boolean hasValue(final Collection collection) { - return (collection != null) && !collection.isEmpty(); - } - - private Properties createPluginProperties() { - Properties p = new Properties(); - if (this.mojo.getPluginProperties() != null) { - p.putAll(this.mojo.getPluginProperties()); - } - return p; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DependencyResolutionRequiredException; +import org.apache.maven.model.Plugin; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.DirectoryClassPathRoot; +import java.util.function.Function; +import org.pitest.functional.FCollection; +import java.util.function.Predicate; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.util.Glob; + +public class MojoToReportOptionsConverter { + + private final AbstractPitMojo mojo; + private final Predicate dependencyFilter; + private final Log log; + private final SurefireConfigConverter surefireConverter; + + public MojoToReportOptionsConverter(final AbstractPitMojo mojo, + SurefireConfigConverter surefireConverter, + Predicate dependencyFilter) { + this.mojo = mojo; + this.dependencyFilter = dependencyFilter; + this.log = mojo.getLog(); + this.surefireConverter = surefireConverter; + } + + public ReportOptions convert() { + + final List classPath = new ArrayList<>(); + + try { + classPath.addAll(this.mojo.getProject().getTestClasspathElements()); + } catch (final DependencyResolutionRequiredException e1) { + this.log.info(e1); + } + + addOwnDependenciesToClassPath(classPath); + + classPath.addAll(this.mojo.getAdditionalClasspathElements()); + + for (Object artifact : this.mojo.getProject().getArtifacts()) { + final Artifact dependency = (Artifact) artifact; + + if (this.mojo.getClasspathDependencyExcludes().contains( + dependency.getGroupId() + ":" + dependency.getArtifactId())) { + classPath.remove(dependency.getFile().getPath()); + } + } + + ReportOptions option = parseReportOptions(classPath); + return updateFromSurefire(option); + + } + + private ReportOptions parseReportOptions(final List classPath) { + final ReportOptions data = new ReportOptions(); + + if (this.mojo.getProject().getBuild() != null) { + this.log.info("Mutating from " + + this.mojo.getProject().getBuild().getOutputDirectory()); + data.setCodePaths(Collections.singleton(this.mojo.getProject().getBuild() + .getOutputDirectory())); + } + + data.setTestPlugin(this.mojo.getTestPlugin()); + data.setClassPathElements(classPath); + data.setDependencyAnalysisMaxDistance(this.mojo.getMaxDependencyDistance()); + data.setFailWhenNoMutations(shouldFailWhenNoMutations()); + + data.setTargetClasses(determineTargetClasses()); + data.setTargetTests(determineTargetTests()); + + data.setExcludedMethods(this.mojo + .getExcludedMethods()); + data.setExcludedClasses(this.mojo.getExcludedClasses()); + data.setExcludedTestClasses(globStringsToPredicates(this.mojo + .getExcludedTestClasses())); + data.setNumberOfThreads(this.mojo.getThreads()); + data.setExcludedRunners(this.mojo.getExcludedRunners()); + + data.setReportDir(this.mojo.getReportsDirectory().getAbsolutePath()); + data.setVerbose(this.mojo.isVerbose()); + if (this.mojo.getJvmArgs() != null) { + data.addChildJVMArgs(this.mojo.getJvmArgs()); + } + + data.setMutators(determineMutators()); + data.setFeatures(determineFeatures()); + data.setTimeoutConstant(this.mojo.getTimeoutConstant()); + data.setTimeoutFactor(this.mojo.getTimeoutFactor()); + if (hasValue(this.mojo.getAvoidCallsTo())) { + data.setLoggingClasses(this.mojo.getAvoidCallsTo()); + } + + final List sourceRoots = new ArrayList<>(); + sourceRoots.addAll(this.mojo.getProject().getCompileSourceRoots()); + sourceRoots.addAll(this.mojo.getProject().getTestCompileSourceRoots()); + + data.setSourceDirs(stringsTofiles(sourceRoots)); + + data.addOutputFormats(determineOutputFormats()); + + setTestGroups(data); + + data.setMutationUnitSize(this.mojo.getMutationUnitSize()); + data.setShouldCreateTimestampedReports(this.mojo.isTimestampedReports()); + data.setDetectInlinedCode(this.mojo.isDetectInlinedCode()); + + determineHistory(data); + + data.setExportLineCoverage(this.mojo.isExportLineCoverage()); + data.setMutationEngine(this.mojo.getMutationEngine()); + data.setJavaExecutable(this.mojo.getJavaExecutable()); + data.setFreeFormProperties(createPluginProperties()); + data.setIncludedTestMethods(this.mojo.getIncludedTestMethods()); + + return data; + } + + + private void determineHistory(final ReportOptions data) { + if (this.mojo.useHistory()) { + useHistoryFileInTempDir(data); + } else { + data.setHistoryInputLocation(this.mojo.getHistoryInputFile()); + data.setHistoryOutputLocation(this.mojo.getHistoryOutputFile()); + } + } + + private void useHistoryFileInTempDir(final ReportOptions data) { + String tempDir = System.getProperty("java.io.tmpdir"); + MavenProject project = this.mojo.project; + String name = project.getGroupId() + "." + + project.getArtifactId() + "." + + project.getVersion() + "_pitest_history.bin"; + File historyFile = new File(tempDir, name); + log.info("Will read and write history at " + historyFile); + if (this.mojo.getHistoryInputFile() == null) { + data.setHistoryInputLocation(historyFile); + } + if (this.mojo.getHistoryOutputFile() == null) { + data.setHistoryOutputLocation(historyFile); + } + } + + private ReportOptions updateFromSurefire(ReportOptions option) { + Collection plugins = lookupPlugin("org.apache.maven.plugins:maven-surefire-plugin"); + if (!this.mojo.isParseSurefireConfig()) { + return option; + } else if (plugins.isEmpty()) { + this.log.warn("Could not find surefire configuration in pom"); + return option; + } + + Plugin surefire = plugins.iterator().next(); + if (surefire != null) { + return this.surefireConverter.update(option, + (Xpp3Dom) surefire.getConfiguration()); + } else { + return option; + } + + } + + private Collection lookupPlugin(String key) { + List plugins = this.mojo.getProject().getBuildPlugins(); + return FCollection.filter(plugins, hasKey(key)); + } + + private static Predicate hasKey(final String key) { + return new Predicate() { + @Override + public boolean test(Plugin a) { + return a.getKey().equals(key); + } + }; + } + + private boolean shouldFailWhenNoMutations() { + return this.mojo.isFailWhenNoMutations(); + } + + private void setTestGroups(final ReportOptions data) { + final TestGroupConfig conf = new TestGroupConfig( + this.mojo.getExcludedGroups(), this.mojo.getIncludedGroups()); + data.setGroupConfig(conf); + } + + private void addOwnDependenciesToClassPath(final List classPath) { + for (final Artifact dependency : filteredDependencies()) { + this.log.info("Adding " + dependency.getGroupId() + ":" + + dependency.getArtifactId() + " to SUT classpath"); + classPath.add(dependency.getFile().getAbsolutePath()); + } + } + + private Collection> globStringsToPredicates( + final List excludedMethods) { + return FCollection.map(excludedMethods, Glob.toGlobPredicate()); + } + + private Collection> determineTargetTests() { + return FCollection.map(this.mojo.getTargetTests(), Glob.toGlobPredicate()); + } + + private Collection filteredDependencies() { + return FCollection.filter(this.mojo.getPluginArtifactMap().values(), + this.dependencyFilter); + } + + private Collection determineMutators() { + if (this.mojo.getMutators() != null) { + return this.mojo.getMutators(); + } else { + return Collections.emptyList(); + } + } + + private Collection determineFeatures() { + if (this.mojo.getFeatures() != null) { + return this.mojo.getFeatures(); + } else { + return Collections.emptyList(); + } + } + + private Collection determineTargetClasses() { + return useConfiguredTargetClassesOrFindOccupiedPackages(this.mojo.getTargetClasses()); + } + + private Collection useConfiguredTargetClassesOrFindOccupiedPackages( + final Collection filters) { + if (!hasValue(filters)) { + this.mojo.getLog().info("Defaulting target classes to match packages in build directory"); + return findOccupiedPackages(); + } else { + return filters; + } + } + + + private Collection findOccupiedPackages() { + String outputDirName = this.mojo.getProject().getBuild() + .getOutputDirectory(); + File outputDir = new File(outputDirName); + if (outputDir.exists()) { + DirectoryClassPathRoot root = new DirectoryClassPathRoot(outputDir); + Set occupiedPackages = new HashSet<>(); + FCollection.mapTo(root.classNames(), classToPackageGlob(), + occupiedPackages); + return occupiedPackages; + } + return Collections.emptyList(); + } + + private static Function classToPackageGlob() { + return new Function() { + @Override + public String apply(String a) { + return ClassName.fromString(a).getPackage().asJavaName() + ".*"; + } + }; + } + + private Collection stringsTofiles(final List sourceRoots) { + return FCollection.map(sourceRoots, stringToFile()); + } + + private Function stringToFile() { + return new Function() { + @Override + public File apply(final String a) { + return new File(a); + } + }; + } + + private Collection determineOutputFormats() { + if (hasValue(this.mojo.getOutputFormats())) { + return this.mojo.getOutputFormats(); + } else { + return Arrays.asList("HTML"); + } + } + + private boolean hasValue(final Collection collection) { + return (collection != null) && !collection.isEmpty(); + } + + private Properties createPluginProperties() { + Properties p = new Properties(); + if (this.mojo.getPluginProperties() != null) { + p.putAll(this.mojo.getPluginProperties()); + } + return p; + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/NonEmptyProjectCheck.java b/pitest-maven/src/main/java/org/pitest/maven/NonEmptyProjectCheck.java index 16596db6e..6904d28f3 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/NonEmptyProjectCheck.java +++ b/pitest-maven/src/main/java/org/pitest/maven/NonEmptyProjectCheck.java @@ -1,27 +1,27 @@ -package org.pitest.maven; - -import java.io.File; - -import org.apache.maven.project.MavenProject; -import org.pitest.functional.FCollection; -import java.util.function.Predicate; - -public class NonEmptyProjectCheck implements Predicate { - - @SuppressWarnings("unchecked") - @Override - public boolean test(MavenProject project) { - return FCollection.contains(project.getTestCompileSourceRoots(), exists()) - && FCollection.contains(project.getCompileSourceRoots(), exists()); - } - - private Predicate exists() { - return new Predicate() { - @Override - public boolean test(String root) { - return new File(root).exists(); - } - }; - } - -} +package org.pitest.maven; + +import java.io.File; + +import org.apache.maven.project.MavenProject; +import org.pitest.functional.FCollection; +import java.util.function.Predicate; + +public class NonEmptyProjectCheck implements Predicate { + + @SuppressWarnings("unchecked") + @Override + public boolean test(MavenProject project) { + return FCollection.contains(project.getTestCompileSourceRoots(), exists()) + && FCollection.contains(project.getCompileSourceRoots(), exists()); + } + + private Predicate exists() { + return new Predicate() { + @Override + public boolean test(String root) { + return new File(root).exists(); + } + }; + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/PathToJavaClassConverter.java b/pitest-maven/src/main/java/org/pitest/maven/PathToJavaClassConverter.java index f6d62f551..632b75e3e 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/PathToJavaClassConverter.java +++ b/pitest-maven/src/main/java/org/pitest/maven/PathToJavaClassConverter.java @@ -1,56 +1,56 @@ -package org.pitest.maven; - -import java.io.File; -import java.util.Collections; - -import java.util.function.Function; - -/** - * Converts paths to java class names globs if they are within the supplied - * source root. Globs include wildcards to catch any inner classes. - * - * This conversion will not pick up non public, non inner classes defined in a - * source file not matching the class name. To cover this corner case would need - * to instead scan the byte code on the classpath and see if it had been tagged - * with the supplied filenames. - * - */ -class PathToJavaClassConverter implements Function> { - - private final String sourceRoot; - - PathToJavaClassConverter(final String sourceRoot) { - this.sourceRoot = sourceRoot; - } - - @Override - public Iterable apply(final String a) { - final File f = new File(a); - final String modifiedFilePath = f.getAbsolutePath(); - final String fileName = f.getName(); - - if (modifiedFilePath.startsWith(this.sourceRoot) - && (fileName.indexOf('.') != -1)) { - return createClassGlobFromFilePath(this.sourceRoot, modifiedFilePath); - } - return Collections.emptyList(); - - } - - private Iterable createClassGlobFromFilePath(final String sourceRoot, - final String modifiedFilePath) { - final String rootedPath = modifiedFilePath.substring( - sourceRoot.length() + 1, modifiedFilePath.length()); - // some scms report paths in portable format, some in os specific format (i - // think) - // replace both possibilities regardless of host os - return Collections.singleton(stripFileExtension(rootedPath).replace('/', - '.').replace('\\', '.') - + "*"); - } - - private String stripFileExtension(final String rootedPath) { - return rootedPath.substring(0, rootedPath.lastIndexOf(".")); - } - -} +package org.pitest.maven; + +import java.io.File; +import java.util.Collections; + +import java.util.function.Function; + +/** + * Converts paths to java class names globs if they are within the supplied + * source root. Globs include wildcards to catch any inner classes. + * + * This conversion will not pick up non public, non inner classes defined in a + * source file not matching the class name. To cover this corner case would need + * to instead scan the byte code on the classpath and see if it had been tagged + * with the supplied filenames. + * + */ +class PathToJavaClassConverter implements Function> { + + private final String sourceRoot; + + PathToJavaClassConverter(final String sourceRoot) { + this.sourceRoot = sourceRoot; + } + + @Override + public Iterable apply(final String a) { + final File f = new File(a); + final String modifiedFilePath = f.getAbsolutePath(); + final String fileName = f.getName(); + + if (modifiedFilePath.startsWith(this.sourceRoot) + && (fileName.indexOf('.') != -1)) { + return createClassGlobFromFilePath(this.sourceRoot, modifiedFilePath); + } + return Collections.emptyList(); + + } + + private Iterable createClassGlobFromFilePath(final String sourceRoot, + final String modifiedFilePath) { + final String rootedPath = modifiedFilePath.substring( + sourceRoot.length() + 1, modifiedFilePath.length()); + // some scms report paths in portable format, some in os specific format (i + // think) + // replace both possibilities regardless of host os + return Collections.singleton(stripFileExtension(rootedPath).replace('/', + '.').replace('\\', '.') + + "*"); + } + + private String stripFileExtension(final String rootedPath) { + return rootedPath.substring(0, rootedPath.lastIndexOf(".")); + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/PitMojo.java b/pitest-maven/src/main/java/org/pitest/maven/PitMojo.java index 47438cb75..3722cbb0a 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/PitMojo.java +++ b/pitest-maven/src/main/java/org/pitest/maven/PitMojo.java @@ -1,16 +1,16 @@ -package org.pitest.maven; - -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.ResolutionScope; - -/** - * Goal which runs a coverage mutation report - */ -@Mojo(name = "mutationCoverage", - defaultPhase = LifecyclePhase.VERIFY, - requiresDependencyResolution = ResolutionScope.TEST, - threadSafe = true) -public class PitMojo extends AbstractPitMojo { - -} +package org.pitest.maven; + +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.ResolutionScope; + +/** + * Goal which runs a coverage mutation report + */ +@Mojo(name = "mutationCoverage", + defaultPhase = LifecyclePhase.VERIFY, + requiresDependencyResolution = ResolutionScope.TEST, + threadSafe = true) +public class PitMojo extends AbstractPitMojo { + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/RunPitStrategy.java b/pitest-maven/src/main/java/org/pitest/maven/RunPitStrategy.java index bddadb133..93d9fd6b9 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/RunPitStrategy.java +++ b/pitest-maven/src/main/java/org/pitest/maven/RunPitStrategy.java @@ -1,43 +1,43 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven; - -import java.io.File; -import java.util.Map; - -import org.apache.maven.plugin.MojoExecutionException; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.tooling.AnalysisResult; -import org.pitest.mutationtest.tooling.CombinedStatistics; -import org.pitest.mutationtest.tooling.EntryPoint; - -public class RunPitStrategy implements GoalStrategy { - - @Override - public CombinedStatistics execute(File baseDir, ReportOptions data, - PluginServices plugins, Map environmentVariables) - throws MojoExecutionException { - - EntryPoint e = new EntryPoint(); - AnalysisResult result = e.execute(baseDir, data, plugins, - environmentVariables); - if (result.getError().isPresent()) { - throw new MojoExecutionException("fail", result.getError().get()); - } - return result.getStatistics().get(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven; + +import java.io.File; +import java.util.Map; + +import org.apache.maven.plugin.MojoExecutionException; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.tooling.AnalysisResult; +import org.pitest.mutationtest.tooling.CombinedStatistics; +import org.pitest.mutationtest.tooling.EntryPoint; + +public class RunPitStrategy implements GoalStrategy { + + @Override + public CombinedStatistics execute(File baseDir, ReportOptions data, + PluginServices plugins, Map environmentVariables) + throws MojoExecutionException { + + EntryPoint e = new EntryPoint(); + AnalysisResult result = e.execute(baseDir, data, plugins, + environmentVariables); + if (result.getError().isPresent()) { + throw new MojoExecutionException("fail", result.getError().get()); + } + return result.getStatistics().get(); + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/ScmMojo.java b/pitest-maven/src/main/java/org/pitest/maven/ScmMojo.java index ff0a8887f..c3320ed08 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/ScmMojo.java +++ b/pitest-maven/src/main/java/org/pitest/maven/ScmMojo.java @@ -1,306 +1,306 @@ -package org.pitest.maven; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.project.MavenProject; -import org.apache.maven.scm.ChangeFile; -import org.apache.maven.scm.ChangeSet; -import org.apache.maven.scm.ScmBranch; -import org.apache.maven.scm.ScmException; -import org.apache.maven.scm.ScmFile; -import org.apache.maven.scm.ScmFileSet; -import org.apache.maven.scm.ScmFileStatus; -import org.apache.maven.scm.command.changelog.ChangeLogScmRequest; -import org.apache.maven.scm.command.changelog.ChangeLogScmResult; -import org.apache.maven.scm.command.status.StatusScmResult; -import org.apache.maven.scm.manager.ScmManager; -import org.apache.maven.scm.repository.ScmRepository; -import org.codehaus.plexus.util.StringUtils; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.tooling.CombinedStatistics; - -/** - * Goal which runs a coverage mutation report only for files that have been - * modified or introduced locally based on the source control configured in - * maven. - */ -@Mojo(name = "scmMutationCoverage", - defaultPhase = LifecyclePhase.VERIFY, - requiresDependencyResolution = ResolutionScope.TEST, - threadSafe = true) -public class ScmMojo extends AbstractPitMojo { - - private static final int NO_LIMIT = -1; - - @Component - private ScmManager manager; - - /** - * List of scm status to include. Names match those defined by the maven scm - * plugin. - * - * Common values include ADDED,MODIFIED (the defaults) & UNKNOWN. - */ - @Parameter(property = "include") - private HashSet include; - - /** - * Analyze last commit. If set to true analyzes last commited change set. - */ - @Parameter(defaultValue = "false", property = "analyseLastCommit") - private boolean analyseLastCommit; - - - @Parameter(property = "originBranch") - private String originBranch; - - @Parameter(property = "destinationBranch", defaultValue = "master") - private String destinationBranch; - - /** - * Connection type to use when querying scm for changed files. Can either be - * "connection" or "developerConnection". - */ - @Parameter(property = "connectionType", defaultValue = "connection") - private String connectionType; - - /** - * Project basedir - */ - @Parameter(property = "basedir", required = true) - private File basedir; - - /** - * Base of scm root. For a multi module project this is probably the parent - * project. - */ - @Parameter(property = "project.parent.basedir") - private File scmRootDir; - - public ScmMojo(final RunPitStrategy executionStrategy, - final ScmManager manager, Predicate filter, - PluginServices plugins, boolean analyseLastCommit, Predicate nonEmptyProjectCheck) { - super(executionStrategy, filter, plugins, nonEmptyProjectCheck); - this.manager = manager; - this.analyseLastCommit = analyseLastCommit; - } - - public ScmMojo() { - - } - - @Override - protected Optional analyse() throws MojoExecutionException { - - this.targetClasses = makeConcreteList(findModifiedClassNames()); - - if (this.targetClasses.isEmpty()) { - this.getLog().info( - "No modified files found - nothing to mutation test, analyseLastCommit=" + this.analyseLastCommit); - return Optional.empty(); - } - - logClassNames(); - defaultTargetTestsToGroupNameIfNoValueSet(); - final ReportOptions data = new MojoToReportOptionsConverter(this, - new SurefireConfigConverter(), filter).convert(); - data.setFailWhenNoMutations(false); - - return Optional.ofNullable(this.goalStrategy.execute(detectBaseDir(), data, - plugins, new HashMap())); - - } - - private void defaultTargetTestsToGroupNameIfNoValueSet() { - if (this.getTargetTests() == null || this.getTargetTests().isEmpty()) { - this.targetTests = makeConcreteList(Collections.singletonList(this - .getProject().getGroupId() + "*")); - } - } - - private void logClassNames() { - for (final String each : this.targetClasses) { - this.getLog().info("Will mutate changed class " + each); - } - } - - private List findModifiedClassNames() throws MojoExecutionException { - - final File sourceRoot = new File(this.project.getBuild() - .getSourceDirectory()); - - final List modifiedPaths = FCollection.map(findModifiedPaths(), pathByScmDir()); - return FCollection.flatMap(modifiedPaths, new PathToJavaClassConverter( - sourceRoot.getAbsolutePath())); - - } - - private Function pathByScmDir() { - return new Function() { - - @Override - public String apply(final String a) { - return scmRootDir.getAbsolutePath() + "/" + a; - } - - }; - } - - private Set findModifiedPaths() throws MojoExecutionException { - try { - final ScmRepository repository = this.manager - .makeScmRepository(getSCMConnection()); - final File scmRoot = scmRoot(); - this.getLog().info("Scm root dir is " + scmRoot); - - final Set statusToInclude = makeStatusSet(); - final Set modifiedPaths; - if (analyseLastCommit) { - modifiedPaths = lastCommitChanges(statusToInclude, repository, scmRoot); - } else if (originBranch != null && destinationBranch != null) { - modifiedPaths = changesBetweenBranchs(originBranch, destinationBranch, statusToInclude, repository, scmRoot); - } else { - modifiedPaths = localChanges(statusToInclude, repository, scmRoot); - } - return modifiedPaths; - } catch (final ScmException e) { - throw new MojoExecutionException("Error while querying scm", e); - } - - } - - private Set lastCommitChanges(Set statusToInclude, ScmRepository repository, File scmRoot) throws ScmException { - ChangeLogScmRequest scmRequest = new ChangeLogScmRequest(repository, new ScmFileSet(scmRoot)); - scmRequest.setLimit(1); - return pathsAffectedByChange(scmRequest, statusToInclude, 1); - } - - private Set changesBetweenBranchs(String origine, String destination, Set statusToInclude, ScmRepository repository, File scmRoot) throws ScmException { - ChangeLogScmRequest scmRequest = new ChangeLogScmRequest(repository, new ScmFileSet(scmRoot)); - scmRequest.setScmBranch(new ScmBranch(destination + ".." + origine)); - return pathsAffectedByChange(scmRequest, statusToInclude, NO_LIMIT); - } - - private Set pathsAffectedByChange(ChangeLogScmRequest scmRequest, Set statusToInclude, int limit) throws ScmException { - Set affected = new LinkedHashSet<>(); - ChangeLogScmResult changeLogScmResult = this.manager.changeLog(scmRequest); - if (changeLogScmResult.isSuccess()) { - List changeSets = limit(changeLogScmResult.getChangeLog().getChangeSets(),limit); - for (ChangeSet change : changeSets) { - List files = change.getFiles(); - for (final ChangeFile changeFile : files) { - if (statusToInclude.contains(changeFile.getAction())) { - affected.add(changeFile.getName()); - } - } - } - } - return affected; - } - - - private Set localChanges(Set statusToInclude, ScmRepository repository, File scmRoot) throws ScmException { - final StatusScmResult status = this.manager.status(repository, - new ScmFileSet(scmRoot)); - Set affected = new LinkedHashSet<>(); - for (final ScmFile file : status.getChangedFiles()) { - if (statusToInclude.contains(file.getStatus())) { - affected.add(file.getPath()); - } - } - return affected; - } - - private List limit(List changeSets, int limit) { - if (limit < 0) { - return changeSets; - } - return changeSets.subList(0, limit); - } - - - private Set makeStatusSet() { - if ((this.include == null) || this.include.isEmpty()) { - return new HashSet<>(Arrays.asList( - ScmStatus.ADDED.getStatus(), ScmStatus.MODIFIED.getStatus())); - } - final Set s = new HashSet<>(); - FCollection.mapTo(this.include, stringToMavenScmStatus(), s); - return s; - } - - private static Function stringToMavenScmStatus() { - return new Function() { - @Override - public ScmFileStatus apply(final String a) { - return ScmStatus.valueOf(a.toUpperCase()).getStatus(); - } - - }; - } - - private File scmRoot() { - if (this.scmRootDir != null) { - return this.scmRootDir; - } - return this.basedir; - } - - private String getSCMConnection() throws MojoExecutionException { - - if (this.project.getScm() == null) { - throw new MojoExecutionException("No SCM Connection configured."); - } - - final String scmConnection = this.project.getScm().getConnection(); - if ("connection".equalsIgnoreCase(this.connectionType) - && StringUtils.isNotEmpty(scmConnection)) { - return scmConnection; - } - - final String scmDeveloper = this.project.getScm().getDeveloperConnection(); - if ("developerconnection".equalsIgnoreCase(this.connectionType) - && StringUtils.isNotEmpty(scmDeveloper)) { - return scmDeveloper; - } - - throw new MojoExecutionException("SCM Connection is not set."); - - } - - public void setConnectionType(final String connectionType) { - this.connectionType = connectionType; - } - - public void setScmRootDir(final File scmRootDir) { - this.scmRootDir = scmRootDir; - } - - /** - * A bug in maven 2 requires that all list fields declare a concrete list type - */ - private static ArrayList makeConcreteList(List list) { - return new ArrayList<>(list); - } - -} +package org.pitest.maven; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.project.MavenProject; +import org.apache.maven.scm.ChangeFile; +import org.apache.maven.scm.ChangeSet; +import org.apache.maven.scm.ScmBranch; +import org.apache.maven.scm.ScmException; +import org.apache.maven.scm.ScmFile; +import org.apache.maven.scm.ScmFileSet; +import org.apache.maven.scm.ScmFileStatus; +import org.apache.maven.scm.command.changelog.ChangeLogScmRequest; +import org.apache.maven.scm.command.changelog.ChangeLogScmResult; +import org.apache.maven.scm.command.status.StatusScmResult; +import org.apache.maven.scm.manager.ScmManager; +import org.apache.maven.scm.repository.ScmRepository; +import org.codehaus.plexus.util.StringUtils; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.tooling.CombinedStatistics; + +/** + * Goal which runs a coverage mutation report only for files that have been + * modified or introduced locally based on the source control configured in + * maven. + */ +@Mojo(name = "scmMutationCoverage", + defaultPhase = LifecyclePhase.VERIFY, + requiresDependencyResolution = ResolutionScope.TEST, + threadSafe = true) +public class ScmMojo extends AbstractPitMojo { + + private static final int NO_LIMIT = -1; + + @Component + private ScmManager manager; + + /** + * List of scm status to include. Names match those defined by the maven scm + * plugin. + * + * Common values include ADDED,MODIFIED (the defaults) & UNKNOWN. + */ + @Parameter(property = "include") + private HashSet include; + + /** + * Analyze last commit. If set to true analyzes last commited change set. + */ + @Parameter(defaultValue = "false", property = "analyseLastCommit") + private boolean analyseLastCommit; + + + @Parameter(property = "originBranch") + private String originBranch; + + @Parameter(property = "destinationBranch", defaultValue = "master") + private String destinationBranch; + + /** + * Connection type to use when querying scm for changed files. Can either be + * "connection" or "developerConnection". + */ + @Parameter(property = "connectionType", defaultValue = "connection") + private String connectionType; + + /** + * Project basedir + */ + @Parameter(property = "basedir", required = true) + private File basedir; + + /** + * Base of scm root. For a multi module project this is probably the parent + * project. + */ + @Parameter(property = "project.parent.basedir") + private File scmRootDir; + + public ScmMojo(final RunPitStrategy executionStrategy, + final ScmManager manager, Predicate filter, + PluginServices plugins, boolean analyseLastCommit, Predicate nonEmptyProjectCheck) { + super(executionStrategy, filter, plugins, nonEmptyProjectCheck); + this.manager = manager; + this.analyseLastCommit = analyseLastCommit; + } + + public ScmMojo() { + + } + + @Override + protected Optional analyse() throws MojoExecutionException { + + this.targetClasses = makeConcreteList(findModifiedClassNames()); + + if (this.targetClasses.isEmpty()) { + this.getLog().info( + "No modified files found - nothing to mutation test, analyseLastCommit=" + this.analyseLastCommit); + return Optional.empty(); + } + + logClassNames(); + defaultTargetTestsToGroupNameIfNoValueSet(); + final ReportOptions data = new MojoToReportOptionsConverter(this, + new SurefireConfigConverter(), filter).convert(); + data.setFailWhenNoMutations(false); + + return Optional.ofNullable(this.goalStrategy.execute(detectBaseDir(), data, + plugins, new HashMap())); + + } + + private void defaultTargetTestsToGroupNameIfNoValueSet() { + if (this.getTargetTests() == null || this.getTargetTests().isEmpty()) { + this.targetTests = makeConcreteList(Collections.singletonList(this + .getProject().getGroupId() + "*")); + } + } + + private void logClassNames() { + for (final String each : this.targetClasses) { + this.getLog().info("Will mutate changed class " + each); + } + } + + private List findModifiedClassNames() throws MojoExecutionException { + + final File sourceRoot = new File(this.project.getBuild() + .getSourceDirectory()); + + final List modifiedPaths = FCollection.map(findModifiedPaths(), pathByScmDir()); + return FCollection.flatMap(modifiedPaths, new PathToJavaClassConverter( + sourceRoot.getAbsolutePath())); + + } + + private Function pathByScmDir() { + return new Function() { + + @Override + public String apply(final String a) { + return scmRootDir.getAbsolutePath() + "/" + a; + } + + }; + } + + private Set findModifiedPaths() throws MojoExecutionException { + try { + final ScmRepository repository = this.manager + .makeScmRepository(getSCMConnection()); + final File scmRoot = scmRoot(); + this.getLog().info("Scm root dir is " + scmRoot); + + final Set statusToInclude = makeStatusSet(); + final Set modifiedPaths; + if (analyseLastCommit) { + modifiedPaths = lastCommitChanges(statusToInclude, repository, scmRoot); + } else if (originBranch != null && destinationBranch != null) { + modifiedPaths = changesBetweenBranchs(originBranch, destinationBranch, statusToInclude, repository, scmRoot); + } else { + modifiedPaths = localChanges(statusToInclude, repository, scmRoot); + } + return modifiedPaths; + } catch (final ScmException e) { + throw new MojoExecutionException("Error while querying scm", e); + } + + } + + private Set lastCommitChanges(Set statusToInclude, ScmRepository repository, File scmRoot) throws ScmException { + ChangeLogScmRequest scmRequest = new ChangeLogScmRequest(repository, new ScmFileSet(scmRoot)); + scmRequest.setLimit(1); + return pathsAffectedByChange(scmRequest, statusToInclude, 1); + } + + private Set changesBetweenBranchs(String origine, String destination, Set statusToInclude, ScmRepository repository, File scmRoot) throws ScmException { + ChangeLogScmRequest scmRequest = new ChangeLogScmRequest(repository, new ScmFileSet(scmRoot)); + scmRequest.setScmBranch(new ScmBranch(destination + ".." + origine)); + return pathsAffectedByChange(scmRequest, statusToInclude, NO_LIMIT); + } + + private Set pathsAffectedByChange(ChangeLogScmRequest scmRequest, Set statusToInclude, int limit) throws ScmException { + Set affected = new LinkedHashSet<>(); + ChangeLogScmResult changeLogScmResult = this.manager.changeLog(scmRequest); + if (changeLogScmResult.isSuccess()) { + List changeSets = limit(changeLogScmResult.getChangeLog().getChangeSets(),limit); + for (ChangeSet change : changeSets) { + List files = change.getFiles(); + for (final ChangeFile changeFile : files) { + if (statusToInclude.contains(changeFile.getAction())) { + affected.add(changeFile.getName()); + } + } + } + } + return affected; + } + + + private Set localChanges(Set statusToInclude, ScmRepository repository, File scmRoot) throws ScmException { + final StatusScmResult status = this.manager.status(repository, + new ScmFileSet(scmRoot)); + Set affected = new LinkedHashSet<>(); + for (final ScmFile file : status.getChangedFiles()) { + if (statusToInclude.contains(file.getStatus())) { + affected.add(file.getPath()); + } + } + return affected; + } + + private List limit(List changeSets, int limit) { + if (limit < 0) { + return changeSets; + } + return changeSets.subList(0, limit); + } + + + private Set makeStatusSet() { + if ((this.include == null) || this.include.isEmpty()) { + return new HashSet<>(Arrays.asList( + ScmStatus.ADDED.getStatus(), ScmStatus.MODIFIED.getStatus())); + } + final Set s = new HashSet<>(); + FCollection.mapTo(this.include, stringToMavenScmStatus(), s); + return s; + } + + private static Function stringToMavenScmStatus() { + return new Function() { + @Override + public ScmFileStatus apply(final String a) { + return ScmStatus.valueOf(a.toUpperCase()).getStatus(); + } + + }; + } + + private File scmRoot() { + if (this.scmRootDir != null) { + return this.scmRootDir; + } + return this.basedir; + } + + private String getSCMConnection() throws MojoExecutionException { + + if (this.project.getScm() == null) { + throw new MojoExecutionException("No SCM Connection configured."); + } + + final String scmConnection = this.project.getScm().getConnection(); + if ("connection".equalsIgnoreCase(this.connectionType) + && StringUtils.isNotEmpty(scmConnection)) { + return scmConnection; + } + + final String scmDeveloper = this.project.getScm().getDeveloperConnection(); + if ("developerconnection".equalsIgnoreCase(this.connectionType) + && StringUtils.isNotEmpty(scmDeveloper)) { + return scmDeveloper; + } + + throw new MojoExecutionException("SCM Connection is not set."); + + } + + public void setConnectionType(final String connectionType) { + this.connectionType = connectionType; + } + + public void setScmRootDir(final File scmRootDir) { + this.scmRootDir = scmRootDir; + } + + /** + * A bug in maven 2 requires that all list fields declare a concrete list type + */ + private static ArrayList makeConcreteList(List list) { + return new ArrayList<>(list); + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/ScmStatus.java b/pitest-maven/src/main/java/org/pitest/maven/ScmStatus.java index 3929a9e96..fb50bf221 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/ScmStatus.java +++ b/pitest-maven/src/main/java/org/pitest/maven/ScmStatus.java @@ -1,103 +1,103 @@ -package org.pitest.maven; - -import org.apache.maven.scm.ScmFileStatus; - -/** - * Maps string to maven ScmFileStatus constants. - * - * Descriptions copied from maven scm source. - */ -public enum ScmStatus { - - /** - * File is added to the working tree and does not yet exist in the repository - */ - ADDED(ScmFileStatus.ADDED), - - /** - * File is removed from the working tree thus not revisioned anymore.
- * The file is still present in the repository.
- * The file could be deleted from the filesystem depending on the provider. - */ - DELETED(ScmFileStatus.DELETED), - - /** - * The file has been modified in the working tree. - */ - MODIFIED(ScmFileStatus.MODIFIED), - - /** - * The file has been renamed or moved in the working tree. - */ - RENAMED(ScmFileStatus.RENAMED), - - /** - * The file has been copied in the working tree. - */ - COPIED(ScmFileStatus.COPIED), - - /** - * The file is missing in the working tree. - */ - MISSING(ScmFileStatus.MISSING), - - /** - * File from working tree is checked into the repository - */ - CHECKED_IN(ScmFileStatus.CHECKED_IN), - - /** - * File is checked out from the repository and into the working tree - */ - CHECKED_OUT(ScmFileStatus.CHECKED_OUT), - - /** - * The file in the working tree has differences to the one in repository that - * conflicts ie. it cannot automatically be merged. - */ - CONFLICT(ScmFileStatus.CONFLICT), - - /** - * The file in the working tree has been updated with changes from the - * repository. - */ - PATCHED(ScmFileStatus.PATCHED), - - /** - * The file is added, removed or updated from the repository, thus its - * up-to-date with the version in the repository. See also isUpdate() - */ - UPDATED(ScmFileStatus.UPDATED), - - /** - * The file is part of a tag. - */ - TAGGED(ScmFileStatus.TAGGED), - - /** - * The file is locked. - */ - LOCKED(ScmFileStatus.LOCKED), - - /** - * The file is in the working tree but is not versioned and not ignored - * either. - */ - UNKNOWN(ScmFileStatus.UNKNOWN), - - /** - * The file is being edited - */ - EDITED(ScmFileStatus.EDITED); - - private final ScmFileStatus status; - - public ScmFileStatus getStatus() { - return this.status; - } - - ScmStatus(final ScmFileStatus status) { - this.status = status; - } - -} +package org.pitest.maven; + +import org.apache.maven.scm.ScmFileStatus; + +/** + * Maps string to maven ScmFileStatus constants. + * + * Descriptions copied from maven scm source. + */ +public enum ScmStatus { + + /** + * File is added to the working tree and does not yet exist in the repository + */ + ADDED(ScmFileStatus.ADDED), + + /** + * File is removed from the working tree thus not revisioned anymore.
+ * The file is still present in the repository.
+ * The file could be deleted from the filesystem depending on the provider. + */ + DELETED(ScmFileStatus.DELETED), + + /** + * The file has been modified in the working tree. + */ + MODIFIED(ScmFileStatus.MODIFIED), + + /** + * The file has been renamed or moved in the working tree. + */ + RENAMED(ScmFileStatus.RENAMED), + + /** + * The file has been copied in the working tree. + */ + COPIED(ScmFileStatus.COPIED), + + /** + * The file is missing in the working tree. + */ + MISSING(ScmFileStatus.MISSING), + + /** + * File from working tree is checked into the repository + */ + CHECKED_IN(ScmFileStatus.CHECKED_IN), + + /** + * File is checked out from the repository and into the working tree + */ + CHECKED_OUT(ScmFileStatus.CHECKED_OUT), + + /** + * The file in the working tree has differences to the one in repository that + * conflicts ie. it cannot automatically be merged. + */ + CONFLICT(ScmFileStatus.CONFLICT), + + /** + * The file in the working tree has been updated with changes from the + * repository. + */ + PATCHED(ScmFileStatus.PATCHED), + + /** + * The file is added, removed or updated from the repository, thus its + * up-to-date with the version in the repository. See also isUpdate() + */ + UPDATED(ScmFileStatus.UPDATED), + + /** + * The file is part of a tag. + */ + TAGGED(ScmFileStatus.TAGGED), + + /** + * The file is locked. + */ + LOCKED(ScmFileStatus.LOCKED), + + /** + * The file is in the working tree but is not versioned and not ignored + * either. + */ + UNKNOWN(ScmFileStatus.UNKNOWN), + + /** + * The file is being edited + */ + EDITED(ScmFileStatus.EDITED); + + private final ScmFileStatus status; + + public ScmFileStatus getStatus() { + return this.status; + } + + ScmStatus(final ScmFileStatus status) { + this.status = status; + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/SurefireConfigConverter.java b/pitest-maven/src/main/java/org/pitest/maven/SurefireConfigConverter.java index 6e8fd9be4..6cf61cc19 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/SurefireConfigConverter.java +++ b/pitest-maven/src/main/java/org/pitest/maven/SurefireConfigConverter.java @@ -1,82 +1,82 @@ -package org.pitest.maven; - -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import org.codehaus.plexus.util.xml.Xpp3Dom; -import java.util.function.Function; -import org.pitest.functional.FCollection; -import java.util.function.Predicate; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.util.Glob; - -/** - * Extracts configuration from surefire plugin and create pitest equivalents - */ -public class SurefireConfigConverter { - - public ReportOptions update(ReportOptions option, Xpp3Dom configuration) { - if (configuration == null) { - return option; - } - convertExcludes(option, configuration); - convertGroups(option, configuration); - return option; - } - - private void convertGroups(ReportOptions option, Xpp3Dom configuration) { - TestGroupConfig existing = option.getGroupConfig(); - if ((existing == null) - || (existing.getExcludedGroups().isEmpty() && existing - .getIncludedGroups().isEmpty())) { - List groups = extractStrings("groups", configuration); - List excluded = extractStrings("excludedGroups", configuration); - TestGroupConfig gc = new TestGroupConfig(excluded, groups); - option.setGroupConfig(gc); - } - } - - private List extractStrings(String element, Xpp3Dom configuration) { - Xpp3Dom groups = configuration.getChild(element); - if (groups != null) { - String[] parts = groups.getValue().split(" "); - return Arrays.asList(parts); - } else { - return Collections.emptyList(); - } - } - - private void convertExcludes(ReportOptions option, Xpp3Dom configuration) { - List> excludes = FCollection.map( - extract("excludes", configuration), filenameToClassFilter()); - excludes.addAll(option.getExcludedTestClasses()); - option.setExcludedTestClasses(excludes); - } - - private Function> filenameToClassFilter() { - return new Function>() { - @Override - public Predicate apply(String a) { - return new Glob(a.replace(".java", "").replace("/", ".")); - } - }; - } - - private List extract(String childname, Xpp3Dom config) { - final Xpp3Dom subelement = config.getChild(childname); - if (subelement != null) { - List result = new LinkedList<>(); - final Xpp3Dom[] children = subelement.getChildren(); - for (Xpp3Dom child : children) { - result.add(child.getValue()); - } - return result; - } - - return Collections.emptyList(); - } - -} +package org.pitest.maven; + +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.codehaus.plexus.util.xml.Xpp3Dom; +import java.util.function.Function; +import org.pitest.functional.FCollection; +import java.util.function.Predicate; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.util.Glob; + +/** + * Extracts configuration from surefire plugin and create pitest equivalents + */ +public class SurefireConfigConverter { + + public ReportOptions update(ReportOptions option, Xpp3Dom configuration) { + if (configuration == null) { + return option; + } + convertExcludes(option, configuration); + convertGroups(option, configuration); + return option; + } + + private void convertGroups(ReportOptions option, Xpp3Dom configuration) { + TestGroupConfig existing = option.getGroupConfig(); + if ((existing == null) + || (existing.getExcludedGroups().isEmpty() && existing + .getIncludedGroups().isEmpty())) { + List groups = extractStrings("groups", configuration); + List excluded = extractStrings("excludedGroups", configuration); + TestGroupConfig gc = new TestGroupConfig(excluded, groups); + option.setGroupConfig(gc); + } + } + + private List extractStrings(String element, Xpp3Dom configuration) { + Xpp3Dom groups = configuration.getChild(element); + if (groups != null) { + String[] parts = groups.getValue().split(" "); + return Arrays.asList(parts); + } else { + return Collections.emptyList(); + } + } + + private void convertExcludes(ReportOptions option, Xpp3Dom configuration) { + List> excludes = FCollection.map( + extract("excludes", configuration), filenameToClassFilter()); + excludes.addAll(option.getExcludedTestClasses()); + option.setExcludedTestClasses(excludes); + } + + private Function> filenameToClassFilter() { + return new Function>() { + @Override + public Predicate apply(String a) { + return new Glob(a.replace(".java", "").replace("/", ".")); + } + }; + } + + private List extract(String childname, Xpp3Dom config) { + final Xpp3Dom subelement = config.getChild(childname); + if (subelement != null) { + List result = new LinkedList<>(); + final Xpp3Dom[] children = subelement.getChildren(); + for (Xpp3Dom child : children) { + result.add(child.getValue()); + } + return result; + } + + return Collections.emptyList(); + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/PitAggregationMojo.java b/pitest-maven/src/main/java/org/pitest/maven/report/PitAggregationMojo.java index b6c874bdb..6d2220e34 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/PitAggregationMojo.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/PitAggregationMojo.java @@ -1,179 +1,179 @@ -package org.pitest.maven.report; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Locale; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Dependency; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; -import org.apache.maven.reporting.MavenReportException; -import org.codehaus.plexus.util.FileUtils; -import org.pitest.aggregate.ReportAggregator; -import java.util.function.Function; -import org.pitest.functional.FCollection; -import org.pitest.maven.DependencyFilter; -import org.pitest.mutationtest.config.DirectoryResultOutputStrategy; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.UndatedReportDirCreationStrategy; - -/** - * Goal which aggregates the results of multiple tests into a single result. - * - *

- * Based upon Jacoco's ReportAggregateMojo, creates a structured report (HTML, - * XML, or CSV) from multiple projects. The report is created the all modules - * this project includes as dependencies. - *

- * - *

- * To successfully aggregate reports, each of the individual sub-module reports - * must have the exportLineCoverage set to true, and must export an - * XML formatted report. The the developer would simply include an extra module, - * which has all of the modules which contain reports as dependencies. That - * "report-aggregation" module would then call this mojo to aggregate all of the - * individual reports into a single report. - *

- * - */ -@Mojo(name = "report-aggregate", defaultPhase = LifecyclePhase.PREPARE_PACKAGE) -public class PitAggregationMojo extends PitReportMojo { - - private static final String MUTATION_RESULT_FILTER = "target/pit-reports/mutations.xml"; - private static final String LINECOVERAGE_FILTER = "target/pit-reports/linecoverage.xml"; - /** - * The projects in the reactor. - */ - @Parameter(property = "reactorProjects", readonly = true) - private List reactorProjects; - - @Override - public String getDescription(final Locale locale) { - return getName(locale) + " Coverage Report."; - } - - @Override - protected void executeReport(final Locale locale) - throws MavenReportException { - try { - final Collection allProjects = findDependencies(); - - final ReportAggregator.Builder reportAggregationBuilder = ReportAggregator - .builder(); - - for (final MavenProject proj : allProjects) { - addProjectFiles(reportAggregationBuilder, proj); - } - - final ReportAggregator reportAggregator = reportAggregationBuilder - .resultOutputStrategy(new DirectoryResultOutputStrategy( - getReportsDirectory().getAbsolutePath(), - new UndatedReportDirCreationStrategy())) - .build(); - - reportAggregator.aggregateReport(); - } catch (final Exception e) { - throw new MavenReportException(e.getMessage(), e); - } - } - - private void addProjectFiles( - final ReportAggregator.Builder reportAggregationBuilder, - final MavenProject proj) throws IOException, Exception { - final File projectBaseDir = proj.getBasedir(); - List files = getProjectFilesByFilter(projectBaseDir, - MUTATION_RESULT_FILTER); - for (final File file : files) { - reportAggregationBuilder.addMutationResultsFile(file); - } - files = getProjectFilesByFilter(projectBaseDir, LINECOVERAGE_FILTER); - for (final File file : files) { - reportAggregationBuilder.addLineCoverageFile(file); - } - files = convertToRootDirs(proj.getCompileSourceRoots(), - proj.getTestCompileSourceRoots()); - for (final File file : files) { - reportAggregationBuilder.addSourceCodeDirectory(file); - } - files = getCompiledDirs(proj); - for (final File file : files) { - reportAggregationBuilder.addCompiledCodeDirectory(file); - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private List convertToRootDirs(final List... directoryLists) { - final List roots = new ArrayList<>(); - for (final List directoryList : directoryLists) { - roots.addAll(directoryList); - } - return FCollection.map(roots, new Function() { - @Override - public File apply(final String a) { - return new File(a); - } - }); - } - - private List getProjectFilesByFilter(final File projectBaseDir, - final String filter) throws IOException { - final List files = FileUtils.getFiles(projectBaseDir, filter, ""); - return files == null ? new ArrayList<>() : files; - } - - @SuppressWarnings("unchecked") - private List getCompiledDirs(final MavenProject project) - throws Exception { - final List sourceRoots = new ArrayList<>(); - for (final Object artifactObj : FCollection - .filter(project.getPluginArtifactMap().values(), new DependencyFilter( - new PluginServices(PitAggregationMojo.class.getClassLoader())))) { - - final Artifact artifact = (Artifact) artifactObj; - sourceRoots.add(artifact.getFile().getAbsolutePath()); - } - return convertToRootDirs(project.getTestClasspathElements(), - Arrays.asList(project.getBuild().getOutputDirectory(), - project.getBuild().getTestOutputDirectory()), - sourceRoots); - } - - // this method comes from - // https://github.com/jacoco/jacoco/blob/master/jacoco-maven-plugin/src/org/jacoco/maven/ReportAggregateMojo.java - private List findDependencies() { - final List result = new ArrayList<>(); - final List scopeList = Arrays.asList(Artifact.SCOPE_COMPILE, - Artifact.SCOPE_RUNTIME, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_TEST); - for (final Object dependencyObject : getProject().getDependencies()) { - final Dependency dependency = (Dependency) dependencyObject; - if (scopeList.contains(dependency.getScope())) { - final MavenProject project = findProjectFromReactor(dependency); - if (project != null) { - result.add(project); - } - } - } - return result; - } - - // this method comes from - // https://github.com/jacoco/jacoco/blob/master/jacoco-maven-plugin/src/org/jacoco/maven/ReportAggregateMojo.java - private MavenProject findProjectFromReactor(final Dependency d) { - for (final MavenProject p : reactorProjects) { - if (p.getGroupId().equals(d.getGroupId()) - && p.getArtifactId().equals(d.getArtifactId()) - && p.getVersion().equals(d.getVersion())) { - return p; - } - } - return null; - } - -} +package org.pitest.maven.report; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Locale; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Dependency; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; +import org.apache.maven.reporting.MavenReportException; +import org.codehaus.plexus.util.FileUtils; +import org.pitest.aggregate.ReportAggregator; +import java.util.function.Function; +import org.pitest.functional.FCollection; +import org.pitest.maven.DependencyFilter; +import org.pitest.mutationtest.config.DirectoryResultOutputStrategy; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.UndatedReportDirCreationStrategy; + +/** + * Goal which aggregates the results of multiple tests into a single result. + * + *

+ * Based upon Jacoco's ReportAggregateMojo, creates a structured report (HTML, + * XML, or CSV) from multiple projects. The report is created the all modules + * this project includes as dependencies. + *

+ * + *

+ * To successfully aggregate reports, each of the individual sub-module reports + * must have the exportLineCoverage set to true, and must export an + * XML formatted report. The the developer would simply include an extra module, + * which has all of the modules which contain reports as dependencies. That + * "report-aggregation" module would then call this mojo to aggregate all of the + * individual reports into a single report. + *

+ * + */ +@Mojo(name = "report-aggregate", defaultPhase = LifecyclePhase.PREPARE_PACKAGE) +public class PitAggregationMojo extends PitReportMojo { + + private static final String MUTATION_RESULT_FILTER = "target/pit-reports/mutations.xml"; + private static final String LINECOVERAGE_FILTER = "target/pit-reports/linecoverage.xml"; + /** + * The projects in the reactor. + */ + @Parameter(property = "reactorProjects", readonly = true) + private List reactorProjects; + + @Override + public String getDescription(final Locale locale) { + return getName(locale) + " Coverage Report."; + } + + @Override + protected void executeReport(final Locale locale) + throws MavenReportException { + try { + final Collection allProjects = findDependencies(); + + final ReportAggregator.Builder reportAggregationBuilder = ReportAggregator + .builder(); + + for (final MavenProject proj : allProjects) { + addProjectFiles(reportAggregationBuilder, proj); + } + + final ReportAggregator reportAggregator = reportAggregationBuilder + .resultOutputStrategy(new DirectoryResultOutputStrategy( + getReportsDirectory().getAbsolutePath(), + new UndatedReportDirCreationStrategy())) + .build(); + + reportAggregator.aggregateReport(); + } catch (final Exception e) { + throw new MavenReportException(e.getMessage(), e); + } + } + + private void addProjectFiles( + final ReportAggregator.Builder reportAggregationBuilder, + final MavenProject proj) throws IOException, Exception { + final File projectBaseDir = proj.getBasedir(); + List files = getProjectFilesByFilter(projectBaseDir, + MUTATION_RESULT_FILTER); + for (final File file : files) { + reportAggregationBuilder.addMutationResultsFile(file); + } + files = getProjectFilesByFilter(projectBaseDir, LINECOVERAGE_FILTER); + for (final File file : files) { + reportAggregationBuilder.addLineCoverageFile(file); + } + files = convertToRootDirs(proj.getCompileSourceRoots(), + proj.getTestCompileSourceRoots()); + for (final File file : files) { + reportAggregationBuilder.addSourceCodeDirectory(file); + } + files = getCompiledDirs(proj); + for (final File file : files) { + reportAggregationBuilder.addCompiledCodeDirectory(file); + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private List convertToRootDirs(final List... directoryLists) { + final List roots = new ArrayList<>(); + for (final List directoryList : directoryLists) { + roots.addAll(directoryList); + } + return FCollection.map(roots, new Function() { + @Override + public File apply(final String a) { + return new File(a); + } + }); + } + + private List getProjectFilesByFilter(final File projectBaseDir, + final String filter) throws IOException { + final List files = FileUtils.getFiles(projectBaseDir, filter, ""); + return files == null ? new ArrayList<>() : files; + } + + @SuppressWarnings("unchecked") + private List getCompiledDirs(final MavenProject project) + throws Exception { + final List sourceRoots = new ArrayList<>(); + for (final Object artifactObj : FCollection + .filter(project.getPluginArtifactMap().values(), new DependencyFilter( + new PluginServices(PitAggregationMojo.class.getClassLoader())))) { + + final Artifact artifact = (Artifact) artifactObj; + sourceRoots.add(artifact.getFile().getAbsolutePath()); + } + return convertToRootDirs(project.getTestClasspathElements(), + Arrays.asList(project.getBuild().getOutputDirectory(), + project.getBuild().getTestOutputDirectory()), + sourceRoots); + } + + // this method comes from + // https://github.com/jacoco/jacoco/blob/master/jacoco-maven-plugin/src/org/jacoco/maven/ReportAggregateMojo.java + private List findDependencies() { + final List result = new ArrayList<>(); + final List scopeList = Arrays.asList(Artifact.SCOPE_COMPILE, + Artifact.SCOPE_RUNTIME, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_TEST); + for (final Object dependencyObject : getProject().getDependencies()) { + final Dependency dependency = (Dependency) dependencyObject; + if (scopeList.contains(dependency.getScope())) { + final MavenProject project = findProjectFromReactor(dependency); + if (project != null) { + result.add(project); + } + } + } + return result; + } + + // this method comes from + // https://github.com/jacoco/jacoco/blob/master/jacoco-maven-plugin/src/org/jacoco/maven/ReportAggregateMojo.java + private MavenProject findProjectFromReactor(final Dependency d) { + for (final MavenProject p : reactorProjects) { + if (p.getGroupId().equals(d.getGroupId()) + && p.getArtifactId().equals(d.getArtifactId()) + && p.getVersion().equals(d.getVersion())) { + return p; + } + } + return null; + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/PitReportMojo.java b/pitest-maven/src/main/java/org/pitest/maven/report/PitReportMojo.java index 3d218f150..1e5442fc6 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/PitReportMojo.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/PitReportMojo.java @@ -1,188 +1,188 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report; - -import java.io.File; -import java.util.List; -import java.util.Locale; - -import org.apache.maven.doxia.siterenderer.Renderer; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; -import org.apache.maven.reporting.AbstractMavenReport; -import org.apache.maven.reporting.MavenReportException; -import org.pitest.maven.report.generator.ReportGenerationContext; -import org.pitest.maven.report.generator.ReportGenerationManager; -import org.pitest.util.PitError; - -/** - * Generates a report of the pit mutation testing. - */ -@Mojo(name = "report", defaultPhase = LifecyclePhase.SITE) -public class PitReportMojo extends AbstractMavenReport { - - @Component - private Renderer siteRenderer; - - @Parameter(defaultValue = "${project}", required = true, readonly = true) - private MavenProject project; - - /** - * When set to true, indicates that generation of the site report should be - * skipped. - */ - @Parameter(property = "pit.report.skip", defaultValue = "false") - private boolean skip; - - /** - * Base directory where all pit reports are written to by the mutationCoverage - * goal. If timestampedReports is true (the default), then the actual reports - * will be contained in a subdirectory within this directory. If - * timestampedReports is false, the actual reports will be in this directory. - */ - @Parameter(property = "reportsDirectory", defaultValue = "${project.build.directory}/pit-reports") - private File reportsDirectory; - - /** - * Determines what type of data file should be used to generate the report. - * Currently, only "HTML" is supported which does nothing more than copy the - * HTML report generated by the mutationCoverage goal into the site directory. - * However, the plan is to accept any source format that can be specified in - * the outputFormats parameter of the mutationCoverage goal. - */ - @Parameter(property = "pit.report.sourceDataFormats", defaultValue = "HTML") - private List sourceDataFormats; - - /** - * Determines the name of the report that is displayed under the site's - * Project Reports section - */ - @Parameter(property = "pit.report.name", defaultValue = "PIT Test Report") - private String siteReportName; - - /** - * Determines the description of the report that is displayed under the - * description of the site's Project Reports section - */ - @Parameter(property = "pit.report.description", defaultValue = "Report of the pit test coverage") - private String siteReportDescription; - - /** - * Specifies the directory under ${project.reporting.outputDirectory} where - * the pit reports will be written. The value of this parameter will be - * relative to ${project.reporting.outputDirectory}. For example, if this - * parameter is set to "foo", then the pit reports will be located in - * ${project.reporting.outputDirectory}/foo. - * - */ - @Parameter(property = "pit.report.outputdir", defaultValue = "pit-reports") - private String siteReportDirectory; - - private ReportGenerationManager reportGenerationManager; - - public PitReportMojo() { - super(); - - this.reportGenerationManager = new ReportGenerationManager(); - } - - @Override - public String getOutputName() { - return this.siteReportDirectory + File.separator + "index"; - } - - @Override - public String getName(Locale locale) { - return this.siteReportName; - } - - @Override - public String getDescription(Locale locale) { - return this.siteReportDescription; - } - - @Override - protected Renderer getSiteRenderer() { - return this.siteRenderer; - } - - @Override - protected String getOutputDirectory() { - return this.reportsDirectory.getAbsolutePath(); - } - - @Override - protected MavenProject getProject() { - return this.project; - } - - @Override - protected void executeReport(Locale locale) throws MavenReportException { - this.getLog().debug("PitReportMojo - starting"); - - if (!this.reportsDirectory.exists()) { - throw new PitError("could not find reports directory [" - + this.reportsDirectory + "]"); - } - - if (!this.reportsDirectory.canRead()) { - throw new PitError("reports directory [" + this.reportsDirectory - + "] not readable"); - } - - if (!this.reportsDirectory.isDirectory()) { - throw new PitError("reports directory [" + this.reportsDirectory - + "] is actually a file, it must be a directory"); - } - - this.reportGenerationManager.generateSiteReport(this - .buildReportGenerationContext(locale)); - - this.getLog().debug("PitReportMojo - ending"); - } - - @Override - public boolean canGenerateReport() { - return !skip; - } - - @Override - public boolean isExternalReport() { - return true; - } - - public boolean isSkip() { - return skip; - } - - public File getReportsDirectory() { - return reportsDirectory; - } - - public List getSourceDataFormats() { - return this.sourceDataFormats; - } - - private ReportGenerationContext buildReportGenerationContext(Locale locale) { - return new ReportGenerationContext(locale, this.getSink(), - reportsDirectory, new File(this.getReportOutputDirectory() - .getAbsolutePath() + File.separator + this.siteReportDirectory), - this.getLog(), this.getSourceDataFormats()); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report; + +import java.io.File; +import java.util.List; +import java.util.Locale; + +import org.apache.maven.doxia.siterenderer.Renderer; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; +import org.apache.maven.reporting.AbstractMavenReport; +import org.apache.maven.reporting.MavenReportException; +import org.pitest.maven.report.generator.ReportGenerationContext; +import org.pitest.maven.report.generator.ReportGenerationManager; +import org.pitest.util.PitError; + +/** + * Generates a report of the pit mutation testing. + */ +@Mojo(name = "report", defaultPhase = LifecyclePhase.SITE) +public class PitReportMojo extends AbstractMavenReport { + + @Component + private Renderer siteRenderer; + + @Parameter(defaultValue = "${project}", required = true, readonly = true) + private MavenProject project; + + /** + * When set to true, indicates that generation of the site report should be + * skipped. + */ + @Parameter(property = "pit.report.skip", defaultValue = "false") + private boolean skip; + + /** + * Base directory where all pit reports are written to by the mutationCoverage + * goal. If timestampedReports is true (the default), then the actual reports + * will be contained in a subdirectory within this directory. If + * timestampedReports is false, the actual reports will be in this directory. + */ + @Parameter(property = "reportsDirectory", defaultValue = "${project.build.directory}/pit-reports") + private File reportsDirectory; + + /** + * Determines what type of data file should be used to generate the report. + * Currently, only "HTML" is supported which does nothing more than copy the + * HTML report generated by the mutationCoverage goal into the site directory. + * However, the plan is to accept any source format that can be specified in + * the outputFormats parameter of the mutationCoverage goal. + */ + @Parameter(property = "pit.report.sourceDataFormats", defaultValue = "HTML") + private List sourceDataFormats; + + /** + * Determines the name of the report that is displayed under the site's + * Project Reports section + */ + @Parameter(property = "pit.report.name", defaultValue = "PIT Test Report") + private String siteReportName; + + /** + * Determines the description of the report that is displayed under the + * description of the site's Project Reports section + */ + @Parameter(property = "pit.report.description", defaultValue = "Report of the pit test coverage") + private String siteReportDescription; + + /** + * Specifies the directory under ${project.reporting.outputDirectory} where + * the pit reports will be written. The value of this parameter will be + * relative to ${project.reporting.outputDirectory}. For example, if this + * parameter is set to "foo", then the pit reports will be located in + * ${project.reporting.outputDirectory}/foo. + * + */ + @Parameter(property = "pit.report.outputdir", defaultValue = "pit-reports") + private String siteReportDirectory; + + private ReportGenerationManager reportGenerationManager; + + public PitReportMojo() { + super(); + + this.reportGenerationManager = new ReportGenerationManager(); + } + + @Override + public String getOutputName() { + return this.siteReportDirectory + File.separator + "index"; + } + + @Override + public String getName(Locale locale) { + return this.siteReportName; + } + + @Override + public String getDescription(Locale locale) { + return this.siteReportDescription; + } + + @Override + protected Renderer getSiteRenderer() { + return this.siteRenderer; + } + + @Override + protected String getOutputDirectory() { + return this.reportsDirectory.getAbsolutePath(); + } + + @Override + protected MavenProject getProject() { + return this.project; + } + + @Override + protected void executeReport(Locale locale) throws MavenReportException { + this.getLog().debug("PitReportMojo - starting"); + + if (!this.reportsDirectory.exists()) { + throw new PitError("could not find reports directory [" + + this.reportsDirectory + "]"); + } + + if (!this.reportsDirectory.canRead()) { + throw new PitError("reports directory [" + this.reportsDirectory + + "] not readable"); + } + + if (!this.reportsDirectory.isDirectory()) { + throw new PitError("reports directory [" + this.reportsDirectory + + "] is actually a file, it must be a directory"); + } + + this.reportGenerationManager.generateSiteReport(this + .buildReportGenerationContext(locale)); + + this.getLog().debug("PitReportMojo - ending"); + } + + @Override + public boolean canGenerateReport() { + return !skip; + } + + @Override + public boolean isExternalReport() { + return true; + } + + public boolean isSkip() { + return skip; + } + + public File getReportsDirectory() { + return reportsDirectory; + } + + public List getSourceDataFormats() { + return this.sourceDataFormats; + } + + private ReportGenerationContext buildReportGenerationContext(Locale locale) { + return new ReportGenerationContext(locale, this.getSink(), + reportsDirectory, new File(this.getReportOutputDirectory() + .getAbsolutePath() + File.separator + this.siteReportDirectory), + this.getLog(), this.getSourceDataFormats()); + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/ReportSourceLocator.java b/pitest-maven/src/main/java/org/pitest/maven/report/ReportSourceLocator.java index 10ffb5b58..d2e0645ef 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/ReportSourceLocator.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/ReportSourceLocator.java @@ -1,122 +1,122 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report; - -import java.io.File; -import java.io.FileFilter; -import java.util.Arrays; - -import org.apache.commons.io.comparator.LastModifiedFileComparator; -import org.apache.commons.io.filefilter.AndFileFilter; -import org.apache.commons.io.filefilter.CanWriteFileFilter; -import org.apache.commons.io.filefilter.DirectoryFileFilter; -import org.apache.commons.io.filefilter.RegexFileFilter; -import org.apache.maven.plugin.logging.Log; -import org.pitest.util.PitError; - -/** - * Determines the directory where the most recent PIT reports are actually - * located since the value of the timestamedReports parameter could impact where - * the reports are stored. - * - * @author jasonmfehr - */ -public class ReportSourceLocator { - - // a java.io.File object is considered to be representing a directory where a - // timestamped pit report is located if - // 1.) the java.io.File is a directory - // 2.) the directory name contains only numbers - // 3.) the directory is readable - static final FileFilter TIMESTAMPED_REPORTS_FILE_FILTER = - new AndFileFilter(Arrays.asList(DirectoryFileFilter.DIRECTORY, - new RegexFileFilter( - "^\\d+$"), - CanWriteFileFilter.CAN_WRITE)); - - /** - * Determines the directory where the most recent PIT reports are located. If - * timestampedReports is set to true, then the latest reports directory is - * located and returned. If timestampedReports is set to false, then the - * provided reportsDirectory parameter is returned. If multiple runs of the - * plugin have resulted in a combination of a non-timestamped report directory - * and timestamped reports directories, then the latest of all those - * directories is returned. - * - * See {@link ReportSourceLocator#TIMESTAMPED_REPORTS_FILE_FILTER} for an - * explanation of what constitutes a timestamped reports directory; - * - * @param reportsDirectory - * {@link File} representing the directory where non-timestamped - * reports were written if the plugin's configuration has - * timestampedReports set to true; - * @param log - * {@link Log} plugin logger for logging debug messages - * - * @return {@link File} representing the directory where the latest PIT - * reports are located - */ - public File locate(File reportsDirectory, Log log) { - if (!reportsDirectory.exists()) { - throw new PitError("could not find reports directory [" - + reportsDirectory + "]"); - } - - if (!reportsDirectory.canRead()) { - throw new PitError("reports directory [" + reportsDirectory - + "] not readable"); - } - - if (!reportsDirectory.isDirectory()) { - throw new PitError("reports directory [" + reportsDirectory - + "] is actually a file, it must be a directory"); - } - - return executeLocator(reportsDirectory, log); - } - - private File executeLocator(File reportsDirectory, Log log) { - File[] subdirectories = reportsDirectory - .listFiles(TIMESTAMPED_REPORTS_FILE_FILTER); - File latest = reportsDirectory; - - log.debug("ReportSourceLocator starting search in directory [" - + reportsDirectory.getAbsolutePath() + "]"); - - if (subdirectories != null) { - LastModifiedFileComparator c = new LastModifiedFileComparator(); - - for (File f : subdirectories) { - log.debug("comparing directory [" + f.getAbsolutePath() - + "] with the current latest directory of [" - + latest.getAbsolutePath() + "]"); - if (c.compare(latest, f) < 0) { - latest = f; - log.debug("directory [" + f.getAbsolutePath() + "] is now the latest"); - } - } - } else { - throw new PitError("could not list files in directory [" - + reportsDirectory.getAbsolutePath() - + "] because of an unknown I/O error"); - } - - log.debug("ReportSourceLocator determined directory [" - + latest.getAbsolutePath() - + "] is the directory containing the latest pit reports"); - return latest; - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report; + +import java.io.File; +import java.io.FileFilter; +import java.util.Arrays; + +import org.apache.commons.io.comparator.LastModifiedFileComparator; +import org.apache.commons.io.filefilter.AndFileFilter; +import org.apache.commons.io.filefilter.CanWriteFileFilter; +import org.apache.commons.io.filefilter.DirectoryFileFilter; +import org.apache.commons.io.filefilter.RegexFileFilter; +import org.apache.maven.plugin.logging.Log; +import org.pitest.util.PitError; + +/** + * Determines the directory where the most recent PIT reports are actually + * located since the value of the timestamedReports parameter could impact where + * the reports are stored. + * + * @author jasonmfehr + */ +public class ReportSourceLocator { + + // a java.io.File object is considered to be representing a directory where a + // timestamped pit report is located if + // 1.) the java.io.File is a directory + // 2.) the directory name contains only numbers + // 3.) the directory is readable + static final FileFilter TIMESTAMPED_REPORTS_FILE_FILTER = + new AndFileFilter(Arrays.asList(DirectoryFileFilter.DIRECTORY, + new RegexFileFilter( + "^\\d+$"), + CanWriteFileFilter.CAN_WRITE)); + + /** + * Determines the directory where the most recent PIT reports are located. If + * timestampedReports is set to true, then the latest reports directory is + * located and returned. If timestampedReports is set to false, then the + * provided reportsDirectory parameter is returned. If multiple runs of the + * plugin have resulted in a combination of a non-timestamped report directory + * and timestamped reports directories, then the latest of all those + * directories is returned. + * + * See {@link ReportSourceLocator#TIMESTAMPED_REPORTS_FILE_FILTER} for an + * explanation of what constitutes a timestamped reports directory; + * + * @param reportsDirectory + * {@link File} representing the directory where non-timestamped + * reports were written if the plugin's configuration has + * timestampedReports set to true; + * @param log + * {@link Log} plugin logger for logging debug messages + * + * @return {@link File} representing the directory where the latest PIT + * reports are located + */ + public File locate(File reportsDirectory, Log log) { + if (!reportsDirectory.exists()) { + throw new PitError("could not find reports directory [" + + reportsDirectory + "]"); + } + + if (!reportsDirectory.canRead()) { + throw new PitError("reports directory [" + reportsDirectory + + "] not readable"); + } + + if (!reportsDirectory.isDirectory()) { + throw new PitError("reports directory [" + reportsDirectory + + "] is actually a file, it must be a directory"); + } + + return executeLocator(reportsDirectory, log); + } + + private File executeLocator(File reportsDirectory, Log log) { + File[] subdirectories = reportsDirectory + .listFiles(TIMESTAMPED_REPORTS_FILE_FILTER); + File latest = reportsDirectory; + + log.debug("ReportSourceLocator starting search in directory [" + + reportsDirectory.getAbsolutePath() + "]"); + + if (subdirectories != null) { + LastModifiedFileComparator c = new LastModifiedFileComparator(); + + for (File f : subdirectories) { + log.debug("comparing directory [" + f.getAbsolutePath() + + "] with the current latest directory of [" + + latest.getAbsolutePath() + "]"); + if (c.compare(latest, f) < 0) { + latest = f; + log.debug("directory [" + f.getAbsolutePath() + "] is now the latest"); + } + } + } else { + throw new PitError("could not list files in directory [" + + reportsDirectory.getAbsolutePath() + + "] because of an unknown I/O error"); + } + + log.debug("ReportSourceLocator determined directory [" + + latest.getAbsolutePath() + + "] is the directory containing the latest pit reports"); + return latest; + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/generator/HTMLReportGenerator.java b/pitest-maven/src/main/java/org/pitest/maven/report/generator/HTMLReportGenerator.java index 3a562e330..cc4e477fb 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/generator/HTMLReportGenerator.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/generator/HTMLReportGenerator.java @@ -1,60 +1,60 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -import java.io.FileFilter; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.NotFileFilter; -import org.apache.commons.io.filefilter.RegexFileFilter; - -public class HTMLReportGenerator implements ReportGenerationStrategy { - - protected static final FileFilter EXCLUDE_TIMESTAMPED_REPORTS_DIRECTORIES = new NotFileFilter( - new RegexFileFilter( - "^\\d+$")); - - @Override - public ReportGenerationResultEnum generate(ReportGenerationContext context) { - try { - context.getLogger().debug( - "HTMLReportGenerator using directory [" - + context.getReportsDataDirectory() - + "] as directory containing the html report"); - context.getLogger().debug( - "HTMLReportGenerator using directory [" + context.getSiteDirectory() - + "] as directory that is the destination of the site report"); - FileUtils.copyDirectory(context.getReportsDataDirectory(), - context.getSiteDirectory(), EXCLUDE_TIMESTAMPED_REPORTS_DIRECTORIES); - } catch (IOException e) { - context.getLogger().warn(e); - return ReportGenerationResultEnum.FAILURE; - } - - return ReportGenerationResultEnum.SUCCESS; - } - - @Override - public String getGeneratorName() { - return "HTMLReportGenerator"; - } - - @Override - public String getGeneratorDataFormat() { - return "HTML"; - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +import java.io.FileFilter; +import java.io.IOException; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.NotFileFilter; +import org.apache.commons.io.filefilter.RegexFileFilter; + +public class HTMLReportGenerator implements ReportGenerationStrategy { + + protected static final FileFilter EXCLUDE_TIMESTAMPED_REPORTS_DIRECTORIES = new NotFileFilter( + new RegexFileFilter( + "^\\d+$")); + + @Override + public ReportGenerationResultEnum generate(ReportGenerationContext context) { + try { + context.getLogger().debug( + "HTMLReportGenerator using directory [" + + context.getReportsDataDirectory() + + "] as directory containing the html report"); + context.getLogger().debug( + "HTMLReportGenerator using directory [" + context.getSiteDirectory() + + "] as directory that is the destination of the site report"); + FileUtils.copyDirectory(context.getReportsDataDirectory(), + context.getSiteDirectory(), EXCLUDE_TIMESTAMPED_REPORTS_DIRECTORIES); + } catch (IOException e) { + context.getLogger().warn(e); + return ReportGenerationResultEnum.FAILURE; + } + + return ReportGenerationResultEnum.SUCCESS; + } + + @Override + public String getGeneratorName() { + return "HTMLReportGenerator"; + } + + @Override + public String getGeneratorDataFormat() { + return "HTML"; + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationContext.java b/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationContext.java index 61714455a..1c8420d99 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationContext.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationContext.java @@ -1,104 +1,104 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -import java.io.File; -import java.util.List; -import java.util.Locale; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.maven.doxia.sink.Sink; -import org.apache.maven.plugin.logging.Log; - -public class ReportGenerationContext { - - private Locale locale; - private Sink sink; - private File reportsDataDirectory; - private File siteDirectory; - private Log logger; - private List sourceDataFormats; - - public ReportGenerationContext() { - - } - - public ReportGenerationContext(Locale locale, Sink sink, - File reportsDataDirectory, File siteDirectory, Log logger, - List sourceDataFormats) { - this.locale = locale; - this.sink = sink; - this.reportsDataDirectory = reportsDataDirectory; - this.siteDirectory = siteDirectory; - this.logger = logger; - this.sourceDataFormats = sourceDataFormats; - } - - public Locale getLocale() { - return this.locale; - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - public Sink getSink() { - return this.sink; - } - - public void setSink(Sink sink) { - this.sink = sink; - } - - public File getReportsDataDirectory() { - return this.reportsDataDirectory; - } - - public void setReportsDataDirectory(File reportsDataDirectory) { - this.reportsDataDirectory = reportsDataDirectory; - } - - public File getSiteDirectory() { - return this.siteDirectory; - } - - public void setSiteDirectory(File siteDirectory) { - this.siteDirectory = siteDirectory; - } - - public Log getLogger() { - return this.logger; - } - - public void setLogger(Log logger) { - this.logger = logger; - } - - public List getSourceDataFormats() { - return this.sourceDataFormats; - } - - public void setSourceDataFormats(List sourceDataFormats) { - this.sourceDataFormats = sourceDataFormats; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, - ToStringStyle.MULTI_LINE_STYLE); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +import java.io.File; +import java.util.List; +import java.util.Locale; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.apache.commons.lang.builder.ToStringStyle; +import org.apache.maven.doxia.sink.Sink; +import org.apache.maven.plugin.logging.Log; + +public class ReportGenerationContext { + + private Locale locale; + private Sink sink; + private File reportsDataDirectory; + private File siteDirectory; + private Log logger; + private List sourceDataFormats; + + public ReportGenerationContext() { + + } + + public ReportGenerationContext(Locale locale, Sink sink, + File reportsDataDirectory, File siteDirectory, Log logger, + List sourceDataFormats) { + this.locale = locale; + this.sink = sink; + this.reportsDataDirectory = reportsDataDirectory; + this.siteDirectory = siteDirectory; + this.logger = logger; + this.sourceDataFormats = sourceDataFormats; + } + + public Locale getLocale() { + return this.locale; + } + + public void setLocale(Locale locale) { + this.locale = locale; + } + + public Sink getSink() { + return this.sink; + } + + public void setSink(Sink sink) { + this.sink = sink; + } + + public File getReportsDataDirectory() { + return this.reportsDataDirectory; + } + + public void setReportsDataDirectory(File reportsDataDirectory) { + this.reportsDataDirectory = reportsDataDirectory; + } + + public File getSiteDirectory() { + return this.siteDirectory; + } + + public void setSiteDirectory(File siteDirectory) { + this.siteDirectory = siteDirectory; + } + + public Log getLogger() { + return this.logger; + } + + public void setLogger(Log logger) { + this.logger = logger; + } + + public List getSourceDataFormats() { + return this.sourceDataFormats; + } + + public void setSourceDataFormats(List sourceDataFormats) { + this.sourceDataFormats = sourceDataFormats; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, + ToStringStyle.MULTI_LINE_STYLE); + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationManager.java b/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationManager.java index 61ff95866..2103a92d7 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationManager.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationManager.java @@ -1,83 +1,83 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -import java.util.Arrays; -import java.util.List; - -import org.pitest.maven.report.ReportSourceLocator; -import org.pitest.util.PitError; - -public class ReportGenerationManager { - - private final ReportSourceLocator reportLocator; - private final List reportGenerationStrategyList; - - public ReportGenerationManager() { - this(new ReportSourceLocator(), Arrays.asList(new XMLReportGenerator(), - new HTMLReportGenerator())); - } - - public ReportGenerationManager(final ReportSourceLocator reportLocator, - final List reportGenerationStrategyList) { - this.reportLocator = reportLocator; - this.reportGenerationStrategyList = reportGenerationStrategyList; - } - - public void generateSiteReport(ReportGenerationContext context) { - ReportGenerationResultEnum result; - boolean successfulExecution = false; - - context.setReportsDataDirectory(this.reportLocator.locate( - context.getReportsDataDirectory(), context.getLogger())); - - context.getLogger().debug("starting execution of report generators"); - context.getLogger().debug("using report generation context: " + context); - - for (String dataFormat : context.getSourceDataFormats()) { - context.getLogger().debug( - "starting report generator for source data format [" + dataFormat - + "]"); - result = this.locateReportGenerationStrategy(dataFormat) - .generate(context); - context.getLogger().debug( - "result of report generator for source data format [" + dataFormat - + "] was [" + result.toString() + "]"); - if (result == ReportGenerationResultEnum.SUCCESS) { - successfulExecution = true; - break; - } - } - - if (!successfulExecution) { - throw new PitError("no report generators executed successfully"); - } - - context.getLogger().debug("finished execution of report generators"); - } - - private ReportGenerationStrategy locateReportGenerationStrategy( - String sourceDataFormat) { - for (ReportGenerationStrategy strategy : this.reportGenerationStrategyList) { - if (sourceDataFormat.equalsIgnoreCase(strategy.getGeneratorDataFormat())) { - return strategy; - } - } - - throw new PitError("Could not locate report generator for data source [" - + sourceDataFormat + "]"); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +import java.util.Arrays; +import java.util.List; + +import org.pitest.maven.report.ReportSourceLocator; +import org.pitest.util.PitError; + +public class ReportGenerationManager { + + private final ReportSourceLocator reportLocator; + private final List reportGenerationStrategyList; + + public ReportGenerationManager() { + this(new ReportSourceLocator(), Arrays.asList(new XMLReportGenerator(), + new HTMLReportGenerator())); + } + + public ReportGenerationManager(final ReportSourceLocator reportLocator, + final List reportGenerationStrategyList) { + this.reportLocator = reportLocator; + this.reportGenerationStrategyList = reportGenerationStrategyList; + } + + public void generateSiteReport(ReportGenerationContext context) { + ReportGenerationResultEnum result; + boolean successfulExecution = false; + + context.setReportsDataDirectory(this.reportLocator.locate( + context.getReportsDataDirectory(), context.getLogger())); + + context.getLogger().debug("starting execution of report generators"); + context.getLogger().debug("using report generation context: " + context); + + for (String dataFormat : context.getSourceDataFormats()) { + context.getLogger().debug( + "starting report generator for source data format [" + dataFormat + + "]"); + result = this.locateReportGenerationStrategy(dataFormat) + .generate(context); + context.getLogger().debug( + "result of report generator for source data format [" + dataFormat + + "] was [" + result.toString() + "]"); + if (result == ReportGenerationResultEnum.SUCCESS) { + successfulExecution = true; + break; + } + } + + if (!successfulExecution) { + throw new PitError("no report generators executed successfully"); + } + + context.getLogger().debug("finished execution of report generators"); + } + + private ReportGenerationStrategy locateReportGenerationStrategy( + String sourceDataFormat) { + for (ReportGenerationStrategy strategy : this.reportGenerationStrategyList) { + if (sourceDataFormat.equalsIgnoreCase(strategy.getGeneratorDataFormat())) { + return strategy; + } + } + + throw new PitError("Could not locate report generator for data source [" + + sourceDataFormat + "]"); + } + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationResultEnum.java b/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationResultEnum.java index f5d064e59..811b6e632 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationResultEnum.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationResultEnum.java @@ -1,21 +1,21 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -public enum ReportGenerationResultEnum { - - SUCCESS, FAILURE, NOT_EXECUTED - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +public enum ReportGenerationResultEnum { + + SUCCESS, FAILURE, NOT_EXECUTED + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationStrategy.java b/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationStrategy.java index e0d3bd6ef..06a50ae58 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationStrategy.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/generator/ReportGenerationStrategy.java @@ -1,25 +1,25 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -public interface ReportGenerationStrategy { - - ReportGenerationResultEnum generate(ReportGenerationContext context); - - String getGeneratorName(); - - String getGeneratorDataFormat(); - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +public interface ReportGenerationStrategy { + + ReportGenerationResultEnum generate(ReportGenerationContext context); + + String getGeneratorName(); + + String getGeneratorDataFormat(); + +} diff --git a/pitest-maven/src/main/java/org/pitest/maven/report/generator/XMLReportGenerator.java b/pitest-maven/src/main/java/org/pitest/maven/report/generator/XMLReportGenerator.java index 9e5c65e2d..536915deb 100644 --- a/pitest-maven/src/main/java/org/pitest/maven/report/generator/XMLReportGenerator.java +++ b/pitest-maven/src/main/java/org/pitest/maven/report/generator/XMLReportGenerator.java @@ -1,35 +1,35 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -public class XMLReportGenerator implements ReportGenerationStrategy { - - @Override - public ReportGenerationResultEnum generate(ReportGenerationContext context) { - context.getLogger().debug("XMLReportGenerator not yet implemented"); - return ReportGenerationResultEnum.NOT_EXECUTED; - } - - @Override - public String getGeneratorName() { - return "XMLReportGenerator"; - } - - @Override - public String getGeneratorDataFormat() { - return "XML"; - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +public class XMLReportGenerator implements ReportGenerationStrategy { + + @Override + public ReportGenerationResultEnum generate(ReportGenerationContext context) { + context.getLogger().debug("XMLReportGenerator not yet implemented"); + return ReportGenerationResultEnum.NOT_EXECUTED; + } + + @Override + public String getGeneratorName() { + return "XMLReportGenerator"; + } + + @Override + public String getGeneratorDataFormat() { + return "XML"; + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/BasePitMojoTest.java b/pitest-maven/src/test/java/org/pitest/maven/BasePitMojoTest.java index ce88fa975..0d6e6edc8 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/BasePitMojoTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/BasePitMojoTest.java @@ -1,134 +1,134 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven; - -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.AbstractMojoTestCase; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.configuration.PlexusConfiguration; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classpath.ClassPath; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.config.PluginServices; - -import edu.emory.mathcs.backport.java.util.Collections; - -public abstract class BasePitMojoTest extends AbstractMojoTestCase { - - @Mock - protected MavenProject project; - - @Mock - protected RunPitStrategy executionStrategy; - - protected List classPath; - - @Mock - protected Predicate filter; - - @Mock - protected PluginServices plugins; - - @Override - protected void setUp() throws Exception { - super.setUp(); - MockitoAnnotations.initMocks(this); - this.classPath = new ArrayList<>(FCollection.map( - ClassPath.getClassPathElementsAsFiles(), fileToString())); - when(this.project.getTestClasspathElements()).thenReturn(this.classPath); - when(this.project.getPackaging()).thenReturn("jar"); - - final Build build = new Build(); - build.setOutputDirectory(""); - - when(this.project.getBuild()).thenReturn(build); - - when(this.plugins.findToolClasspathPlugins()).thenReturn( - Collections.emptyList()); - when(this.plugins.findClientClasspathPlugins()).thenReturn( - Collections.emptyList()); - } - - private Function fileToString() { - return new Function() { - - @Override - public String apply(final File a) { - return a.getAbsolutePath(); - } - - }; - } - - protected String createPomWithConfiguration(final String config) { - final String pom = "\n" + // - " \n" + // - " \n" + // - " \n" + // - " org.pitest\n" + // - " pitest-maven\n" + // - " \n" + config + // - " \n" + // - " \n" + // - " \n" + // - " \n" + // - ""; - return pom; - } - - protected AbstractPitMojo createPITMojo(final String config) throws Exception { - final AbstractPitMojo pitMojo = new AbstractPitMojo(this.executionStrategy, this.filter, - this.plugins, p -> true); - configurePitMojo(pitMojo, config); - return pitMojo; - } - - protected void configurePitMojo(final AbstractPitMojo pitMojo, final String config) - throws Exception { - final Xpp3Dom xpp3dom = Xpp3DomBuilder.build(new StringReader(config)); - final PlexusConfiguration pluginConfiguration = extractPluginConfiguration( - "pitest-maven", xpp3dom); - - // default the report dir to something - setVariableValueToObject(pitMojo, "reportsDirectory", new File(".")); - - configureMojo(pitMojo, pluginConfiguration); - - final Map pluginArtifacts = new HashMap<>(); - setVariableValueToObject(pitMojo, "pluginArtifactMap", pluginArtifacts); - - setVariableValueToObject(pitMojo, "project", this.project); - - ArrayList elements = new ArrayList<>(); - setVariableValueToObject(pitMojo, "additionalClasspathElements", elements); - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven; + +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.configuration.PlexusConfiguration; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.codehaus.plexus.util.xml.Xpp3DomBuilder; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classpath.ClassPath; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.config.PluginServices; + +import edu.emory.mathcs.backport.java.util.Collections; + +public abstract class BasePitMojoTest extends AbstractMojoTestCase { + + @Mock + protected MavenProject project; + + @Mock + protected RunPitStrategy executionStrategy; + + protected List classPath; + + @Mock + protected Predicate filter; + + @Mock + protected PluginServices plugins; + + @Override + protected void setUp() throws Exception { + super.setUp(); + MockitoAnnotations.initMocks(this); + this.classPath = new ArrayList<>(FCollection.map( + ClassPath.getClassPathElementsAsFiles(), fileToString())); + when(this.project.getTestClasspathElements()).thenReturn(this.classPath); + when(this.project.getPackaging()).thenReturn("jar"); + + final Build build = new Build(); + build.setOutputDirectory(""); + + when(this.project.getBuild()).thenReturn(build); + + when(this.plugins.findToolClasspathPlugins()).thenReturn( + Collections.emptyList()); + when(this.plugins.findClientClasspathPlugins()).thenReturn( + Collections.emptyList()); + } + + private Function fileToString() { + return new Function() { + + @Override + public String apply(final File a) { + return a.getAbsolutePath(); + } + + }; + } + + protected String createPomWithConfiguration(final String config) { + final String pom = "\n" + // + " \n" + // + " \n" + // + " \n" + // + " org.pitest\n" + // + " pitest-maven\n" + // + " \n" + config + // + " \n" + // + " \n" + // + " \n" + // + " \n" + // + ""; + return pom; + } + + protected AbstractPitMojo createPITMojo(final String config) throws Exception { + final AbstractPitMojo pitMojo = new AbstractPitMojo(this.executionStrategy, this.filter, + this.plugins, p -> true); + configurePitMojo(pitMojo, config); + return pitMojo; + } + + protected void configurePitMojo(final AbstractPitMojo pitMojo, final String config) + throws Exception { + final Xpp3Dom xpp3dom = Xpp3DomBuilder.build(new StringReader(config)); + final PlexusConfiguration pluginConfiguration = extractPluginConfiguration( + "pitest-maven", xpp3dom); + + // default the report dir to something + setVariableValueToObject(pitMojo, "reportsDirectory", new File(".")); + + configureMojo(pitMojo, pluginConfiguration); + + final Map pluginArtifacts = new HashMap<>(); + setVariableValueToObject(pitMojo, "pluginArtifactMap", pluginArtifacts); + + setVariableValueToObject(pitMojo, "project", this.project); + + ArrayList elements = new ArrayList<>(); + setVariableValueToObject(pitMojo, "additionalClasspathElements", elements); + + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/DependencyFilterIT.java b/pitest-maven/src/test/java/org/pitest/maven/DependencyFilterIT.java index 30dfc5d4d..0dd6f20d3 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/DependencyFilterIT.java +++ b/pitest-maven/src/test/java/org/pitest/maven/DependencyFilterIT.java @@ -1,57 +1,57 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import org.apache.maven.artifact.Artifact; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.mutationtest.config.PluginServices; - -@Category(SystemTest.class) -public class DependencyFilterIT { - - private DependencyFilter testee; - - @Mock - private Artifact artifact; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new DependencyFilter(PluginServices.makeForContextLoader()); - } - - @Test - public void shouldAllowPitestCore() { - when(this.artifact.getGroupId()).thenReturn("org.pitest"); - when(this.artifact.getArtifactId()).thenReturn("pitest"); - assertTrue(this.testee.test(this.artifact)); - } - - @Test - public void shouldNotAllowHtmlReport() { - when(this.artifact.getGroupId()).thenReturn("org.pitest"); - when(this.artifact.getArtifactId()).thenReturn("pitest-html-report"); - assertFalse(this.testee.test(this.artifact)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import org.apache.maven.artifact.Artifact; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.mutationtest.config.PluginServices; + +@Category(SystemTest.class) +public class DependencyFilterIT { + + private DependencyFilter testee; + + @Mock + private Artifact artifact; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new DependencyFilter(PluginServices.makeForContextLoader()); + } + + @Test + public void shouldAllowPitestCore() { + when(this.artifact.getGroupId()).thenReturn("org.pitest"); + when(this.artifact.getArtifactId()).thenReturn("pitest"); + assertTrue(this.testee.test(this.artifact)); + } + + @Test + public void shouldNotAllowHtmlReport() { + when(this.artifact.getGroupId()).thenReturn("org.pitest"); + when(this.artifact.getArtifactId()).thenReturn("pitest-html-report"); + assertFalse(this.testee.test(this.artifact)); + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/MojoToReportOptionsConverterTest.java b/pitest-maven/src/test/java/org/pitest/maven/MojoToReportOptionsConverterTest.java index ac20d5193..c45a710e9 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/MojoToReportOptionsConverterTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/MojoToReportOptionsConverterTest.java @@ -1,396 +1,396 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.AdditionalAnswers.returnsFirstArg; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.model.Build; -import org.apache.maven.model.Model; -import org.apache.maven.model.Plugin; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.mockito.Mockito; -import java.util.function.Predicate; -import org.pitest.mutationtest.config.ConfigOption; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.util.Unchecked; - -public class MojoToReportOptionsConverterTest extends BasePitMojoTest { - - private MojoToReportOptionsConverter testee; - private SurefireConfigConverter surefireConverter; - - @Override - public void setUp() throws Exception { - super.setUp(); - Plugin surefire = new Plugin(); - surefire.setGroupId("org.apache.maven.plugins"); - surefire.setArtifactId("maven-surefire-plugin"); - this.surefireConverter = Mockito.mock(SurefireConfigConverter.class); - List mavenPlugins = Collections.singletonList(surefire); - when(this.project.getBuildPlugins()).thenReturn(mavenPlugins); - Build build = new Build(); - build.setOutputDirectory(""); - when(this.project.getBuild()).thenReturn(build); - } - - public void testsParsesReportDir() { - final ReportOptions actual = parseConfig("Foo"); - assertEquals(new File("Foo").getAbsolutePath(), actual.getReportDir()); - } - - public void testCreatesPredicateFromListOfTargetClassGlobs() { - final String xml = "" + // - " foo*" + // - " bar*" + // - " "; - - final ReportOptions actual = parseConfig(xml); - final Predicate actualPredicate = actual.getTargetClassesFilter(); - assertTrue(actualPredicate.test("foo_anything")); - assertTrue(actualPredicate.test("bar_anything")); - assertFalse(actualPredicate.test("notfoobar")); - } - - public void testUsesSourceDirectoriesFromProject() { - when(this.project.getCompileSourceRoots()).thenReturn(Arrays.asList("src")); - when(this.project.getTestCompileSourceRoots()).thenReturn( - Arrays.asList("tst")); - final ReportOptions actual = parseConfig(""); - assertEquals(Arrays.asList(new File("src"), new File("tst")), - actual.getSourceDirs()); - } - - public void testParsesMaxDependencyDistance() { - final ReportOptions actual = parseConfig("42"); - assertEquals(42, actual.getDependencyAnalysisMaxDistance()); - } - - public void testParsesExcludedRunners() { - String runner = "org.springframework.test.context.junit4.SpringJUnit4ClassRunner"; - final ReportOptions actual = parseConfig("" + runner + ""); - assertThat(actual.getExcludedRunners()).hasSize(1).containsExactly(runner); - } - - public void testParsesListOfJVMArgs() { - final String xml = "" + // - " foo" + // - " bar" + // - " "; - final ReportOptions actual = parseConfig(xml); - assertEquals(Arrays.asList("foo", "bar"), actual.getJvmArgs()); - } - - public void testParsesListOfMutationOperators() { - final String xml = "" + // - " foo" + // - " bar" + // - " "; - final ReportOptions actual = parseConfig(xml); - assertEquals(Arrays.asList("foo", "bar"), actual.getMutators()); - } - - public void testParsesListOfFeatures() { - final String xml = "" + // - " +FOO" + // - " -BAR(foo[1] bar[3])" + // - " "; - final ReportOptions actual = parseConfig(xml); - assertThat(actual.getFeatures()).contains("+FOO", "-BAR(foo[1] bar[3])"); - } - - - public void testParsesNumberOfThreads() { - final ReportOptions actual = parseConfig("42"); - assertEquals(42, actual.getNumberOfThreads()); - } - - public void testParsesTimeOutFactor() { - final ReportOptions actual = parseConfig("1.32"); - assertEquals(1.32f, actual.getTimeoutFactor(), 0.1); - } - - public void testParsesTimeOutConstant() { - final ReportOptions actual = parseConfig("42"); - assertEquals(42, actual.getTimeoutConstant()); - } - - public void testParsesListOfTargetTestClassGlobs() { - final String xml = "" + // - " foo*" + // - " bar*" + // - " "; - final ReportOptions actual = parseConfig(xml); - final Predicate actualPredicate = actual.getTargetTestsFilter(); - assertTrue(actualPredicate.test("foo_anything")); - assertTrue(actualPredicate.test("bar_anything")); - assertFalse(actualPredicate.test("notfoobar")); - } - - public void testParsesListOfExcludedTestClassGlobs() { - final String xml = "" + // - " foo*" + // - " " + // - " " + // - " foo*" + // - " bar*" + // - " "; - final ReportOptions actual = parseConfig(xml); - final Predicate testPredicate = actual.getTargetTestsFilter(); - assertFalse(testPredicate.test("foo_anything")); - assertTrue(testPredicate.test("bar_anything")); - } - - public void testParsesListOfExcludedClassGlobsAndApplyTheseToTargets() { - final String xml = "" + // - " foo*" + // - " " + // - " " + // - " foo*" + // - " bar*" + // - " "; - final ReportOptions actual = parseConfig(xml); - final Predicate targetPredicate = actual.getTargetClassesFilter(); - assertFalse(targetPredicate.test("foo_anything")); - assertTrue(targetPredicate.test("bar_anything")); - } - - public void testDefaultsLoggingPackagesToDefaultsDefinedByDefaultMutationConfigFactory() { - final ReportOptions actual = parseConfig(""); - assertEquals(ReportOptions.LOGGING_CLASSES, actual.getLoggingClasses()); - } - - public void testParsesListOfClassesToAvoidCallTo() { - final String xml = "" + // - " foo" + // - " bar" + // - " foo.bar" + // - " "; - final ReportOptions actual = parseConfig(xml); - assertEquals(Arrays.asList("foo", "bar", "foo.bar"), - actual.getLoggingClasses()); - } - - public void testParsesCommaListOfExcludedMethods() { - final String xml = "" + // - " foo*" + // - " bar*" + // - " car" + // - " "; - final ReportOptions options = parseConfig(xml); - final Collection actual = options.getExcludedMethods(); - assertThat(actual).containsExactlyInAnyOrder("foo*", "bar*", "car"); - } - - public void testParsesVerboseFlag() { - assertTrue(parseConfig("true").isVerbose()); - assertFalse(parseConfig("false").isVerbose()); - } - - public void testParsesDetectInlineCodeFlag() { - assertTrue(parseConfig("true") - .isDetectInlinedCode()); - assertFalse(parseConfig("false") - .isDetectInlinedCode()); - } - - public void testDefaultsToHtmlReportWhenNoOutputFormatsSpecified() { - final ReportOptions actual = parseConfig(""); - assertEquals(new HashSet<>(Arrays.asList("HTML")), - actual.getOutputFormats()); - } - - public void testParsesListOfOutputFormatsWhenSupplied() { - final String xml = "" + // - " HTML" + // - " CSV" + // - " "; - final ReportOptions actual = parseConfig(xml); - assertEquals(new HashSet<>(Arrays.asList("HTML", "CSV")), - actual.getOutputFormats()); - } - - public void testObeysFailWhenNoMutationsFlagWhenPackagingTypeIsNotPOM() { - when(this.project.getModel()).thenReturn(new Model()); - assertTrue(parseConfig("true") - .shouldFailWhenNoMutations()); - assertFalse(parseConfig("false") - .shouldFailWhenNoMutations()); - } - - public void testParsesTestGroupsToExclude() { - final ReportOptions actual = parseConfig("foobar"); - assertEquals(Arrays.asList("foo", "bar"), actual.getGroupConfig() - .getExcludedGroups()); - } - - public void testParsesTestGroupsToInclude() { - final ReportOptions actual = parseConfig("foobar"); - assertEquals(Arrays.asList("foo", "bar"), actual.getGroupConfig() - .getIncludedGroups()); - } - - public void testParsesTestMethodsToInclude() { - final ReportOptions actual = parseConfig("foobar"); - assertEquals(Arrays.asList("foo", "bar"), actual - .getIncludedTestMethods()); - } - - public void testMaintainsOrderOfClassPath() { - final ReportOptions actual = parseConfig("foobar"); - assertEquals(this.classPath, actual.getClassPathElements()); - } - - public void testParsesMutationUnitSize() { - final ReportOptions actual = parseConfig("50"); - assertEquals(50, actual.getMutationUnitSize()); - } - - public void testDefaultsMutationUnitSizeToCorrectValue() { - final ReportOptions actual = parseConfig(""); - assertEquals( - (int) ConfigOption.MUTATION_UNIT_SIZE.getDefault(Integer.class), - actual.getMutationUnitSize()); - } - - public void testParsesTimeStampedReports() { - final ReportOptions actual = parseConfig("false"); - assertEquals(false, actual.shouldCreateTimeStampedReports()); - } - - public void testParsesHistoryInputFile() { - final ReportOptions actual = parseConfig("foo"); - assertEquals(new File("foo"), actual.getHistoryInputLocation()); - } - - public void testParsesHistoryOutputFile() { - final ReportOptions actual = parseConfig("foo"); - assertEquals(new File("foo"), actual.getHistoryOutputLocation()); - } - - public void testParsesLocalHistoryFlag() { - when(this.project.getGroupId()).thenReturn("com.example"); - when(this.project.getArtifactId()).thenReturn("foo"); - when(this.project.getVersion()).thenReturn("0.1-SNAPSHOT"); - final ReportOptions actual = parseConfig("true"); - String expected = "com.example.foo.0.1-SNAPSHOT_pitest_history.bin"; - assertThat(actual.getHistoryInputLocation().getAbsolutePath()).endsWith(expected); - } - - public void testParsesLineCoverageExportFlagWhenSet() { - final ReportOptions actual = parseConfig("true"); - assertTrue(actual.shouldExportLineCoverage()); - } - - public void testParsesLineCoverageExportFlagWhenNotSet() { - final ReportOptions actual = parseConfig("false"); - assertFalse(actual.shouldExportLineCoverage()); - } - - public void testParsesEngineWhenSet() { - final ReportOptions actual = parseConfig("foo"); - assertEquals("foo", actual.getMutationEngine()); - } - - public void testDefaultsJavaExecutableToNull() { - final ReportOptions actual = parseConfig(""); - assertEquals(null, actual.getJavaExecutable()); - } - - public void testParsesJavaExecutable() { - final ReportOptions actual = parseConfig("foo"); - assertEquals("foo", actual.getJavaExecutable()); - } - - public void testParsesExcludedClasspathElements() - throws DependencyResolutionRequiredException { - final String sep = File.pathSeparator; - - final Set artifacts = new HashSet<>(); - final Artifact dependency = Mockito.mock(Artifact.class); - when(dependency.getGroupId()).thenReturn("group"); - when(dependency.getArtifactId()).thenReturn("artifact"); - when(dependency.getFile()).thenReturn( - new File("group" + sep + "artifact" + sep + "1.0.0" + sep - + "group-artifact-1.0.0.jar")); - artifacts.add(dependency); - when(this.project.getArtifacts()).thenReturn(artifacts); - when(this.project.getTestClasspathElements()).thenReturn( - Arrays.asList("group" + sep + "artifact" + sep + "1.0.0" + sep - + "group-artifact-1.0.0.jar")); - - final ReportOptions actual = parseConfig("" - + " group:artifact" - + " "); - assertFalse(actual.getClassPathElements().contains( - "group" + sep + "artifact" + sep + "1.0.0" + sep - + "group-artifact-1.0.0.jar")); - } - - public void testParsesSurefireConfigWhenFlagSet() { - parseConfig("true"); - verify(this.surefireConverter).update(any(ReportOptions.class), - any(Xpp3Dom.class)); - } - - public void testIgnoreSurefireConfigWhenFlagNotSet() { - parseConfig("false"); - verify(this.surefireConverter, never()).update(any(ReportOptions.class), - any(Xpp3Dom.class)); - } - - public void testParsesCustomProperties() { - final ReportOptions actual = parseConfig("foobar"); - assertEquals("foo", actual.getFreeFormProperties().get("foo")); - assertEquals("bar", actual.getFreeFormProperties().get("bar")); - } - - public void testParsesTestPlugin() { - final ReportOptions actual = parseConfig("testng"); - assertEquals("testng", actual.getTestPlugin()); - } - - private ReportOptions parseConfig(final String xml) { - try { - final String pom = createPomWithConfiguration(xml); - final AbstractPitMojo mojo = createPITMojo(pom); - Predicate filter = Mockito.mock(Predicate.class); - when( - this.surefireConverter.update(any(ReportOptions.class), - any(Xpp3Dom.class))).then(returnsFirstArg()); - this.testee = new MojoToReportOptionsConverter(mojo, - this.surefireConverter, filter); - final ReportOptions actual = this.testee.convert(); - return actual; - } catch (final Exception ex) { - throw Unchecked.translateCheckedException(ex); - } - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DependencyResolutionRequiredException; +import org.apache.maven.model.Build; +import org.apache.maven.model.Model; +import org.apache.maven.model.Plugin; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.mockito.Mockito; +import java.util.function.Predicate; +import org.pitest.mutationtest.config.ConfigOption; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.util.Unchecked; + +public class MojoToReportOptionsConverterTest extends BasePitMojoTest { + + private MojoToReportOptionsConverter testee; + private SurefireConfigConverter surefireConverter; + + @Override + public void setUp() throws Exception { + super.setUp(); + Plugin surefire = new Plugin(); + surefire.setGroupId("org.apache.maven.plugins"); + surefire.setArtifactId("maven-surefire-plugin"); + this.surefireConverter = Mockito.mock(SurefireConfigConverter.class); + List mavenPlugins = Collections.singletonList(surefire); + when(this.project.getBuildPlugins()).thenReturn(mavenPlugins); + Build build = new Build(); + build.setOutputDirectory(""); + when(this.project.getBuild()).thenReturn(build); + } + + public void testsParsesReportDir() { + final ReportOptions actual = parseConfig("Foo"); + assertEquals(new File("Foo").getAbsolutePath(), actual.getReportDir()); + } + + public void testCreatesPredicateFromListOfTargetClassGlobs() { + final String xml = "" + // + " foo*" + // + " bar*" + // + " "; + + final ReportOptions actual = parseConfig(xml); + final Predicate actualPredicate = actual.getTargetClassesFilter(); + assertTrue(actualPredicate.test("foo_anything")); + assertTrue(actualPredicate.test("bar_anything")); + assertFalse(actualPredicate.test("notfoobar")); + } + + public void testUsesSourceDirectoriesFromProject() { + when(this.project.getCompileSourceRoots()).thenReturn(Arrays.asList("src")); + when(this.project.getTestCompileSourceRoots()).thenReturn( + Arrays.asList("tst")); + final ReportOptions actual = parseConfig(""); + assertEquals(Arrays.asList(new File("src"), new File("tst")), + actual.getSourceDirs()); + } + + public void testParsesMaxDependencyDistance() { + final ReportOptions actual = parseConfig("42"); + assertEquals(42, actual.getDependencyAnalysisMaxDistance()); + } + + public void testParsesExcludedRunners() { + String runner = "org.springframework.test.context.junit4.SpringJUnit4ClassRunner"; + final ReportOptions actual = parseConfig("" + runner + ""); + assertThat(actual.getExcludedRunners()).hasSize(1).containsExactly(runner); + } + + public void testParsesListOfJVMArgs() { + final String xml = "" + // + " foo" + // + " bar" + // + " "; + final ReportOptions actual = parseConfig(xml); + assertEquals(Arrays.asList("foo", "bar"), actual.getJvmArgs()); + } + + public void testParsesListOfMutationOperators() { + final String xml = "" + // + " foo" + // + " bar" + // + " "; + final ReportOptions actual = parseConfig(xml); + assertEquals(Arrays.asList("foo", "bar"), actual.getMutators()); + } + + public void testParsesListOfFeatures() { + final String xml = "" + // + " +FOO" + // + " -BAR(foo[1] bar[3])" + // + " "; + final ReportOptions actual = parseConfig(xml); + assertThat(actual.getFeatures()).contains("+FOO", "-BAR(foo[1] bar[3])"); + } + + + public void testParsesNumberOfThreads() { + final ReportOptions actual = parseConfig("42"); + assertEquals(42, actual.getNumberOfThreads()); + } + + public void testParsesTimeOutFactor() { + final ReportOptions actual = parseConfig("1.32"); + assertEquals(1.32f, actual.getTimeoutFactor(), 0.1); + } + + public void testParsesTimeOutConstant() { + final ReportOptions actual = parseConfig("42"); + assertEquals(42, actual.getTimeoutConstant()); + } + + public void testParsesListOfTargetTestClassGlobs() { + final String xml = "" + // + " foo*" + // + " bar*" + // + " "; + final ReportOptions actual = parseConfig(xml); + final Predicate actualPredicate = actual.getTargetTestsFilter(); + assertTrue(actualPredicate.test("foo_anything")); + assertTrue(actualPredicate.test("bar_anything")); + assertFalse(actualPredicate.test("notfoobar")); + } + + public void testParsesListOfExcludedTestClassGlobs() { + final String xml = "" + // + " foo*" + // + " " + // + " " + // + " foo*" + // + " bar*" + // + " "; + final ReportOptions actual = parseConfig(xml); + final Predicate testPredicate = actual.getTargetTestsFilter(); + assertFalse(testPredicate.test("foo_anything")); + assertTrue(testPredicate.test("bar_anything")); + } + + public void testParsesListOfExcludedClassGlobsAndApplyTheseToTargets() { + final String xml = "" + // + " foo*" + // + " " + // + " " + // + " foo*" + // + " bar*" + // + " "; + final ReportOptions actual = parseConfig(xml); + final Predicate targetPredicate = actual.getTargetClassesFilter(); + assertFalse(targetPredicate.test("foo_anything")); + assertTrue(targetPredicate.test("bar_anything")); + } + + public void testDefaultsLoggingPackagesToDefaultsDefinedByDefaultMutationConfigFactory() { + final ReportOptions actual = parseConfig(""); + assertEquals(ReportOptions.LOGGING_CLASSES, actual.getLoggingClasses()); + } + + public void testParsesListOfClassesToAvoidCallTo() { + final String xml = "" + // + " foo" + // + " bar" + // + " foo.bar" + // + " "; + final ReportOptions actual = parseConfig(xml); + assertEquals(Arrays.asList("foo", "bar", "foo.bar"), + actual.getLoggingClasses()); + } + + public void testParsesCommaListOfExcludedMethods() { + final String xml = "" + // + " foo*" + // + " bar*" + // + " car" + // + " "; + final ReportOptions options = parseConfig(xml); + final Collection actual = options.getExcludedMethods(); + assertThat(actual).containsExactlyInAnyOrder("foo*", "bar*", "car"); + } + + public void testParsesVerboseFlag() { + assertTrue(parseConfig("true").isVerbose()); + assertFalse(parseConfig("false").isVerbose()); + } + + public void testParsesDetectInlineCodeFlag() { + assertTrue(parseConfig("true") + .isDetectInlinedCode()); + assertFalse(parseConfig("false") + .isDetectInlinedCode()); + } + + public void testDefaultsToHtmlReportWhenNoOutputFormatsSpecified() { + final ReportOptions actual = parseConfig(""); + assertEquals(new HashSet<>(Arrays.asList("HTML")), + actual.getOutputFormats()); + } + + public void testParsesListOfOutputFormatsWhenSupplied() { + final String xml = "" + // + " HTML" + // + " CSV" + // + " "; + final ReportOptions actual = parseConfig(xml); + assertEquals(new HashSet<>(Arrays.asList("HTML", "CSV")), + actual.getOutputFormats()); + } + + public void testObeysFailWhenNoMutationsFlagWhenPackagingTypeIsNotPOM() { + when(this.project.getModel()).thenReturn(new Model()); + assertTrue(parseConfig("true") + .shouldFailWhenNoMutations()); + assertFalse(parseConfig("false") + .shouldFailWhenNoMutations()); + } + + public void testParsesTestGroupsToExclude() { + final ReportOptions actual = parseConfig("foobar"); + assertEquals(Arrays.asList("foo", "bar"), actual.getGroupConfig() + .getExcludedGroups()); + } + + public void testParsesTestGroupsToInclude() { + final ReportOptions actual = parseConfig("foobar"); + assertEquals(Arrays.asList("foo", "bar"), actual.getGroupConfig() + .getIncludedGroups()); + } + + public void testParsesTestMethodsToInclude() { + final ReportOptions actual = parseConfig("foobar"); + assertEquals(Arrays.asList("foo", "bar"), actual + .getIncludedTestMethods()); + } + + public void testMaintainsOrderOfClassPath() { + final ReportOptions actual = parseConfig("foobar"); + assertEquals(this.classPath, actual.getClassPathElements()); + } + + public void testParsesMutationUnitSize() { + final ReportOptions actual = parseConfig("50"); + assertEquals(50, actual.getMutationUnitSize()); + } + + public void testDefaultsMutationUnitSizeToCorrectValue() { + final ReportOptions actual = parseConfig(""); + assertEquals( + (int) ConfigOption.MUTATION_UNIT_SIZE.getDefault(Integer.class), + actual.getMutationUnitSize()); + } + + public void testParsesTimeStampedReports() { + final ReportOptions actual = parseConfig("false"); + assertEquals(false, actual.shouldCreateTimeStampedReports()); + } + + public void testParsesHistoryInputFile() { + final ReportOptions actual = parseConfig("foo"); + assertEquals(new File("foo"), actual.getHistoryInputLocation()); + } + + public void testParsesHistoryOutputFile() { + final ReportOptions actual = parseConfig("foo"); + assertEquals(new File("foo"), actual.getHistoryOutputLocation()); + } + + public void testParsesLocalHistoryFlag() { + when(this.project.getGroupId()).thenReturn("com.example"); + when(this.project.getArtifactId()).thenReturn("foo"); + when(this.project.getVersion()).thenReturn("0.1-SNAPSHOT"); + final ReportOptions actual = parseConfig("true"); + String expected = "com.example.foo.0.1-SNAPSHOT_pitest_history.bin"; + assertThat(actual.getHistoryInputLocation().getAbsolutePath()).endsWith(expected); + } + + public void testParsesLineCoverageExportFlagWhenSet() { + final ReportOptions actual = parseConfig("true"); + assertTrue(actual.shouldExportLineCoverage()); + } + + public void testParsesLineCoverageExportFlagWhenNotSet() { + final ReportOptions actual = parseConfig("false"); + assertFalse(actual.shouldExportLineCoverage()); + } + + public void testParsesEngineWhenSet() { + final ReportOptions actual = parseConfig("foo"); + assertEquals("foo", actual.getMutationEngine()); + } + + public void testDefaultsJavaExecutableToNull() { + final ReportOptions actual = parseConfig(""); + assertEquals(null, actual.getJavaExecutable()); + } + + public void testParsesJavaExecutable() { + final ReportOptions actual = parseConfig("foo"); + assertEquals("foo", actual.getJavaExecutable()); + } + + public void testParsesExcludedClasspathElements() + throws DependencyResolutionRequiredException { + final String sep = File.pathSeparator; + + final Set artifacts = new HashSet<>(); + final Artifact dependency = Mockito.mock(Artifact.class); + when(dependency.getGroupId()).thenReturn("group"); + when(dependency.getArtifactId()).thenReturn("artifact"); + when(dependency.getFile()).thenReturn( + new File("group" + sep + "artifact" + sep + "1.0.0" + sep + + "group-artifact-1.0.0.jar")); + artifacts.add(dependency); + when(this.project.getArtifacts()).thenReturn(artifacts); + when(this.project.getTestClasspathElements()).thenReturn( + Arrays.asList("group" + sep + "artifact" + sep + "1.0.0" + sep + + "group-artifact-1.0.0.jar")); + + final ReportOptions actual = parseConfig("" + + " group:artifact" + + " "); + assertFalse(actual.getClassPathElements().contains( + "group" + sep + "artifact" + sep + "1.0.0" + sep + + "group-artifact-1.0.0.jar")); + } + + public void testParsesSurefireConfigWhenFlagSet() { + parseConfig("true"); + verify(this.surefireConverter).update(any(ReportOptions.class), + any(Xpp3Dom.class)); + } + + public void testIgnoreSurefireConfigWhenFlagNotSet() { + parseConfig("false"); + verify(this.surefireConverter, never()).update(any(ReportOptions.class), + any(Xpp3Dom.class)); + } + + public void testParsesCustomProperties() { + final ReportOptions actual = parseConfig("foobar"); + assertEquals("foo", actual.getFreeFormProperties().get("foo")); + assertEquals("bar", actual.getFreeFormProperties().get("bar")); + } + + public void testParsesTestPlugin() { + final ReportOptions actual = parseConfig("testng"); + assertEquals("testng", actual.getTestPlugin()); + } + + private ReportOptions parseConfig(final String xml) { + try { + final String pom = createPomWithConfiguration(xml); + final AbstractPitMojo mojo = createPITMojo(pom); + Predicate filter = Mockito.mock(Predicate.class); + when( + this.surefireConverter.update(any(ReportOptions.class), + any(Xpp3Dom.class))).then(returnsFirstArg()); + this.testee = new MojoToReportOptionsConverter(mojo, + this.surefireConverter, filter); + final ReportOptions actual = this.testee.convert(); + return actual; + } catch (final Exception ex) { + throw Unchecked.translateCheckedException(ex); + } + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/NonEmptyProjectCheckIT.java b/pitest-maven/src/test/java/org/pitest/maven/NonEmptyProjectCheckIT.java index 6ad83f0a6..ae37d2228 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/NonEmptyProjectCheckIT.java +++ b/pitest-maven/src/test/java/org/pitest/maven/NonEmptyProjectCheckIT.java @@ -1,60 +1,60 @@ -package org.pitest.maven; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Collections; - -import org.apache.maven.project.MavenProject; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -@Category(SystemTest.class) -@RunWith(MockitoJUnitRunner.class) -public class NonEmptyProjectCheckIT { - - @Rule - public TemporaryFolder realDir = new TemporaryFolder(); - - NonEmptyProjectCheck testee = new NonEmptyProjectCheck(); - - @Mock - private MavenProject project; - - @Test - public void shouldTreatProjectWithCodeAndTestsAsNonEmpty() { - when(project.getTestCompileSourceRoots()).thenReturn(Collections.singletonList(dirThatExists())); - when(project.getCompileSourceRoots()).thenReturn(Collections.singletonList(dirThatExists())); - assertThat(testee.test(project)).isTrue(); - } - - @Test - public void shouldTreatProjectWithNoTestsAsEmpty() { - when(project.getTestCompileSourceRoots()).thenReturn(Collections.singletonList(dirThatExists())); - when(project.getCompileSourceRoots()).thenReturn(Collections.singletonList(nonExistentDir())); - assertThat(testee.test(project)).isFalse(); - } - - @Test - public void shouldTreatProjectWithNoCodeAsEmpty() { - when(project.getTestCompileSourceRoots()).thenReturn(Collections.singletonList(nonExistentDir())); - when(project.getCompileSourceRoots()).thenReturn(Collections.singletonList(dirThatExists())); - assertThat(testee.test(project)).isFalse(); - } - - private String dirThatExists() { - return realDir.getRoot().getAbsolutePath(); - } - - private String nonExistentDir() { - return new File("ifthisfileexistsbybizarrechancethetestwillfail").getAbsolutePath(); - } - - -} +package org.pitest.maven; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Collections; + +import org.apache.maven.project.MavenProject; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +@Category(SystemTest.class) +@RunWith(MockitoJUnitRunner.class) +public class NonEmptyProjectCheckIT { + + @Rule + public TemporaryFolder realDir = new TemporaryFolder(); + + NonEmptyProjectCheck testee = new NonEmptyProjectCheck(); + + @Mock + private MavenProject project; + + @Test + public void shouldTreatProjectWithCodeAndTestsAsNonEmpty() { + when(project.getTestCompileSourceRoots()).thenReturn(Collections.singletonList(dirThatExists())); + when(project.getCompileSourceRoots()).thenReturn(Collections.singletonList(dirThatExists())); + assertThat(testee.test(project)).isTrue(); + } + + @Test + public void shouldTreatProjectWithNoTestsAsEmpty() { + when(project.getTestCompileSourceRoots()).thenReturn(Collections.singletonList(dirThatExists())); + when(project.getCompileSourceRoots()).thenReturn(Collections.singletonList(nonExistentDir())); + assertThat(testee.test(project)).isFalse(); + } + + @Test + public void shouldTreatProjectWithNoCodeAsEmpty() { + when(project.getTestCompileSourceRoots()).thenReturn(Collections.singletonList(nonExistentDir())); + when(project.getCompileSourceRoots()).thenReturn(Collections.singletonList(dirThatExists())); + assertThat(testee.test(project)).isFalse(); + } + + private String dirThatExists() { + return realDir.getRoot().getAbsolutePath(); + } + + private String nonExistentDir() { + return new File("ifthisfileexistsbybizarrechancethetestwillfail").getAbsolutePath(); + } + + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/PathToJavaClassConverterTest.java b/pitest-maven/src/test/java/org/pitest/maven/PathToJavaClassConverterTest.java index 6819c0fc2..b8bf093b0 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/PathToJavaClassConverterTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/PathToJavaClassConverterTest.java @@ -1,63 +1,63 @@ -package org.pitest.maven; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; - -import org.junit.Test; - -public class PathToJavaClassConverterTest { - - private static final String SRC = new File("src/java") - .getAbsolutePath(); - private final PathToJavaClassConverter testee = new PathToJavaClassConverter( - SRC); - - @Test - public void shouldReturnNoMatchedForFilesNotUnderSourceTree() { - assertFalse(this.testee.apply("not/under/source/tree/File.java").iterator() - .hasNext()); - } - - @Test - public void shouldConvertFileInPackageDefaultToJavaClassName() { - assertEquals("InDefault*", apply("InDefault.java")); - } - - @Test - public void shouldConvertFileInPackageToJavaClassName() { - assertEquals("com.example.Class*", apply("com/example/Class.java")); - } - - @Test - public void shouldConvertFilesWithOddCaseExtensionsToJavaClassName() { - assertEquals("com.example.Class*", apply("com/example/Class.JaVa")); - } - - @Test - public void shouldNotConvertFilesWithoutExtension() { - assertFalse(this.testee.apply(SRC + "/File").iterator().hasNext()); - } - - @Test - public void shouldConvertFilesWithDotInPath() { - assertTrue(this.testee.apply(SRC + "/foo.bar/File.java").iterator() - .hasNext()); - } - - @Test - public void shouldIncludeWildCardInGeneratedGlobToCatchInnerClasses() { - assertTrue(apply("foo.java").endsWith("*")); - } - - @Test - public void shouldConvertBackslashPathsRegardlessOfOs() { - assertEquals("com.example.Class*", apply("com\\example\\Class.java")); - } - - private String apply(final String value) { - return this.testee.apply(SRC + "/" + value).iterator().next(); - } -} +package org.pitest.maven; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Test; + +public class PathToJavaClassConverterTest { + + private static final String SRC = new File("src/java") + .getAbsolutePath(); + private final PathToJavaClassConverter testee = new PathToJavaClassConverter( + SRC); + + @Test + public void shouldReturnNoMatchedForFilesNotUnderSourceTree() { + assertFalse(this.testee.apply("not/under/source/tree/File.java").iterator() + .hasNext()); + } + + @Test + public void shouldConvertFileInPackageDefaultToJavaClassName() { + assertEquals("InDefault*", apply("InDefault.java")); + } + + @Test + public void shouldConvertFileInPackageToJavaClassName() { + assertEquals("com.example.Class*", apply("com/example/Class.java")); + } + + @Test + public void shouldConvertFilesWithOddCaseExtensionsToJavaClassName() { + assertEquals("com.example.Class*", apply("com/example/Class.JaVa")); + } + + @Test + public void shouldNotConvertFilesWithoutExtension() { + assertFalse(this.testee.apply(SRC + "/File").iterator().hasNext()); + } + + @Test + public void shouldConvertFilesWithDotInPath() { + assertTrue(this.testee.apply(SRC + "/foo.bar/File.java").iterator() + .hasNext()); + } + + @Test + public void shouldIncludeWildCardInGeneratedGlobToCatchInnerClasses() { + assertTrue(apply("foo.java").endsWith("*")); + } + + @Test + public void shouldConvertBackslashPathsRegardlessOfOs() { + assertEquals("com.example.Class*", apply("com\\example\\Class.java")); + } + + private String apply(final String value) { + return this.testee.apply(SRC + "/" + value).iterator().next(); + } +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/PitMojoTest.java b/pitest-maven/src/test/java/org/pitest/maven/PitMojoTest.java index e19698663..58fbffe3d 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/PitMojoTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/PitMojoTest.java @@ -1,180 +1,180 @@ -package org.pitest.maven; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Collections; -import java.util.Map; - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.mockito.Matchers; -import org.pitest.coverage.CoverageSummary; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.mutationtest.statistics.MutationStatistics; -import org.pitest.mutationtest.statistics.Score; -import org.pitest.mutationtest.tooling.CombinedStatistics; - -public class PitMojoTest extends BasePitMojoTest { - - private AbstractPitMojo testee; - - @Override - public void setUp() throws Exception { - super.setUp(); - } - - public void testRunsAMutationReportWhenMutationCoverageGoalTrigered() - throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("")); - final Build build = new Build(); - build.setOutputDirectory("foo"); - this.testee.getProject().setBuild(build); - this.testee.execute(); - verify(this.executionStrategy).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - public void testDoesNotAnalysePomProjects() throws Exception { - when(this.project.getPackaging()).thenReturn("pom"); - this.testee = createPITMojo(createPomWithConfiguration("")); - this.testee.execute(); - verify(this.executionStrategy, never()).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - public void testDoesNotAnalyseProjectsWithSkipFlagSet() throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("true")); - this.testee.execute(); - verify(this.executionStrategy, never()).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - public void testThrowsMojoFailureExceptionWhenMutationScoreBelowThreshold() - throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("21")); - setupCoverage(20, 1, 1); - try { - this.testee.execute(); - fail(); - } catch (final MojoFailureException ex) { - // pass - } - } - - public void testDoesNotThrowsMojoFailureExceptionWhenMutationScoreOnThreshold() - throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("21")); - setupCoverage(21, 1, 1); - try { - this.testee.execute(); - // pass - } catch (final MojoFailureException ex) { - fail(); - } - } - - public void testThrowsMojoFailureExceptionWhenSurvivingMutantsAboveThreshold() - throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("19")); - setupSuvivingMutants(20); - try { - this.testee.execute(); - fail(); - } catch (final MojoFailureException ex) { - // pass - } - } - - public void testDoesNotThrowsMojoFailureExceptionWhenSurvivingMutantsOnThreshold() - throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("19")); - setupSuvivingMutants(19); - try { - this.testee.execute(); - } catch (final MojoFailureException ex) { - fail(); - } - } - - public void testAllowsSurvivingMutantsThresholdToBeZero() - throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("0")); - setupSuvivingMutants(1); - try { - this.testee.execute(); - fail(); - } catch (final MojoFailureException ex) { - // pass - } - } - - public void testThrowsMojoFailureExceptionWhenCoverageBelowThreshold() - throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("50")); - setupCoverage(100l, 100, 40); - try { - this.testee.execute(); - fail(); - } catch (final MojoFailureException ex) { - // pass - } - } - - public void testDoesNotThrowMojoFailureExceptionWhenCoverageOnThreshold() - throws Exception { - this.testee = createPITMojo(createPomWithConfiguration("50")); - setupCoverage(100l, 100, 50); - try { - this.testee.execute(); - // pass - } catch (final MojoFailureException ex) { - fail(); - } - } - - public void testConfigureEnvironmentVariable() throws Exception { - - AbstractPitMojo mojo = createPITMojo(createPomWithConfiguration("\n" - + " \n" - + " :20\n" - + " ")); - - assertEquals(mojo.getEnvironmentVariables().get("DISPLAY"), ":20"); - } - - private void setupCoverage(long mutationScore, int lines, int linesCovered) - throws MojoExecutionException { - Iterable scores = Collections.emptyList(); - final MutationStatistics stats = new MutationStatistics(scores, 100, mutationScore, 0); - CoverageSummary sum = new CoverageSummary(lines, linesCovered); - final CombinedStatistics cs = new CombinedStatistics(stats, sum); - when( - this.executionStrategy.execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap())) - .thenReturn(cs); - } - - private void setupSuvivingMutants(long survivors) - throws MojoExecutionException { - Iterable scores = Collections.emptyList(); - int detected = 100; - final MutationStatistics stats = new MutationStatistics(scores, detected + survivors, detected, 0); - CoverageSummary sum = new CoverageSummary(0, 0); - final CombinedStatistics cs = new CombinedStatistics(stats, sum); - when( - this.executionStrategy.execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap())) - .thenReturn(cs); - } - - private Map anyMap() { - return Matchers.> any(); - } - -} +package org.pitest.maven; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Collections; +import java.util.Map; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.mockito.Matchers; +import org.pitest.coverage.CoverageSummary; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.mutationtest.statistics.MutationStatistics; +import org.pitest.mutationtest.statistics.Score; +import org.pitest.mutationtest.tooling.CombinedStatistics; + +public class PitMojoTest extends BasePitMojoTest { + + private AbstractPitMojo testee; + + @Override + public void setUp() throws Exception { + super.setUp(); + } + + public void testRunsAMutationReportWhenMutationCoverageGoalTrigered() + throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("")); + final Build build = new Build(); + build.setOutputDirectory("foo"); + this.testee.getProject().setBuild(build); + this.testee.execute(); + verify(this.executionStrategy).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + public void testDoesNotAnalysePomProjects() throws Exception { + when(this.project.getPackaging()).thenReturn("pom"); + this.testee = createPITMojo(createPomWithConfiguration("")); + this.testee.execute(); + verify(this.executionStrategy, never()).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + public void testDoesNotAnalyseProjectsWithSkipFlagSet() throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("true")); + this.testee.execute(); + verify(this.executionStrategy, never()).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + public void testThrowsMojoFailureExceptionWhenMutationScoreBelowThreshold() + throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("21")); + setupCoverage(20, 1, 1); + try { + this.testee.execute(); + fail(); + } catch (final MojoFailureException ex) { + // pass + } + } + + public void testDoesNotThrowsMojoFailureExceptionWhenMutationScoreOnThreshold() + throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("21")); + setupCoverage(21, 1, 1); + try { + this.testee.execute(); + // pass + } catch (final MojoFailureException ex) { + fail(); + } + } + + public void testThrowsMojoFailureExceptionWhenSurvivingMutantsAboveThreshold() + throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("19")); + setupSuvivingMutants(20); + try { + this.testee.execute(); + fail(); + } catch (final MojoFailureException ex) { + // pass + } + } + + public void testDoesNotThrowsMojoFailureExceptionWhenSurvivingMutantsOnThreshold() + throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("19")); + setupSuvivingMutants(19); + try { + this.testee.execute(); + } catch (final MojoFailureException ex) { + fail(); + } + } + + public void testAllowsSurvivingMutantsThresholdToBeZero() + throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("0")); + setupSuvivingMutants(1); + try { + this.testee.execute(); + fail(); + } catch (final MojoFailureException ex) { + // pass + } + } + + public void testThrowsMojoFailureExceptionWhenCoverageBelowThreshold() + throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("50")); + setupCoverage(100l, 100, 40); + try { + this.testee.execute(); + fail(); + } catch (final MojoFailureException ex) { + // pass + } + } + + public void testDoesNotThrowMojoFailureExceptionWhenCoverageOnThreshold() + throws Exception { + this.testee = createPITMojo(createPomWithConfiguration("50")); + setupCoverage(100l, 100, 50); + try { + this.testee.execute(); + // pass + } catch (final MojoFailureException ex) { + fail(); + } + } + + public void testConfigureEnvironmentVariable() throws Exception { + + AbstractPitMojo mojo = createPITMojo(createPomWithConfiguration("\n" + + " \n" + + " :20\n" + + " ")); + + assertEquals(mojo.getEnvironmentVariables().get("DISPLAY"), ":20"); + } + + private void setupCoverage(long mutationScore, int lines, int linesCovered) + throws MojoExecutionException { + Iterable scores = Collections.emptyList(); + final MutationStatistics stats = new MutationStatistics(scores, 100, mutationScore, 0); + CoverageSummary sum = new CoverageSummary(lines, linesCovered); + final CombinedStatistics cs = new CombinedStatistics(stats, sum); + when( + this.executionStrategy.execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap())) + .thenReturn(cs); + } + + private void setupSuvivingMutants(long survivors) + throws MojoExecutionException { + Iterable scores = Collections.emptyList(); + int detected = 100; + final MutationStatistics stats = new MutationStatistics(scores, detected + survivors, detected, 0); + CoverageSummary sum = new CoverageSummary(0, 0); + final CombinedStatistics cs = new CombinedStatistics(stats, sum); + when( + this.executionStrategy.execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap())) + .thenReturn(cs); + } + + private Map anyMap() { + return Matchers.> any(); + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/RunDecisionTest.java b/pitest-maven/src/test/java/org/pitest/maven/RunDecisionTest.java index af5470d8c..a050151c3 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/RunDecisionTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/RunDecisionTest.java @@ -1,47 +1,47 @@ -package org.pitest.maven; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -public class RunDecisionTest { - - @Test - public void shouldRunIfThereAreNoReasonsWhyNot() throws Exception { - AbstractPitMojo.RunDecision rd = new AbstractPitMojo.RunDecision(); - - assertThat(rd.getReasons()).isEmpty(); - assertThat(rd.shouldRun()).isTrue(); - } - - @Test - public void shouldNotRunIfThereIsAReasonsWhyNot() throws Exception { - AbstractPitMojo.RunDecision rd = new AbstractPitMojo.RunDecision(); - - rd.addReason("Today is Sunday"); - - assertThat(rd.getReasons()).hasSize(1); - assertThat(rd.shouldRun()).isFalse(); - } - - @Test - public void addReasonAddsReason() throws Exception { - AbstractPitMojo.RunDecision rd = new AbstractPitMojo.RunDecision(); - - rd.addReason("Today is Sunday"); - - assertThat(rd.getReasons()).hasSize(1); - } - - @Test - public void getReasonsReturnsAllReasons() throws Exception { - AbstractPitMojo.RunDecision rd = new AbstractPitMojo.RunDecision(); - - rd.addReason("Today is Monday"); - rd.addReason("Today is Sunday"); - - assertThat(rd.getReasons()).hasSize(2); - assertThat(rd.getReasons()).contains("Today is Sunday", "Today is Monday"); - } - +package org.pitest.maven; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class RunDecisionTest { + + @Test + public void shouldRunIfThereAreNoReasonsWhyNot() throws Exception { + AbstractPitMojo.RunDecision rd = new AbstractPitMojo.RunDecision(); + + assertThat(rd.getReasons()).isEmpty(); + assertThat(rd.shouldRun()).isTrue(); + } + + @Test + public void shouldNotRunIfThereIsAReasonsWhyNot() throws Exception { + AbstractPitMojo.RunDecision rd = new AbstractPitMojo.RunDecision(); + + rd.addReason("Today is Sunday"); + + assertThat(rd.getReasons()).hasSize(1); + assertThat(rd.shouldRun()).isFalse(); + } + + @Test + public void addReasonAddsReason() throws Exception { + AbstractPitMojo.RunDecision rd = new AbstractPitMojo.RunDecision(); + + rd.addReason("Today is Sunday"); + + assertThat(rd.getReasons()).hasSize(1); + } + + @Test + public void getReasonsReturnsAllReasons() throws Exception { + AbstractPitMojo.RunDecision rd = new AbstractPitMojo.RunDecision(); + + rd.addReason("Today is Monday"); + rd.addReason("Today is Sunday"); + + assertThat(rd.getReasons()).hasSize(2); + assertThat(rd.getReasons()).contains("Today is Sunday", "Today is Monday"); + } + } \ No newline at end of file diff --git a/pitest-maven/src/test/java/org/pitest/maven/ScmMojoTest.java b/pitest-maven/src/test/java/org/pitest/maven/ScmMojoTest.java index 68cfd88a3..a8484c690 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/ScmMojoTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/ScmMojoTest.java @@ -1,195 +1,195 @@ -package org.pitest.maven; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.Map; - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.scm.ChangeFile; -import org.apache.maven.scm.ChangeSet; -import org.apache.maven.scm.ScmException; -import org.apache.maven.scm.ScmFile; -import org.apache.maven.scm.ScmFileSet; -import org.apache.maven.scm.ScmFileStatus; -import org.apache.maven.scm.command.changelog.ChangeLogScmRequest; -import org.apache.maven.scm.command.changelog.ChangeLogScmResult; -import org.apache.maven.scm.command.changelog.ChangeLogSet; -import org.apache.maven.scm.command.status.StatusScmResult; -import org.apache.maven.scm.manager.ScmManager; -import org.apache.maven.scm.repository.ScmRepository; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.pitest.mutationtest.config.PluginServices; -import org.pitest.mutationtest.config.ReportOptions; - -public class ScmMojoTest extends BasePitMojoTest { - - private ScmMojo testee; - - @Mock - private Build build; - - @Mock - private Scm scm; - - @Mock - private ScmManager manager; - - @Mock - private ScmRepository repository; - - @Override - public void setUp() throws Exception { - super.setUp(); - this.testee = new ScmMojo(this.executionStrategy, this.manager, - this.filter, this.plugins, false, i -> true); - this.testee.setScmRootDir(new File("foo")); - when(this.project.getBuild()).thenReturn(this.build); - when(this.build.getSourceDirectory()).thenReturn("foo"); - when(this.build.getOutputDirectory()).thenReturn("foo"); - when(this.project.getScm()).thenReturn(this.scm); - when(this.manager.makeScmRepository(any(String.class))).thenReturn( - this.repository); - configurePitMojo(this.testee, createPomWithConfiguration("")); - } - - public void testThrowsAnExceptionWhenNoScmConfigured() throws Exception { - try { - when(this.project.getScm()).thenReturn(null); - this.testee.execute(); - fail("Exception expected"); - } catch (final MojoExecutionException ex) { - assertEquals("No SCM Connection configured.", ex.getMessage()); - } - } - - public void testUsesCorrectConnectionWhenDeveloperConnectionSet() - throws Exception { - final String devUrl = "devcon"; - when(this.scm.getDeveloperConnection()).thenReturn(devUrl); - setupToReturnNoModifiedFiles(); - this.testee.setConnectionType("developerconnection"); - this.testee.execute(); - verify(this.manager).makeScmRepository(devUrl); - - } - - public void testUsesCorrectConnectionWhenNonDeveloperConnectionSet() - throws Exception { - final String url = "prodcon"; - when(this.scm.getConnection()).thenReturn(url); - setupToReturnNoModifiedFiles(); - this.testee.setConnectionType("connection"); - this.testee.execute(); - verify(this.manager).makeScmRepository(url); - - } - - public void testClassesAddedToScmAreMutationTested() throws Exception { - setupConnection(); - setFileWithStatus(ScmFileStatus.ADDED); - this.testee.execute(); - verify(this.executionStrategy).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - private void setFileWithStatus(final ScmFileStatus status) - throws ScmException { - when(this.manager.status(any(ScmRepository.class), any(ScmFileSet.class))) - .thenReturn( - new StatusScmResult("", Arrays.asList(new ScmFile( - "foo/bar/Bar.java", status)))); - } - - public void testModifiedClassesAreMutationTested() throws Exception { - setupConnection(); - setFileWithStatus(ScmFileStatus.MODIFIED); - this.testee.execute(); - verify(this.executionStrategy).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - public void testLastCommitIsMutationTested() throws Exception { - setupConnection(); - configurePitMojo( - this.testee, - createPomWithConfiguration("true")); - givenChangeLogWithLastCommit(); - this.testee.execute(); - verify(this.executionStrategy).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - private void givenChangeLogWithLastCommit() throws ScmException { - when(this.manager.changeLog(any(ChangeLogScmRequest.class))) - .thenReturn(new ChangeLogScmResult("", new ChangeLogSet(Arrays.asList(aChangeSetWithAddedFile()), - new Date(), new Date()))); - } - - private ChangeSet aChangeSetWithAddedFile() { - return new ChangeSet(new Date(), "", "", Arrays.asList(aChangeFile(ScmFileStatus.ADDED))); - } - - private ChangeFile aChangeFile(ScmFileStatus fileStatus) { - ChangeFile changeFile = new ChangeFile("foo/bar/Bar.java"); - changeFile.setAction(fileStatus); - return changeFile; - } - - public void testUnknownAndDeletedClassesAreNotMutationTested() - throws Exception { - setupConnection(); - when(this.manager.status(any(ScmRepository.class), any(ScmFileSet.class))) - .thenReturn( - new StatusScmResult("", Arrays.asList(new ScmFile( - "foo/bar/Bar.java", ScmFileStatus.DELETED), new ScmFile( - "foo/bar/Bar.java", ScmFileStatus.UNKNOWN)))); - this.testee.execute(); - verify(this.executionStrategy, never()).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - public void testCanOverrideInspectedStatus() throws Exception { - setupConnection(); - setFileWithStatus(ScmFileStatus.UNKNOWN); - configurePitMojo( - this.testee, - createPomWithConfiguration("DELETEDUNKNOWN")); - this.testee.execute(); - verify(this.executionStrategy, times(1)).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - public void testDoesNotAnalysePomProjects() throws Exception { - setupConnection(); - setFileWithStatus(ScmFileStatus.MODIFIED); - when(this.project.getPackaging()).thenReturn("pom"); - this.testee.execute(); - verify(this.executionStrategy, never()).execute(any(File.class), - any(ReportOptions.class), any(PluginServices.class), anyMap()); - } - - private void setupConnection() { - when(this.scm.getConnection()).thenReturn("url"); - this.testee.setConnectionType("connection"); - } - - private void setupToReturnNoModifiedFiles() throws ScmException { - when(this.manager.status(any(ScmRepository.class), any(ScmFileSet.class))) - .thenReturn(new StatusScmResult("", Collections. emptyList())); - } - - private Map anyMap() { - return Matchers.> any(); - } +package org.pitest.maven; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.Map; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.scm.ChangeFile; +import org.apache.maven.scm.ChangeSet; +import org.apache.maven.scm.ScmException; +import org.apache.maven.scm.ScmFile; +import org.apache.maven.scm.ScmFileSet; +import org.apache.maven.scm.ScmFileStatus; +import org.apache.maven.scm.command.changelog.ChangeLogScmRequest; +import org.apache.maven.scm.command.changelog.ChangeLogScmResult; +import org.apache.maven.scm.command.changelog.ChangeLogSet; +import org.apache.maven.scm.command.status.StatusScmResult; +import org.apache.maven.scm.manager.ScmManager; +import org.apache.maven.scm.repository.ScmRepository; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.pitest.mutationtest.config.PluginServices; +import org.pitest.mutationtest.config.ReportOptions; + +public class ScmMojoTest extends BasePitMojoTest { + + private ScmMojo testee; + + @Mock + private Build build; + + @Mock + private Scm scm; + + @Mock + private ScmManager manager; + + @Mock + private ScmRepository repository; + + @Override + public void setUp() throws Exception { + super.setUp(); + this.testee = new ScmMojo(this.executionStrategy, this.manager, + this.filter, this.plugins, false, i -> true); + this.testee.setScmRootDir(new File("foo")); + when(this.project.getBuild()).thenReturn(this.build); + when(this.build.getSourceDirectory()).thenReturn("foo"); + when(this.build.getOutputDirectory()).thenReturn("foo"); + when(this.project.getScm()).thenReturn(this.scm); + when(this.manager.makeScmRepository(any(String.class))).thenReturn( + this.repository); + configurePitMojo(this.testee, createPomWithConfiguration("")); + } + + public void testThrowsAnExceptionWhenNoScmConfigured() throws Exception { + try { + when(this.project.getScm()).thenReturn(null); + this.testee.execute(); + fail("Exception expected"); + } catch (final MojoExecutionException ex) { + assertEquals("No SCM Connection configured.", ex.getMessage()); + } + } + + public void testUsesCorrectConnectionWhenDeveloperConnectionSet() + throws Exception { + final String devUrl = "devcon"; + when(this.scm.getDeveloperConnection()).thenReturn(devUrl); + setupToReturnNoModifiedFiles(); + this.testee.setConnectionType("developerconnection"); + this.testee.execute(); + verify(this.manager).makeScmRepository(devUrl); + + } + + public void testUsesCorrectConnectionWhenNonDeveloperConnectionSet() + throws Exception { + final String url = "prodcon"; + when(this.scm.getConnection()).thenReturn(url); + setupToReturnNoModifiedFiles(); + this.testee.setConnectionType("connection"); + this.testee.execute(); + verify(this.manager).makeScmRepository(url); + + } + + public void testClassesAddedToScmAreMutationTested() throws Exception { + setupConnection(); + setFileWithStatus(ScmFileStatus.ADDED); + this.testee.execute(); + verify(this.executionStrategy).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + private void setFileWithStatus(final ScmFileStatus status) + throws ScmException { + when(this.manager.status(any(ScmRepository.class), any(ScmFileSet.class))) + .thenReturn( + new StatusScmResult("", Arrays.asList(new ScmFile( + "foo/bar/Bar.java", status)))); + } + + public void testModifiedClassesAreMutationTested() throws Exception { + setupConnection(); + setFileWithStatus(ScmFileStatus.MODIFIED); + this.testee.execute(); + verify(this.executionStrategy).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + public void testLastCommitIsMutationTested() throws Exception { + setupConnection(); + configurePitMojo( + this.testee, + createPomWithConfiguration("true")); + givenChangeLogWithLastCommit(); + this.testee.execute(); + verify(this.executionStrategy).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + private void givenChangeLogWithLastCommit() throws ScmException { + when(this.manager.changeLog(any(ChangeLogScmRequest.class))) + .thenReturn(new ChangeLogScmResult("", new ChangeLogSet(Arrays.asList(aChangeSetWithAddedFile()), + new Date(), new Date()))); + } + + private ChangeSet aChangeSetWithAddedFile() { + return new ChangeSet(new Date(), "", "", Arrays.asList(aChangeFile(ScmFileStatus.ADDED))); + } + + private ChangeFile aChangeFile(ScmFileStatus fileStatus) { + ChangeFile changeFile = new ChangeFile("foo/bar/Bar.java"); + changeFile.setAction(fileStatus); + return changeFile; + } + + public void testUnknownAndDeletedClassesAreNotMutationTested() + throws Exception { + setupConnection(); + when(this.manager.status(any(ScmRepository.class), any(ScmFileSet.class))) + .thenReturn( + new StatusScmResult("", Arrays.asList(new ScmFile( + "foo/bar/Bar.java", ScmFileStatus.DELETED), new ScmFile( + "foo/bar/Bar.java", ScmFileStatus.UNKNOWN)))); + this.testee.execute(); + verify(this.executionStrategy, never()).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + public void testCanOverrideInspectedStatus() throws Exception { + setupConnection(); + setFileWithStatus(ScmFileStatus.UNKNOWN); + configurePitMojo( + this.testee, + createPomWithConfiguration("DELETEDUNKNOWN")); + this.testee.execute(); + verify(this.executionStrategy, times(1)).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + public void testDoesNotAnalysePomProjects() throws Exception { + setupConnection(); + setFileWithStatus(ScmFileStatus.MODIFIED); + when(this.project.getPackaging()).thenReturn("pom"); + this.testee.execute(); + verify(this.executionStrategy, never()).execute(any(File.class), + any(ReportOptions.class), any(PluginServices.class), anyMap()); + } + + private void setupConnection() { + when(this.scm.getConnection()).thenReturn("url"); + this.testee.setConnectionType("connection"); + } + + private void setupToReturnNoModifiedFiles() throws ScmException { + when(this.manager.status(any(ScmRepository.class), any(ScmFileSet.class))) + .thenReturn(new StatusScmResult("", Collections. emptyList())); + } + + private Map anyMap() { + return Matchers.> any(); + } } \ No newline at end of file diff --git a/pitest-maven/src/test/java/org/pitest/maven/ScmStatusTest.java b/pitest-maven/src/test/java/org/pitest/maven/ScmStatusTest.java index 33f61f4b9..7bc07c535 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/ScmStatusTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/ScmStatusTest.java @@ -1,27 +1,27 @@ -package org.pitest.maven; - -import static org.junit.Assert.assertEquals; - -import org.apache.maven.scm.ScmFileStatus; -import org.junit.Test; - -public class ScmStatusTest { - - @Test - public void shouldMapTheStringAddedToTheRightScmFileStatus() { - assertEquals(ScmFileStatus.ADDED, ScmStatus.valueOf("ADDED").getStatus()); - } - - @Test - public void shouldMapTheStringModifiedToTheRightScmFileStatus() { - assertEquals(ScmFileStatus.MODIFIED, ScmStatus.valueOf("MODIFIED") - .getStatus()); - } - - @Test - public void shouldMapTheStringUnknownToTheRightScmFileStatus() { - assertEquals(ScmFileStatus.UNKNOWN, ScmStatus.valueOf("UNKNOWN") - .getStatus()); - } - -} +package org.pitest.maven; + +import static org.junit.Assert.assertEquals; + +import org.apache.maven.scm.ScmFileStatus; +import org.junit.Test; + +public class ScmStatusTest { + + @Test + public void shouldMapTheStringAddedToTheRightScmFileStatus() { + assertEquals(ScmFileStatus.ADDED, ScmStatus.valueOf("ADDED").getStatus()); + } + + @Test + public void shouldMapTheStringModifiedToTheRightScmFileStatus() { + assertEquals(ScmFileStatus.MODIFIED, ScmStatus.valueOf("MODIFIED") + .getStatus()); + } + + @Test + public void shouldMapTheStringUnknownToTheRightScmFileStatus() { + assertEquals(ScmFileStatus.UNKNOWN, ScmStatus.valueOf("UNKNOWN") + .getStatus()); + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/SurefireConfigConverterTest.java b/pitest-maven/src/test/java/org/pitest/maven/SurefireConfigConverterTest.java index da79c2a73..6c122b4b8 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/SurefireConfigConverterTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/SurefireConfigConverterTest.java @@ -1,124 +1,124 @@ -package org.pitest.maven; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Collections; - -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; -import org.junit.Test; -import java.util.function.Predicate; -import org.pitest.mutationtest.config.ReportOptions; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.util.Glob; - -public class SurefireConfigConverterTest { - - SurefireConfigConverter testee = new SurefireConfigConverter(); - ReportOptions options = new ReportOptions(); - Xpp3Dom surefireConfig; - - @Test - public void shouldIgnoreNullSurefireConfiguration() { - assertThat(this.testee.update(this.options, null)).isSameAs(this.options); - } - - @Test - public void shouldCreatePredicateForEachExclude() throws Exception { - this.surefireConfig = makeConfig("AB"); - - ReportOptions actual = this.testee - .update(this.options, this.surefireConfig); - assertThat(actual.getExcludedTestClasses()).hasSize(2); - } - - @Test - public void shouldConvertSurefireExclusionsToPackagePredicates() - throws Exception { - this.surefireConfig = makeConfig("**/FailingTest.java"); - - ReportOptions actual = this.testee - .update(this.options, this.surefireConfig); - Predicate predicate = actual.getExcludedTestClasses().iterator().next(); - assertThat(predicate.test("com.example.FailingTest")).isTrue(); - assertThat(predicate.test("com.example.Test")).isFalse(); - } - - @Test - public void shouldKeepExistingExclusions() throws Exception { - this.surefireConfig = makeConfig("AB"); - this.options.setExcludedTestClasses(Collections - .> singletonList(new Glob("Foo"))); - ReportOptions actual = this.testee - .update(this.options, this.surefireConfig); - - assertThat(actual.getExcludedTestClasses()).hasSize(3); - } - - @Test - public void shouldConvertSingleSurefireGroups() throws Exception { - this.surefireConfig = makeConfig("com.example.Unit"); - ReportOptions actual = this.testee - .update(this.options, this.surefireConfig); - - assertThat(actual.getGroupConfig().getIncludedGroups()).containsOnly( - "com.example.Unit"); - } - - @Test - public void shouldConvertMultipleSurefireGroups() throws Exception { - this.surefireConfig = makeConfig("com.example.Unit com.example.Fast"); - ReportOptions actual = this.testee - .update(this.options, this.surefireConfig); - - assertThat(actual.getGroupConfig().getIncludedGroups()).containsOnly( - "com.example.Unit", "com.example.Fast"); - } - - @Test - public void shouldConvertMultipleSurefireGroupExcludes() throws Exception { - this.surefireConfig = makeConfig("com.example.Unit com.example.Fast"); - ReportOptions actual = this.testee - .update(this.options, this.surefireConfig); - - assertThat(actual.getGroupConfig().getExcludedGroups()).containsOnly( - "com.example.Unit", "com.example.Fast"); - } - - @Test - public void shouldNotUseSurefireGroupsWhenPitestIncludesSpecified() - throws Exception { - TestGroupConfig gc = new TestGroupConfig(Collections. emptyList(), - Arrays.asList("bar")); - this.options.setGroupConfig(gc); - this.surefireConfig = makeConfig("com.example.Unit com.example.Fast"); - ReportOptions actual = this.testee - .update(this.options, this.surefireConfig); - - assertThat(actual.getGroupConfig().getIncludedGroups()).containsOnly("bar"); - } - - @Test - public void shouldNotUseSurefireGroupsWhenPitestExcludesSpecified() - throws Exception { - TestGroupConfig gc = new TestGroupConfig(Arrays.asList("bar"), - Collections. emptyList()); - this.options.setGroupConfig(gc); - this.surefireConfig = makeConfig("com.example.Unit com.example.Fast"); - - ReportOptions actual = this.testee - .update(this.options, this.surefireConfig); - - assertThat(actual.getGroupConfig().getExcludedGroups()).containsOnly("bar"); - } - - private Xpp3Dom makeConfig(String s) throws Exception { - String xml = "" + s + ""; - InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8")); - return Xpp3DomBuilder.build(stream, "UTF-8"); - } - -} +package org.pitest.maven; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; + +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.codehaus.plexus.util.xml.Xpp3DomBuilder; +import org.junit.Test; +import java.util.function.Predicate; +import org.pitest.mutationtest.config.ReportOptions; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.util.Glob; + +public class SurefireConfigConverterTest { + + SurefireConfigConverter testee = new SurefireConfigConverter(); + ReportOptions options = new ReportOptions(); + Xpp3Dom surefireConfig; + + @Test + public void shouldIgnoreNullSurefireConfiguration() { + assertThat(this.testee.update(this.options, null)).isSameAs(this.options); + } + + @Test + public void shouldCreatePredicateForEachExclude() throws Exception { + this.surefireConfig = makeConfig("AB"); + + ReportOptions actual = this.testee + .update(this.options, this.surefireConfig); + assertThat(actual.getExcludedTestClasses()).hasSize(2); + } + + @Test + public void shouldConvertSurefireExclusionsToPackagePredicates() + throws Exception { + this.surefireConfig = makeConfig("**/FailingTest.java"); + + ReportOptions actual = this.testee + .update(this.options, this.surefireConfig); + Predicate predicate = actual.getExcludedTestClasses().iterator().next(); + assertThat(predicate.test("com.example.FailingTest")).isTrue(); + assertThat(predicate.test("com.example.Test")).isFalse(); + } + + @Test + public void shouldKeepExistingExclusions() throws Exception { + this.surefireConfig = makeConfig("AB"); + this.options.setExcludedTestClasses(Collections + .> singletonList(new Glob("Foo"))); + ReportOptions actual = this.testee + .update(this.options, this.surefireConfig); + + assertThat(actual.getExcludedTestClasses()).hasSize(3); + } + + @Test + public void shouldConvertSingleSurefireGroups() throws Exception { + this.surefireConfig = makeConfig("com.example.Unit"); + ReportOptions actual = this.testee + .update(this.options, this.surefireConfig); + + assertThat(actual.getGroupConfig().getIncludedGroups()).containsOnly( + "com.example.Unit"); + } + + @Test + public void shouldConvertMultipleSurefireGroups() throws Exception { + this.surefireConfig = makeConfig("com.example.Unit com.example.Fast"); + ReportOptions actual = this.testee + .update(this.options, this.surefireConfig); + + assertThat(actual.getGroupConfig().getIncludedGroups()).containsOnly( + "com.example.Unit", "com.example.Fast"); + } + + @Test + public void shouldConvertMultipleSurefireGroupExcludes() throws Exception { + this.surefireConfig = makeConfig("com.example.Unit com.example.Fast"); + ReportOptions actual = this.testee + .update(this.options, this.surefireConfig); + + assertThat(actual.getGroupConfig().getExcludedGroups()).containsOnly( + "com.example.Unit", "com.example.Fast"); + } + + @Test + public void shouldNotUseSurefireGroupsWhenPitestIncludesSpecified() + throws Exception { + TestGroupConfig gc = new TestGroupConfig(Collections. emptyList(), + Arrays.asList("bar")); + this.options.setGroupConfig(gc); + this.surefireConfig = makeConfig("com.example.Unit com.example.Fast"); + ReportOptions actual = this.testee + .update(this.options, this.surefireConfig); + + assertThat(actual.getGroupConfig().getIncludedGroups()).containsOnly("bar"); + } + + @Test + public void shouldNotUseSurefireGroupsWhenPitestExcludesSpecified() + throws Exception { + TestGroupConfig gc = new TestGroupConfig(Arrays.asList("bar"), + Collections. emptyList()); + this.options.setGroupConfig(gc); + this.surefireConfig = makeConfig("com.example.Unit com.example.Fast"); + + ReportOptions actual = this.testee + .update(this.options, this.surefireConfig); + + assertThat(actual.getGroupConfig().getExcludedGroups()).containsOnly("bar"); + } + + private Xpp3Dom makeConfig(String s) throws Exception { + String xml = "" + s + ""; + InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8")); + return Xpp3DomBuilder.build(stream, "UTF-8"); + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/SystemTest.java b/pitest-maven/src/test/java/org/pitest/maven/SystemTest.java index ebb40b128..908cb17c9 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/SystemTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/SystemTest.java @@ -1,5 +1,5 @@ -package org.pitest.maven; - -public interface SystemTest { - -} +package org.pitest.maven; + +public interface SystemTest { + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/report/PitReportMojoTest.java b/pitest-maven/src/test/java/org/pitest/maven/report/PitReportMojoTest.java index 5c6f44e62..b2b1ee733 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/report/PitReportMojoTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/report/PitReportMojoTest.java @@ -1,114 +1,114 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.lang.reflect.Field; -import java.util.Locale; - -import org.apache.maven.doxia.sink.Sink; -import org.apache.maven.plugin.logging.Log; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.pitest.maven.report.generator.ReportGenerationContext; -import org.pitest.maven.report.generator.ReportGenerationManager; -import org.pitest.util.PitError; - -@RunWith(MockitoJUnitRunner.class) -public class PitReportMojoTest { - - @Captor - private ArgumentCaptor contextCaptor; - - @Mock - private Log log; - @Mock - private File reportsDirectory; - @Mock - private ReportGenerationManager reportGenerationManager; - @Mock - private Sink sink; - - @InjectMocks - private PitReportMojo fixture; - - @Test(expected = PitError.class) - public void testNonExistantReportsDirectory() throws Exception { - this.setupMocks(false, true, true); - this.fixture.executeReport(Locale.ENGLISH); - } - - @Test(expected = PitError.class) - public void testNonReadableReportsDirectory() throws Exception { - this.setupMocks(true, false, true); - this.fixture.executeReport(Locale.ENGLISH); - } - - @Test(expected = PitError.class) - public void testFileReportsDirectory() throws Exception { - this.setupMocks(true, true, false); - this.fixture.executeReport(Locale.ENGLISH); - } - - @Test - public void testGenerateReport() throws Exception { - ReportGenerationContext actualContext; - - this.reflectionSetSiteReportDir("pit-reports"); - - setupMocks(true, true, true); - when(this.reportsDirectory.getAbsolutePath()).thenReturn("abspath"); - - this.fixture.executeReport(Locale.ENGLISH); - - verify(this.reportGenerationManager).generateSiteReport( - this.contextCaptor.capture()); - actualContext = this.contextCaptor.getValue(); - - assertThat(actualContext.getLocale(), sameInstance(Locale.ENGLISH)); - assertThat(actualContext.getLogger(), sameInstance(this.log)); - assertThat(actualContext.getReportsDataDirectory(), - sameInstance(this.reportsDirectory)); - assertThat(actualContext.getSink(), sameInstance(this.sink)); - assertThat(actualContext.getSiteDirectory().getPath(), is("abspath" - + File.separator + "pit-reports")); - } - - private void setupMocks(boolean reportsDirectoryExists, - boolean reportsDirectoryReadable, boolean reportsDirectoryIsDirectory) { - when(this.reportsDirectory.exists()).thenReturn(reportsDirectoryExists); - when(this.reportsDirectory.canRead()).thenReturn(reportsDirectoryReadable); - when(this.reportsDirectory.isDirectory()).thenReturn( - reportsDirectoryIsDirectory); - } - - private void reflectionSetSiteReportDir(String value) throws Exception { - Field f = this.fixture.getClass().getDeclaredField("siteReportDirectory"); - f.setAccessible(true); - f.set(this.fixture, value); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.Locale; + +import org.apache.maven.doxia.sink.Sink; +import org.apache.maven.plugin.logging.Log; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.pitest.maven.report.generator.ReportGenerationContext; +import org.pitest.maven.report.generator.ReportGenerationManager; +import org.pitest.util.PitError; + +@RunWith(MockitoJUnitRunner.class) +public class PitReportMojoTest { + + @Captor + private ArgumentCaptor contextCaptor; + + @Mock + private Log log; + @Mock + private File reportsDirectory; + @Mock + private ReportGenerationManager reportGenerationManager; + @Mock + private Sink sink; + + @InjectMocks + private PitReportMojo fixture; + + @Test(expected = PitError.class) + public void testNonExistantReportsDirectory() throws Exception { + this.setupMocks(false, true, true); + this.fixture.executeReport(Locale.ENGLISH); + } + + @Test(expected = PitError.class) + public void testNonReadableReportsDirectory() throws Exception { + this.setupMocks(true, false, true); + this.fixture.executeReport(Locale.ENGLISH); + } + + @Test(expected = PitError.class) + public void testFileReportsDirectory() throws Exception { + this.setupMocks(true, true, false); + this.fixture.executeReport(Locale.ENGLISH); + } + + @Test + public void testGenerateReport() throws Exception { + ReportGenerationContext actualContext; + + this.reflectionSetSiteReportDir("pit-reports"); + + setupMocks(true, true, true); + when(this.reportsDirectory.getAbsolutePath()).thenReturn("abspath"); + + this.fixture.executeReport(Locale.ENGLISH); + + verify(this.reportGenerationManager).generateSiteReport( + this.contextCaptor.capture()); + actualContext = this.contextCaptor.getValue(); + + assertThat(actualContext.getLocale(), sameInstance(Locale.ENGLISH)); + assertThat(actualContext.getLogger(), sameInstance(this.log)); + assertThat(actualContext.getReportsDataDirectory(), + sameInstance(this.reportsDirectory)); + assertThat(actualContext.getSink(), sameInstance(this.sink)); + assertThat(actualContext.getSiteDirectory().getPath(), is("abspath" + + File.separator + "pit-reports")); + } + + private void setupMocks(boolean reportsDirectoryExists, + boolean reportsDirectoryReadable, boolean reportsDirectoryIsDirectory) { + when(this.reportsDirectory.exists()).thenReturn(reportsDirectoryExists); + when(this.reportsDirectory.canRead()).thenReturn(reportsDirectoryReadable); + when(this.reportsDirectory.isDirectory()).thenReturn( + reportsDirectoryIsDirectory); + } + + private void reflectionSetSiteReportDir(String value) throws Exception { + Field f = this.fixture.getClass().getDeclaredField("siteReportDirectory"); + f.setAccessible(true); + f.set(this.fixture, value); + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/report/ReportSourceLocatorParamaterizedTest.java b/pitest-maven/src/test/java/org/pitest/maven/report/ReportSourceLocatorParamaterizedTest.java index af238d77c..0e27cd907 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/report/ReportSourceLocatorParamaterizedTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/report/ReportSourceLocatorParamaterizedTest.java @@ -1,76 +1,76 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Arrays; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class ReportSourceLocatorParamaterizedTest { - - private static final String VALID_DIRECTORY_NAME = "20150304"; - private static final String INVALID_DIRECTORY_NAME = "abc2015def0304gh"; - - @Parameters(name = "{index}: reportSourceLocator(isDirectory: {0}, directoryName: \"{1}\", canWrite: {2}, shouldBeValid: {3})") - public static final Iterable data() { - return Arrays.asList(new Object[][] { - { true, VALID_DIRECTORY_NAME, true, true }, - { true, VALID_DIRECTORY_NAME, false, false }, - { true, INVALID_DIRECTORY_NAME, true, false }, - { true, INVALID_DIRECTORY_NAME, false, false }, - { false, VALID_DIRECTORY_NAME, true, false }, - { false, VALID_DIRECTORY_NAME, false, false }, - { false, INVALID_DIRECTORY_NAME, true, false }, - { false, INVALID_DIRECTORY_NAME, false, false } }); - } - - @Parameter - public boolean isDirectory; - - @Parameter(value = 1) - public String directoryName; - - @Parameter(value = 2) - public boolean canWrite; - - @Parameter(value = 3) - public boolean expectedResult; - - @Test - public void test() { - File mockDir = mock(File.class); - - when(mockDir.isDirectory()).thenReturn(this.isDirectory); - when(mockDir.getParentFile()).thenReturn(null); - when(mockDir.getName()).thenReturn(this.directoryName); - when(mockDir.canWrite()).thenReturn(this.canWrite); - - assertThat( - ReportSourceLocator.TIMESTAMPED_REPORTS_FILE_FILTER.accept(mockDir), - is(this.expectedResult)); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Arrays; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(Parameterized.class) +public class ReportSourceLocatorParamaterizedTest { + + private static final String VALID_DIRECTORY_NAME = "20150304"; + private static final String INVALID_DIRECTORY_NAME = "abc2015def0304gh"; + + @Parameters(name = "{index}: reportSourceLocator(isDirectory: {0}, directoryName: \"{1}\", canWrite: {2}, shouldBeValid: {3})") + public static final Iterable data() { + return Arrays.asList(new Object[][] { + { true, VALID_DIRECTORY_NAME, true, true }, + { true, VALID_DIRECTORY_NAME, false, false }, + { true, INVALID_DIRECTORY_NAME, true, false }, + { true, INVALID_DIRECTORY_NAME, false, false }, + { false, VALID_DIRECTORY_NAME, true, false }, + { false, VALID_DIRECTORY_NAME, false, false }, + { false, INVALID_DIRECTORY_NAME, true, false }, + { false, INVALID_DIRECTORY_NAME, false, false } }); + } + + @Parameter + public boolean isDirectory; + + @Parameter(value = 1) + public String directoryName; + + @Parameter(value = 2) + public boolean canWrite; + + @Parameter(value = 3) + public boolean expectedResult; + + @Test + public void test() { + File mockDir = mock(File.class); + + when(mockDir.isDirectory()).thenReturn(this.isDirectory); + when(mockDir.getParentFile()).thenReturn(null); + when(mockDir.getName()).thenReturn(this.directoryName); + when(mockDir.canWrite()).thenReturn(this.canWrite); + + assertThat( + ReportSourceLocator.TIMESTAMPED_REPORTS_FILE_FILTER.accept(mockDir), + is(this.expectedResult)); + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/report/ReportSourceLocatorTest.java b/pitest-maven/src/test/java/org/pitest/maven/report/ReportSourceLocatorTest.java index 909cf7f44..d79b15f2d 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/report/ReportSourceLocatorTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/report/ReportSourceLocatorTest.java @@ -1,125 +1,125 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report; - -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.FileFilter; - -import org.apache.maven.plugin.logging.Log; -import org.junit.Before; -import org.junit.Test; -import org.pitest.util.PitError; - -public class ReportSourceLocatorTest { - - private ReportSourceLocator fixture; - private Log mockLog; - - @Before - public void setUp() { - this.fixture = new ReportSourceLocator(); - this.mockLog = mock(Log.class); - } - - @Test(expected = PitError.class) - public void testCouldNotListdirectories() { - File mockReportsDir = this.buildMockReportsDirectory(); - - when(mockReportsDir.listFiles(isA(FileFilter.class))).thenReturn(null); - this.fixture.locate(mockReportsDir, this.mockLog); - } - - @Test - public void testNoSubdirectories() { - File mockReportsDir = this.buildMockReportsDirectory(); - - when(mockReportsDir.listFiles(isA(FileFilter.class))).thenReturn( - new File[0]); - assertThat(this.fixture.locate(mockReportsDir, this.mockLog), - sameInstance(mockReportsDir)); - } - - @Test - public void testOneSubdirectory() { - File mockReportsDir = this.buildMockReportsDirectory(); - File dummySubDir = mock(File.class); - - when(mockReportsDir.listFiles(isA(FileFilter.class))).thenReturn( - new File[] { dummySubDir }); - when(mockReportsDir.lastModified()).thenReturn(1L); - when(dummySubDir.lastModified()).thenReturn(2L); - assertThat(this.fixture.locate(mockReportsDir, this.mockLog), - sameInstance(dummySubDir)); - } - - @Test - public void testMultipleSubdirectories() { - File mockReportsDir = this.buildMockReportsDirectory(); - File mockSubDir0 = mock(File.class); - File mockSubDir1 = mock(File.class); - File mockSubDir2 = mock(File.class); - File mockSubDir3 = mock(File.class); - - when(mockSubDir0.lastModified()).thenReturn(2L); - when(mockSubDir1.lastModified()).thenReturn(3L); - when(mockSubDir2.lastModified()).thenReturn(1L); - when(mockSubDir3.lastModified()).thenReturn(3L); - - when(mockReportsDir.listFiles(isA(FileFilter.class))).thenReturn( - new File[] { mockSubDir0, mockSubDir1, mockSubDir2, mockSubDir3 }); - assertThat(this.fixture.locate(mockReportsDir, this.mockLog), - sameInstance(mockSubDir1)); - } - - @Test(expected = PitError.class) - public void testNotDirectory() { - this.fixture.locate(this.buildMockReportsDirectory(true, true, false), - this.mockLog); - } - - @Test(expected = PitError.class) - public void testNotReadable() { - this.fixture.locate(this.buildMockReportsDirectory(true, false, true), - this.mockLog); - } - - @Test(expected = PitError.class) - public void testNotExists() { - this.fixture.locate(this.buildMockReportsDirectory(false, true, true), - this.mockLog); - } - - private File buildMockReportsDirectory() { - return this.buildMockReportsDirectory(true, true, true); - } - - private File buildMockReportsDirectory(boolean exists, boolean canRead, - boolean isDirectory) { - File testFile = mock(File.class); - - when(testFile.exists()).thenReturn(exists); - when(testFile.canRead()).thenReturn(canRead); - when(testFile.isDirectory()).thenReturn(isDirectory); - - return testFile; - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report; + +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileFilter; + +import org.apache.maven.plugin.logging.Log; +import org.junit.Before; +import org.junit.Test; +import org.pitest.util.PitError; + +public class ReportSourceLocatorTest { + + private ReportSourceLocator fixture; + private Log mockLog; + + @Before + public void setUp() { + this.fixture = new ReportSourceLocator(); + this.mockLog = mock(Log.class); + } + + @Test(expected = PitError.class) + public void testCouldNotListdirectories() { + File mockReportsDir = this.buildMockReportsDirectory(); + + when(mockReportsDir.listFiles(isA(FileFilter.class))).thenReturn(null); + this.fixture.locate(mockReportsDir, this.mockLog); + } + + @Test + public void testNoSubdirectories() { + File mockReportsDir = this.buildMockReportsDirectory(); + + when(mockReportsDir.listFiles(isA(FileFilter.class))).thenReturn( + new File[0]); + assertThat(this.fixture.locate(mockReportsDir, this.mockLog), + sameInstance(mockReportsDir)); + } + + @Test + public void testOneSubdirectory() { + File mockReportsDir = this.buildMockReportsDirectory(); + File dummySubDir = mock(File.class); + + when(mockReportsDir.listFiles(isA(FileFilter.class))).thenReturn( + new File[] { dummySubDir }); + when(mockReportsDir.lastModified()).thenReturn(1L); + when(dummySubDir.lastModified()).thenReturn(2L); + assertThat(this.fixture.locate(mockReportsDir, this.mockLog), + sameInstance(dummySubDir)); + } + + @Test + public void testMultipleSubdirectories() { + File mockReportsDir = this.buildMockReportsDirectory(); + File mockSubDir0 = mock(File.class); + File mockSubDir1 = mock(File.class); + File mockSubDir2 = mock(File.class); + File mockSubDir3 = mock(File.class); + + when(mockSubDir0.lastModified()).thenReturn(2L); + when(mockSubDir1.lastModified()).thenReturn(3L); + when(mockSubDir2.lastModified()).thenReturn(1L); + when(mockSubDir3.lastModified()).thenReturn(3L); + + when(mockReportsDir.listFiles(isA(FileFilter.class))).thenReturn( + new File[] { mockSubDir0, mockSubDir1, mockSubDir2, mockSubDir3 }); + assertThat(this.fixture.locate(mockReportsDir, this.mockLog), + sameInstance(mockSubDir1)); + } + + @Test(expected = PitError.class) + public void testNotDirectory() { + this.fixture.locate(this.buildMockReportsDirectory(true, true, false), + this.mockLog); + } + + @Test(expected = PitError.class) + public void testNotReadable() { + this.fixture.locate(this.buildMockReportsDirectory(true, false, true), + this.mockLog); + } + + @Test(expected = PitError.class) + public void testNotExists() { + this.fixture.locate(this.buildMockReportsDirectory(false, true, true), + this.mockLog); + } + + private File buildMockReportsDirectory() { + return this.buildMockReportsDirectory(true, true, true); + } + + private File buildMockReportsDirectory(boolean exists, boolean canRead, + boolean isDirectory) { + File testFile = mock(File.class); + + when(testFile.exists()).thenReturn(exists); + when(testFile.canRead()).thenReturn(canRead); + when(testFile.isDirectory()).thenReturn(isDirectory); + + return testFile; + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/report/generator/HTMLReportGeneratorTest.java b/pitest-maven/src/test/java/org/pitest/maven/report/generator/HTMLReportGeneratorTest.java index d0e93b9e5..2a4feeb09 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/report/generator/HTMLReportGeneratorTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/report/generator/HTMLReportGeneratorTest.java @@ -1,107 +1,107 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; - -import java.io.File; -import java.util.Arrays; - -import org.apache.maven.plugin.logging.Log; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -public class HTMLReportGeneratorTest { - - private static final String HTML_SOURCE_DATA_FORMAT = "HTML"; - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - private Log mockLogger; - private HTMLReportGenerator fixture; - - @Before - public void setUp() { - this.mockLogger = mock(Log.class); - this.fixture = new HTMLReportGenerator(); - } - - @Test - public void testName() { - assertThat(this.fixture.getGeneratorName(), is("HTMLReportGenerator")); - } - - @Test - public void testCopySuccess() throws Exception { - File sourceFolder = this.tempFolder.newFolder("reportsFolder"); - File destFolder = this.tempFolder.newFolder("siteFolder"); - - new File(sourceFolder, "file0.txt").createNewFile(); - new File(sourceFolder, "file1.txt").createNewFile(); - - assertThat(this.fixture.generate(new ReportGenerationContext(null, null, - sourceFolder, destFolder, this.mockLogger, Arrays - .asList(HTML_SOURCE_DATA_FORMAT))), - sameInstance(ReportGenerationResultEnum.SUCCESS)); - assertThat(sourceFolder.listFiles().length, is(2)); - assertThat(destFolder.listFiles().length, is(2)); - } - - @Test - public void testCopySkipsTimestampedReportsSubDirectories() throws Exception { - File sourceFolder = this.tempFolder.newFolder("reportsFolder"); - File destFolder = this.tempFolder.newFolder("siteFolder"); - String[] destinationFiles; - - new File(sourceFolder, "file0.txt").createNewFile(); - new File(sourceFolder, "file1.txt").createNewFile(); - new File(sourceFolder, "0123456789").createNewFile(); - - assertThat(this.fixture.generate(new ReportGenerationContext(null, null, - sourceFolder, destFolder, this.mockLogger, Arrays - .asList(HTML_SOURCE_DATA_FORMAT))), - sameInstance(ReportGenerationResultEnum.SUCCESS)); - assertThat(sourceFolder.list().length, is(3)); - - destinationFiles = destFolder.list(); - assertThat(destFolder.listFiles().length, is(2)); - for (String f : destinationFiles) { - assertThat(f, startsWith("file")); - } - } - - @Test - public void testCopyFails() { - assertThat(this.fixture.generate(new ReportGenerationContext(null, null, - new File("foo"), new File("bar"), this.mockLogger, Arrays - .asList(HTML_SOURCE_DATA_FORMAT))), - sameInstance(ReportGenerationResultEnum.FAILURE)); - } - - @Test - public void testSourceDataFormat() { - assertThat(this.fixture.getGeneratorDataFormat(), - equalTo(HTML_SOURCE_DATA_FORMAT)); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.CoreMatchers.startsWith; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; + +import java.io.File; +import java.util.Arrays; + +import org.apache.maven.plugin.logging.Log; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class HTMLReportGeneratorTest { + + private static final String HTML_SOURCE_DATA_FORMAT = "HTML"; + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + private Log mockLogger; + private HTMLReportGenerator fixture; + + @Before + public void setUp() { + this.mockLogger = mock(Log.class); + this.fixture = new HTMLReportGenerator(); + } + + @Test + public void testName() { + assertThat(this.fixture.getGeneratorName(), is("HTMLReportGenerator")); + } + + @Test + public void testCopySuccess() throws Exception { + File sourceFolder = this.tempFolder.newFolder("reportsFolder"); + File destFolder = this.tempFolder.newFolder("siteFolder"); + + new File(sourceFolder, "file0.txt").createNewFile(); + new File(sourceFolder, "file1.txt").createNewFile(); + + assertThat(this.fixture.generate(new ReportGenerationContext(null, null, + sourceFolder, destFolder, this.mockLogger, Arrays + .asList(HTML_SOURCE_DATA_FORMAT))), + sameInstance(ReportGenerationResultEnum.SUCCESS)); + assertThat(sourceFolder.listFiles().length, is(2)); + assertThat(destFolder.listFiles().length, is(2)); + } + + @Test + public void testCopySkipsTimestampedReportsSubDirectories() throws Exception { + File sourceFolder = this.tempFolder.newFolder("reportsFolder"); + File destFolder = this.tempFolder.newFolder("siteFolder"); + String[] destinationFiles; + + new File(sourceFolder, "file0.txt").createNewFile(); + new File(sourceFolder, "file1.txt").createNewFile(); + new File(sourceFolder, "0123456789").createNewFile(); + + assertThat(this.fixture.generate(new ReportGenerationContext(null, null, + sourceFolder, destFolder, this.mockLogger, Arrays + .asList(HTML_SOURCE_DATA_FORMAT))), + sameInstance(ReportGenerationResultEnum.SUCCESS)); + assertThat(sourceFolder.list().length, is(3)); + + destinationFiles = destFolder.list(); + assertThat(destFolder.listFiles().length, is(2)); + for (String f : destinationFiles) { + assertThat(f, startsWith("file")); + } + } + + @Test + public void testCopyFails() { + assertThat(this.fixture.generate(new ReportGenerationContext(null, null, + new File("foo"), new File("bar"), this.mockLogger, Arrays + .asList(HTML_SOURCE_DATA_FORMAT))), + sameInstance(ReportGenerationResultEnum.FAILURE)); + } + + @Test + public void testSourceDataFormat() { + assertThat(this.fixture.getGeneratorDataFormat(), + equalTo(HTML_SOURCE_DATA_FORMAT)); + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/report/generator/ReportGenerationManagerTest.java b/pitest-maven/src/test/java/org/pitest/maven/report/generator/ReportGenerationManagerTest.java index a580ffb5e..7245e4396 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/report/generator/ReportGenerationManagerTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/report/generator/ReportGenerationManagerTest.java @@ -1,153 +1,153 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; - -import org.apache.maven.plugin.logging.Log; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.pitest.maven.report.ReportSourceLocator; -import org.pitest.util.PitError; - -@RunWith(MockitoJUnitRunner.class) -public class ReportGenerationManagerTest { - - private ReportGenerationContext generationContext; - private List reportGenerationStrategyList; - - @Mock - private ReportSourceLocator reportLocator; - @Mock - private XMLReportGenerator xmlGenerator; - @Mock - private HTMLReportGenerator htmlGenerator; - @Mock - private Log log; - @Mock - private File reportsDataDirectory; - @Mock - private File siteDirectory; - @Mock - private File locatedReportsDataDirectory; - - private ReportGenerationManager fixture; - - @Before - public void setUp() { - this.reportGenerationStrategyList = new LinkedList<>(); - this.reportGenerationStrategyList.add(this.xmlGenerator); - this.reportGenerationStrategyList.add(this.htmlGenerator); - - this.fixture = new ReportGenerationManager(this.reportLocator, - this.reportGenerationStrategyList); - - this.generationContext = new ReportGenerationContext(Locale.ENGLISH, null, - this.reportsDataDirectory, this.siteDirectory, this.log, Arrays.asList( - "XML", "HTML")); - - when(this.reportLocator.locate(this.reportsDataDirectory, this.log)) - .thenReturn(this.locatedReportsDataDirectory); - when(this.xmlGenerator.getGeneratorDataFormat()).thenReturn("XML"); - when(this.htmlGenerator.getGeneratorDataFormat()).thenReturn("HTML"); - } - - @Test - public void testFirstGeneratorSuccess() { - when(this.xmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.SUCCESS); - - this.fixture.generateSiteReport(this.generationContext); - - verify(this.xmlGenerator).generate(this.generationContext); - verifyZeroInteractions(this.htmlGenerator); - this.assertLocatedReportsDirectory(); - } - - @Test - public void testFirstGeneratorNotRunSecondGeneratorSuccess() { - when(this.xmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.NOT_EXECUTED); - when(this.htmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.SUCCESS); - - this.fixture.generateSiteReport(this.generationContext); - - verify(this.xmlGenerator).generate(this.generationContext); - verify(this.htmlGenerator).generate(this.generationContext); - this.assertLocatedReportsDirectory(); - } - - @Test(expected = PitError.class) - public void testFirstGeneratorNotRunSecondGeneratorNotRun() { - when(this.xmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.NOT_EXECUTED); - when(this.htmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.NOT_EXECUTED); - - this.fixture.generateSiteReport(this.generationContext); - this.assertLocatedReportsDirectory(); - } - - @Test - public void testFirstGeneratorFailSecondGeneratorSuccess() { - when(this.xmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.FAILURE); - when(this.htmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.SUCCESS); - - this.fixture.generateSiteReport(this.generationContext); - - verify(this.xmlGenerator).generate(this.generationContext); - verify(this.htmlGenerator).generate(this.generationContext); - this.assertLocatedReportsDirectory(); - } - - @Test(expected = PitError.class) - public void testFirstGeneratorFailSecondGeneratorFail() { - when(this.xmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.FAILURE); - when(this.htmlGenerator.generate(this.generationContext)).thenReturn( - ReportGenerationResultEnum.FAILURE); - - this.fixture.generateSiteReport(this.generationContext); - this.assertLocatedReportsDirectory(); - } - - @Test(expected = PitError.class) - public void testNoGeneratorsFound() { - this.generationContext.setSourceDataFormats(Arrays.asList("foo")); - this.fixture.generateSiteReport(this.generationContext); - } - - private void assertLocatedReportsDirectory() { - assertThat(this.generationContext.getReportsDataDirectory(), - sameInstance(this.locatedReportsDataDirectory)); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; + +import org.apache.maven.plugin.logging.Log; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.pitest.maven.report.ReportSourceLocator; +import org.pitest.util.PitError; + +@RunWith(MockitoJUnitRunner.class) +public class ReportGenerationManagerTest { + + private ReportGenerationContext generationContext; + private List reportGenerationStrategyList; + + @Mock + private ReportSourceLocator reportLocator; + @Mock + private XMLReportGenerator xmlGenerator; + @Mock + private HTMLReportGenerator htmlGenerator; + @Mock + private Log log; + @Mock + private File reportsDataDirectory; + @Mock + private File siteDirectory; + @Mock + private File locatedReportsDataDirectory; + + private ReportGenerationManager fixture; + + @Before + public void setUp() { + this.reportGenerationStrategyList = new LinkedList<>(); + this.reportGenerationStrategyList.add(this.xmlGenerator); + this.reportGenerationStrategyList.add(this.htmlGenerator); + + this.fixture = new ReportGenerationManager(this.reportLocator, + this.reportGenerationStrategyList); + + this.generationContext = new ReportGenerationContext(Locale.ENGLISH, null, + this.reportsDataDirectory, this.siteDirectory, this.log, Arrays.asList( + "XML", "HTML")); + + when(this.reportLocator.locate(this.reportsDataDirectory, this.log)) + .thenReturn(this.locatedReportsDataDirectory); + when(this.xmlGenerator.getGeneratorDataFormat()).thenReturn("XML"); + when(this.htmlGenerator.getGeneratorDataFormat()).thenReturn("HTML"); + } + + @Test + public void testFirstGeneratorSuccess() { + when(this.xmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.SUCCESS); + + this.fixture.generateSiteReport(this.generationContext); + + verify(this.xmlGenerator).generate(this.generationContext); + verifyZeroInteractions(this.htmlGenerator); + this.assertLocatedReportsDirectory(); + } + + @Test + public void testFirstGeneratorNotRunSecondGeneratorSuccess() { + when(this.xmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.NOT_EXECUTED); + when(this.htmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.SUCCESS); + + this.fixture.generateSiteReport(this.generationContext); + + verify(this.xmlGenerator).generate(this.generationContext); + verify(this.htmlGenerator).generate(this.generationContext); + this.assertLocatedReportsDirectory(); + } + + @Test(expected = PitError.class) + public void testFirstGeneratorNotRunSecondGeneratorNotRun() { + when(this.xmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.NOT_EXECUTED); + when(this.htmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.NOT_EXECUTED); + + this.fixture.generateSiteReport(this.generationContext); + this.assertLocatedReportsDirectory(); + } + + @Test + public void testFirstGeneratorFailSecondGeneratorSuccess() { + when(this.xmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.FAILURE); + when(this.htmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.SUCCESS); + + this.fixture.generateSiteReport(this.generationContext); + + verify(this.xmlGenerator).generate(this.generationContext); + verify(this.htmlGenerator).generate(this.generationContext); + this.assertLocatedReportsDirectory(); + } + + @Test(expected = PitError.class) + public void testFirstGeneratorFailSecondGeneratorFail() { + when(this.xmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.FAILURE); + when(this.htmlGenerator.generate(this.generationContext)).thenReturn( + ReportGenerationResultEnum.FAILURE); + + this.fixture.generateSiteReport(this.generationContext); + this.assertLocatedReportsDirectory(); + } + + @Test(expected = PitError.class) + public void testNoGeneratorsFound() { + this.generationContext.setSourceDataFormats(Arrays.asList("foo")); + this.fixture.generateSiteReport(this.generationContext); + } + + private void assertLocatedReportsDirectory() { + assertThat(this.generationContext.getReportsDataDirectory(), + sameInstance(this.locatedReportsDataDirectory)); + } + +} diff --git a/pitest-maven/src/test/java/org/pitest/maven/report/generator/XMLReportGeneratorTest.java b/pitest-maven/src/test/java/org/pitest/maven/report/generator/XMLReportGeneratorTest.java index 84ec215c8..7adb3a605 100644 --- a/pitest-maven/src/test/java/org/pitest/maven/report/generator/XMLReportGeneratorTest.java +++ b/pitest-maven/src/test/java/org/pitest/maven/report/generator/XMLReportGeneratorTest.java @@ -1,60 +1,60 @@ -/* - * Copyright 2015 Jason Fehr - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.maven.report.generator; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; - -import java.util.Arrays; - -import org.apache.maven.plugin.logging.Log; -import org.junit.Before; -import org.junit.Test; - -public class XMLReportGeneratorTest { - - private static final String XML_SOURCE_DATA_FORMAT = "XML"; - - private Log mockLogger; - private XMLReportGenerator fixture; - - @Before - public void setUp() { - this.mockLogger = mock(Log.class); - this.fixture = new XMLReportGenerator(); - } - - @Test - public void testName() { - assertThat(this.fixture.getGeneratorName(), is("XMLReportGenerator")); - } - - @Test - public void testNotExecuted() { - assertThat(this.fixture.generate(new ReportGenerationContext(null, null, - null, null, this.mockLogger, Arrays.asList(XML_SOURCE_DATA_FORMAT))), - sameInstance(ReportGenerationResultEnum.NOT_EXECUTED)); - } - - @Test - public void testSourceDataFormat() { - assertThat(this.fixture.getGeneratorDataFormat(), - equalTo(XML_SOURCE_DATA_FORMAT)); - } - -} +/* + * Copyright 2015 Jason Fehr + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.maven.report.generator; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; + +import java.util.Arrays; + +import org.apache.maven.plugin.logging.Log; +import org.junit.Before; +import org.junit.Test; + +public class XMLReportGeneratorTest { + + private static final String XML_SOURCE_DATA_FORMAT = "XML"; + + private Log mockLogger; + private XMLReportGenerator fixture; + + @Before + public void setUp() { + this.mockLogger = mock(Log.class); + this.fixture = new XMLReportGenerator(); + } + + @Test + public void testName() { + assertThat(this.fixture.getGeneratorName(), is("XMLReportGenerator")); + } + + @Test + public void testNotExecuted() { + assertThat(this.fixture.generate(new ReportGenerationContext(null, null, + null, null, this.mockLogger, Arrays.asList(XML_SOURCE_DATA_FORMAT))), + sameInstance(ReportGenerationResultEnum.NOT_EXECUTED)); + } + + @Test + public void testSourceDataFormat() { + assertThat(this.fixture.getGeneratorDataFormat(), + equalTo(XML_SOURCE_DATA_FORMAT)); + } + +} diff --git a/pitest/pom.xml b/pitest/pom.xml index 02ca268e1..dab029d4a 100644 --- a/pitest/pom.xml +++ b/pitest/pom.xml @@ -1,254 +1,254 @@ - - - 4.0.0 - - pitest-parent - org.pitest - 1.4.0-SNAPSHOT - - pitest - jar - pitest - http://pitest.org - Mutation testing system for Java. - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - true - - true - - - - - - test-jar - - - - - - - maven-surefire-plugin - - none:none - - - org/**/Test*.java - org/**/*Test.java - - - **/*$* - com/*/**.java - **/FullyCoveredByTestNGTesteeTest.java - - org.pitest.SystemTest - - - - org.testng - testng - ${testng.version} - - - - - - maven-failsafe-plugin - - org.pitest.SystemTest - - - - - integration-test - verify - - - - **/*.class - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - - - - org.ow2.asm:* - - - - - - - - - - org.objectweb.asm - org.pitest.reloc.asm - - - - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - javadoc - - jar - - - - - - - maven-antrun-plugin - 1.8 - - - prepare-package - - run - - - - - - - - - - - - - - - src/main/resources - true - - - - - - - org.ow2.asm - asm - ${asm.version} - - - org.ow2.asm - asm-commons - ${asm.version} - - - junit - junit - ${junit.version} - provided - - - org.ow2.asm - asm-util - ${asm.version} - test - - - org.ow2.asm - asm-analysis - ${asm.version} - test - - - commons-lang - commons-lang - 2.6 - test - - - jmock - jmock - 1.2.0 - test - - - org.testng - testng - ${testng.version} - provided - - - - org.hamcrest - hamcrest-core - ${hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${hamcrest.version} - test - - - pl.pragmatists - JUnitParams - 1.0.4 - test - - - nl.jqno.equalsverifier - equalsverifier - 1.7.5 - test - - - com.thoughtworks.xstream - xstream - 1.4.8 - test - - - - + + + 4.0.0 + + pitest-parent + org.pitest + 1.4.0-SNAPSHOT + + pitest + jar + pitest + http://pitest.org + Mutation testing system for Java. + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + + true + + + + + + test-jar + + + + + + + maven-surefire-plugin + + none:none + + + org/**/Test*.java + org/**/*Test.java + + + **/*$* + com/*/**.java + **/FullyCoveredByTestNGTesteeTest.java + + org.pitest.SystemTest + + + + org.testng + testng + ${testng.version} + + + + + + maven-failsafe-plugin + + org.pitest.SystemTest + + + + + integration-test + verify + + + + **/*.class + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + + org.ow2.asm:* + + + + + + + + + + org.objectweb.asm + org.pitest.reloc.asm + + + + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + javadoc + + jar + + + + + + + maven-antrun-plugin + 1.8 + + + prepare-package + + run + + + + + + + + + + + + + + + src/main/resources + true + + + + + + + org.ow2.asm + asm + ${asm.version} + + + org.ow2.asm + asm-commons + ${asm.version} + + + junit + junit + ${junit.version} + provided + + + org.ow2.asm + asm-util + ${asm.version} + test + + + org.ow2.asm + asm-analysis + ${asm.version} + test + + + commons-lang + commons-lang + 2.6 + test + + + jmock + jmock + 1.2.0 + test + + + org.testng + testng + ${testng.version} + provided + + + + org.hamcrest + hamcrest-core + ${hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${hamcrest.version} + test + + + pl.pragmatists + JUnitParams + 1.0.4 + test + + + nl.jqno.equalsverifier + equalsverifier + 1.7.5 + test + + + com.thoughtworks.xstream + xstream + 1.4.8 + test + + + + diff --git a/pitest/src/main/java/org/pitest/boot/HotSwapAgent.java b/pitest/src/main/java/org/pitest/boot/HotSwapAgent.java index b4204c1cc..a1901af47 100644 --- a/pitest/src/main/java/org/pitest/boot/HotSwapAgent.java +++ b/pitest/src/main/java/org/pitest/boot/HotSwapAgent.java @@ -1,61 +1,61 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.boot; - -import java.lang.instrument.ClassDefinition; -import java.lang.instrument.ClassFileTransformer; -import java.lang.instrument.Instrumentation; -import java.lang.instrument.UnmodifiableClassException; - -public class HotSwapAgent { - - private static Instrumentation instrumentation; - - public static void premain(final String agentArguments, // NO_UCD - final Instrumentation inst) { - System.out.println("Installing PIT agent"); - instrumentation = inst; - } - - public static void addTransformer(final ClassFileTransformer transformer) { - instrumentation.addTransformer(transformer); - } - - public static void agentmain(final String agentArguments, // NO_UCD - final Instrumentation inst) throws Exception { - instrumentation = inst; - } - - public static boolean hotSwap(final Class mutateMe, final byte[] bytes) { // NO_UCD - - final ClassDefinition[] definitions = { new ClassDefinition(mutateMe, bytes) }; - - try { - instrumentation.redefineClasses(definitions); - - return true; - } catch (final ClassNotFoundException e) { - // swallow - } catch (final UnmodifiableClassException e) { - // swallow - } catch (final java.lang.VerifyError e) { - // swallow - } catch (final java.lang.InternalError e) { - // swallow - } - return false; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.boot; + +import java.lang.instrument.ClassDefinition; +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.Instrumentation; +import java.lang.instrument.UnmodifiableClassException; + +public class HotSwapAgent { + + private static Instrumentation instrumentation; + + public static void premain(final String agentArguments, // NO_UCD + final Instrumentation inst) { + System.out.println("Installing PIT agent"); + instrumentation = inst; + } + + public static void addTransformer(final ClassFileTransformer transformer) { + instrumentation.addTransformer(transformer); + } + + public static void agentmain(final String agentArguments, // NO_UCD + final Instrumentation inst) throws Exception { + instrumentation = inst; + } + + public static boolean hotSwap(final Class mutateMe, final byte[] bytes) { // NO_UCD + + final ClassDefinition[] definitions = { new ClassDefinition(mutateMe, bytes) }; + + try { + instrumentation.redefineClasses(definitions); + + return true; + } catch (final ClassNotFoundException e) { + // swallow + } catch (final UnmodifiableClassException e) { + // swallow + } catch (final java.lang.VerifyError e) { + // swallow + } catch (final java.lang.InternalError e) { + // swallow + } + return false; + } + +} diff --git a/pitest/src/main/java/org/pitest/bytecode/FrameOptions.java b/pitest/src/main/java/org/pitest/bytecode/FrameOptions.java index 1332be153..dc29ea46d 100644 --- a/pitest/src/main/java/org/pitest/bytecode/FrameOptions.java +++ b/pitest/src/main/java/org/pitest/bytecode/FrameOptions.java @@ -1,33 +1,33 @@ -package org.pitest.bytecode; - -import org.objectweb.asm.ClassWriter; - -public class FrameOptions { - - private static final int JAVA_7 = 51; - - /** - * Java 7 and above require frame info for class version above 7. The ASM - * compute frame options does not support the JSR opcode used by some pre 7 - * compilers when generating java 5 bytecode. - * - * We dodge this issue by only computing frames for classes with a version - * above 6. - * - * @param bs - * a class - * @return appropriate flags - */ - public static int pickFlags(byte[] bs) { - if (needsFrames(bs)) { - return ClassWriter.COMPUTE_FRAMES; - } - return ClassWriter.COMPUTE_MAXS; - } - - public static boolean needsFrames(byte[] bs) { - final short majorVersion = (short) (((bs[6] & 0xFF) << 8) | (bs[7] & 0xFF)); - return majorVersion >= JAVA_7; - } - -} +package org.pitest.bytecode; + +import org.objectweb.asm.ClassWriter; + +public class FrameOptions { + + private static final int JAVA_7 = 51; + + /** + * Java 7 and above require frame info for class version above 7. The ASM + * compute frame options does not support the JSR opcode used by some pre 7 + * compilers when generating java 5 bytecode. + * + * We dodge this issue by only computing frames for classes with a version + * above 6. + * + * @param bs + * a class + * @return appropriate flags + */ + public static int pickFlags(byte[] bs) { + if (needsFrames(bs)) { + return ClassWriter.COMPUTE_FRAMES; + } + return ClassWriter.COMPUTE_MAXS; + } + + public static boolean needsFrames(byte[] bs) { + final short majorVersion = (short) (((bs[6] & 0xFF) << 8) | (bs[7] & 0xFF)); + return majorVersion >= JAVA_7; + } + +} diff --git a/pitest/src/main/java/org/pitest/bytecode/NullVisitor.java b/pitest/src/main/java/org/pitest/bytecode/NullVisitor.java index 5d570dcc4..de06a2a79 100644 --- a/pitest/src/main/java/org/pitest/bytecode/NullVisitor.java +++ b/pitest/src/main/java/org/pitest/bytecode/NullVisitor.java @@ -1,240 +1,240 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.bytecode; - -import org.objectweb.asm.AnnotationVisitor; -import org.objectweb.asm.Attribute; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -public class NullVisitor extends ClassVisitor { - - public NullVisitor() { - super(Opcodes.ASM6); - } - - public static class NullAnnotationVisitor extends AnnotationVisitor { - - NullAnnotationVisitor() { - super(Opcodes.ASM6); - } - - @Override - public void visit(final String arg0, final Object arg1) { - } - - @Override - public AnnotationVisitor visitAnnotation(final String arg0, - final String arg1) { - return new NullAnnotationVisitor(); - } - - @Override - public AnnotationVisitor visitArray(final String arg0) { - return new NullAnnotationVisitor(); - } - - @Override - public void visitEnd() { - } - - @Override - public void visitEnum(final String arg0, final String arg1, - final String arg2) { - } - - } - - public static class NullMethodVisitor extends MethodVisitor { - - NullMethodVisitor() { - super(Opcodes.ASM6); - } - - @Override - public AnnotationVisitor visitAnnotation(final String arg0, - final boolean arg1) { - return new NullAnnotationVisitor(); - } - - @Override - public AnnotationVisitor visitAnnotationDefault() { - return new NullAnnotationVisitor(); - } - - @Override - public void visitAttribute(final Attribute arg0) { - } - - @Override - public void visitCode() { - } - - @Override - public void visitEnd() { - } - - @Override - public void visitFieldInsn(final int arg0, final String arg1, - final String arg2, final String arg3) { - } - - @Override - public void visitFrame(final int arg0, final int arg1, final Object[] arg2, - final int arg3, final Object[] arg4) { - } - - @Override - public void visitIincInsn(final int arg0, final int arg1) { - } - - @Override - public void visitInsn(final int arg0) { - } - - @Override - public void visitIntInsn(final int arg0, final int arg1) { - } - - @Override - public void visitJumpInsn(final int arg0, final Label arg1) { - } - - @Override - public void visitLabel(final Label arg0) { - } - - @Override - public void visitLdcInsn(final Object arg0) { - } - - @Override - public void visitLineNumber(final int arg0, final Label arg1) { - } - - @Override - public void visitLocalVariable(final String arg0, final String arg1, - final String arg2, final Label arg3, final Label arg4, final int arg5) { - } - - @Override - public void visitLookupSwitchInsn(final Label arg0, final int[] arg1, - final Label[] arg2) { - } - - @Override - public void visitMaxs(final int arg0, final int arg1) { - } - - @Override - public void visitMethodInsn(final int arg0, final String arg1, - final String arg2, final String arg3) { - } - - @Override - public void visitMultiANewArrayInsn(final String arg0, final int arg1) { - } - - @Override - public AnnotationVisitor visitParameterAnnotation(final int arg0, - final String arg1, final boolean arg2) { - return new NullAnnotationVisitor(); - } - - @Override - public void visitTableSwitchInsn(final int arg0, final int arg1, - final Label arg2, final Label... labels) { - } - - @Override - public void visitTryCatchBlock(final Label arg0, final Label arg1, - final Label arg2, final String arg3) { - } - - @Override - public void visitTypeInsn(final int arg0, final String arg1) { - } - - @Override - public void visitVarInsn(final int arg0, final int arg1) { - } - - }; - - @Override - public void visit(final int arg0, final int arg1, final String arg2, - final String arg3, final String arg4, final String[] arg5) { - } - - @Override - public AnnotationVisitor visitAnnotation(final String arg0, final boolean arg1) { - return new NullAnnotationVisitor(); - } - - @Override - public void visitAttribute(final Attribute arg0) { - } - - @Override - public void visitEnd() { - } - - @Override - public FieldVisitor visitField(final int arg0, final String arg1, - final String arg2, final String arg3, final Object arg4) { - return new FieldVisitor(Opcodes.ASM6) { - - @Override - public AnnotationVisitor visitAnnotation(final String arg0, - final boolean arg1) { - return new NullAnnotationVisitor(); - } - - @Override - public void visitAttribute(final Attribute arg0) { - } - - @Override - public void visitEnd() { - } - - }; - } - - @Override - public void visitInnerClass(final String arg0, final String arg1, - final String arg2, final int arg3) { - } - - @Override - public MethodVisitor visitMethod(final int arg0, final String arg1, - final String arg2, final String arg3, final String[] arg4) { - - return new NullMethodVisitor(); - } - - @Override - public void visitOuterClass(final String arg0, final String arg1, - final String arg2) { - } - - @Override - public void visitSource(final String arg0, final String arg1) { - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.bytecode; + +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.Attribute; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +public class NullVisitor extends ClassVisitor { + + public NullVisitor() { + super(Opcodes.ASM6); + } + + public static class NullAnnotationVisitor extends AnnotationVisitor { + + NullAnnotationVisitor() { + super(Opcodes.ASM6); + } + + @Override + public void visit(final String arg0, final Object arg1) { + } + + @Override + public AnnotationVisitor visitAnnotation(final String arg0, + final String arg1) { + return new NullAnnotationVisitor(); + } + + @Override + public AnnotationVisitor visitArray(final String arg0) { + return new NullAnnotationVisitor(); + } + + @Override + public void visitEnd() { + } + + @Override + public void visitEnum(final String arg0, final String arg1, + final String arg2) { + } + + } + + public static class NullMethodVisitor extends MethodVisitor { + + NullMethodVisitor() { + super(Opcodes.ASM6); + } + + @Override + public AnnotationVisitor visitAnnotation(final String arg0, + final boolean arg1) { + return new NullAnnotationVisitor(); + } + + @Override + public AnnotationVisitor visitAnnotationDefault() { + return new NullAnnotationVisitor(); + } + + @Override + public void visitAttribute(final Attribute arg0) { + } + + @Override + public void visitCode() { + } + + @Override + public void visitEnd() { + } + + @Override + public void visitFieldInsn(final int arg0, final String arg1, + final String arg2, final String arg3) { + } + + @Override + public void visitFrame(final int arg0, final int arg1, final Object[] arg2, + final int arg3, final Object[] arg4) { + } + + @Override + public void visitIincInsn(final int arg0, final int arg1) { + } + + @Override + public void visitInsn(final int arg0) { + } + + @Override + public void visitIntInsn(final int arg0, final int arg1) { + } + + @Override + public void visitJumpInsn(final int arg0, final Label arg1) { + } + + @Override + public void visitLabel(final Label arg0) { + } + + @Override + public void visitLdcInsn(final Object arg0) { + } + + @Override + public void visitLineNumber(final int arg0, final Label arg1) { + } + + @Override + public void visitLocalVariable(final String arg0, final String arg1, + final String arg2, final Label arg3, final Label arg4, final int arg5) { + } + + @Override + public void visitLookupSwitchInsn(final Label arg0, final int[] arg1, + final Label[] arg2) { + } + + @Override + public void visitMaxs(final int arg0, final int arg1) { + } + + @Override + public void visitMethodInsn(final int arg0, final String arg1, + final String arg2, final String arg3) { + } + + @Override + public void visitMultiANewArrayInsn(final String arg0, final int arg1) { + } + + @Override + public AnnotationVisitor visitParameterAnnotation(final int arg0, + final String arg1, final boolean arg2) { + return new NullAnnotationVisitor(); + } + + @Override + public void visitTableSwitchInsn(final int arg0, final int arg1, + final Label arg2, final Label... labels) { + } + + @Override + public void visitTryCatchBlock(final Label arg0, final Label arg1, + final Label arg2, final String arg3) { + } + + @Override + public void visitTypeInsn(final int arg0, final String arg1) { + } + + @Override + public void visitVarInsn(final int arg0, final int arg1) { + } + + }; + + @Override + public void visit(final int arg0, final int arg1, final String arg2, + final String arg3, final String arg4, final String[] arg5) { + } + + @Override + public AnnotationVisitor visitAnnotation(final String arg0, final boolean arg1) { + return new NullAnnotationVisitor(); + } + + @Override + public void visitAttribute(final Attribute arg0) { + } + + @Override + public void visitEnd() { + } + + @Override + public FieldVisitor visitField(final int arg0, final String arg1, + final String arg2, final String arg3, final Object arg4) { + return new FieldVisitor(Opcodes.ASM6) { + + @Override + public AnnotationVisitor visitAnnotation(final String arg0, + final boolean arg1) { + return new NullAnnotationVisitor(); + } + + @Override + public void visitAttribute(final Attribute arg0) { + } + + @Override + public void visitEnd() { + } + + }; + } + + @Override + public void visitInnerClass(final String arg0, final String arg1, + final String arg2, final int arg3) { + } + + @Override + public MethodVisitor visitMethod(final int arg0, final String arg1, + final String arg2, final String arg3, final String[] arg4) { + + return new NullMethodVisitor(); + } + + @Override + public void visitOuterClass(final String arg0, final String arg1, + final String arg2) { + } + + @Override + public void visitSource(final String arg0, final String arg1) { + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/AddlerHash.java b/pitest/src/main/java/org/pitest/classinfo/AddlerHash.java index a48510b71..09980e600 100644 --- a/pitest/src/main/java/org/pitest/classinfo/AddlerHash.java +++ b/pitest/src/main/java/org/pitest/classinfo/AddlerHash.java @@ -1,14 +1,14 @@ -package org.pitest.classinfo; - -import java.util.zip.Adler32; - -public class AddlerHash implements HashFunction { - - @Override - public long hash(final byte[] value) { - final Adler32 adler = new Adler32(); - adler.update(value); - return adler.getValue(); - } - -} +package org.pitest.classinfo; + +import java.util.zip.Adler32; + +public class AddlerHash implements HashFunction { + + @Override + public long hash(final byte[] value) { + final Adler32 adler = new Adler32(); + adler.update(value); + return adler.getValue(); + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/BridgeMethodFilter.java b/pitest/src/main/java/org/pitest/classinfo/BridgeMethodFilter.java index 4db0baa1e..d46e7a5fd 100644 --- a/pitest/src/main/java/org/pitest/classinfo/BridgeMethodFilter.java +++ b/pitest/src/main/java/org/pitest/classinfo/BridgeMethodFilter.java @@ -1,35 +1,35 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import org.objectweb.asm.Opcodes; -import org.pitest.functional.F5; - -public enum BridgeMethodFilter implements -F5 { - - INSTANCE; - - @Override - public Boolean apply(final Integer access, final String name, - final String desc, final String signature, final String[] exceptions) { - return (isSynthetic(access)); - } - - private static boolean isSynthetic(final Integer access) { - return (access & Opcodes.ACC_BRIDGE) == 0; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import org.objectweb.asm.Opcodes; +import org.pitest.functional.F5; + +public enum BridgeMethodFilter implements +F5 { + + INSTANCE; + + @Override + public Boolean apply(final Integer access, final String name, + final String desc, final String signature, final String[] exceptions) { + return (isSynthetic(access)); + } + + private static boolean isSynthetic(final Integer access) { + return (access & Opcodes.ACC_BRIDGE) == 0; + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/CachingByteArraySource.java b/pitest/src/main/java/org/pitest/classinfo/CachingByteArraySource.java index e09224fa1..d5d48aa74 100644 --- a/pitest/src/main/java/org/pitest/classinfo/CachingByteArraySource.java +++ b/pitest/src/main/java/org/pitest/classinfo/CachingByteArraySource.java @@ -1,43 +1,43 @@ -package org.pitest.classinfo; - -import java.util.LinkedHashMap; -import java.util.Map; - -import java.util.Optional; - -public class CachingByteArraySource implements ClassByteArraySource { - - private final ClassByteArraySource child; - private final Map> cache; - - public CachingByteArraySource(ClassByteArraySource child, int maxSize) { - this.child = child; - this.cache = new FixedSizeHashMap<>(maxSize); - } - - @Override - public Optional getBytes(String clazz) { - Optional maybeBytes = this.cache.get(clazz); - if (maybeBytes != null) { - return maybeBytes; - } - - maybeBytes = this.child.getBytes(clazz); - this.cache.put(clazz, maybeBytes); - return maybeBytes; - - } - -} - -class FixedSizeHashMap extends LinkedHashMap { - private final int maxsize; - FixedSizeHashMap(int maxsize) { - this.maxsize = maxsize; - } - private static final long serialVersionUID = 2648931151905594122L; - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > this.maxsize; -} -}; +package org.pitest.classinfo; + +import java.util.LinkedHashMap; +import java.util.Map; + +import java.util.Optional; + +public class CachingByteArraySource implements ClassByteArraySource { + + private final ClassByteArraySource child; + private final Map> cache; + + public CachingByteArraySource(ClassByteArraySource child, int maxSize) { + this.child = child; + this.cache = new FixedSizeHashMap<>(maxSize); + } + + @Override + public Optional getBytes(String clazz) { + Optional maybeBytes = this.cache.get(clazz); + if (maybeBytes != null) { + return maybeBytes; + } + + maybeBytes = this.child.getBytes(clazz); + this.cache.put(clazz, maybeBytes); + return maybeBytes; + + } + +} + +class FixedSizeHashMap extends LinkedHashMap { + private final int maxsize; + FixedSizeHashMap(int maxsize) { + this.maxsize = maxsize; + } + private static final long serialVersionUID = 2648931151905594122L; + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > this.maxsize; +} +}; diff --git a/pitest/src/main/java/org/pitest/classinfo/ClassByteArraySource.java b/pitest/src/main/java/org/pitest/classinfo/ClassByteArraySource.java index dba514656..28b96a2de 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ClassByteArraySource.java +++ b/pitest/src/main/java/org/pitest/classinfo/ClassByteArraySource.java @@ -1,28 +1,32 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.util.Optional; - -public interface ClassByteArraySource { - - /** - * Returns bytes for a class represented in java/lang/String format - * @param clazz classname in com.example.Foo format - * @return bytes option of byte[] - */ - Optional getBytes(String clazz); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.util.Optional; + +public interface ClassByteArraySource { + + /** + * Returns bytes for a class represented in java/lang/String format. Implemented + * in CachingByteArraySource, ClassloaderByteArraySource, + * ClassPathByteArraySource, ResourceFolderByteArraySource + * + * @param clazz + * classname in com.example.Foo format + * @return bytes option of byte[] + */ + Optional getBytes(String clazz); + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/ClassIdentifier.java b/pitest/src/main/java/org/pitest/classinfo/ClassIdentifier.java index 75f7ded3d..74f462eeb 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ClassIdentifier.java +++ b/pitest/src/main/java/org/pitest/classinfo/ClassIdentifier.java @@ -1,60 +1,60 @@ -package org.pitest.classinfo; - -import java.io.Serializable; - -public final class ClassIdentifier implements Serializable { - - private static final long serialVersionUID = 1L; - - private final long hash; - private final ClassName name; - - public ClassIdentifier(final long hash, final ClassName name) { - this.hash = hash; - this.name = name; - } - - public long getHash() { - return this.hash; - } - - public ClassName getName() { - return this.name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + (int) (this.hash ^ (this.hash >>> 32)); - result = (prime * result) - + ((this.name == null) ? 0 : this.name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ClassIdentifier other = (ClassIdentifier) obj; - if (this.hash != other.hash) { - return false; - } - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - return true; - } - -} +package org.pitest.classinfo; + +import java.io.Serializable; + +public final class ClassIdentifier implements Serializable { + + private static final long serialVersionUID = 1L; + + private final long hash; + private final ClassName name; + + public ClassIdentifier(final long hash, final ClassName name) { + this.hash = hash; + this.name = name; + } + + public long getHash() { + return this.hash; + } + + public ClassName getName() { + return this.name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (this.hash ^ (this.hash >>> 32)); + result = (prime * result) + + ((this.name == null) ? 0 : this.name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ClassIdentifier other = (ClassIdentifier) obj; + if (this.hash != other.hash) { + return false; + } + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/ClassInfo.java b/pitest/src/main/java/org/pitest/classinfo/ClassInfo.java index 1aa0b145b..0c240ef09 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ClassInfo.java +++ b/pitest/src/main/java/org/pitest/classinfo/ClassInfo.java @@ -1,171 +1,174 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.lang.annotation.Annotation; -import java.math.BigInteger; -import java.util.Collection; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.objectweb.asm.Opcodes; -import org.pitest.functional.FCollection; -import java.util.Optional; - -public class ClassInfo { - - private final ClassIdentifier id; - - private final int access; - private final Set codeLines; - private final ClassPointer outerClass; - private final ClassPointer superClass; - private final Collection annotations; - private final String sourceFile; - private final Map classAnnotationValues; - - public ClassInfo(final ClassPointer superClass, - final ClassPointer outerClass, final ClassInfoBuilder builder) { - this.superClass = superClass; - this.outerClass = outerClass; - this.id = builder.id; - this.access = builder.access; - this.codeLines = builder.codeLines; - this.annotations = FCollection.map(builder.annotations, - ClassName.stringToClassName()); - this.sourceFile = builder.sourceFile; - this.classAnnotationValues = builder.classAnnotationValues; - } - - public int getNumberOfCodeLines() { - return this.codeLines.size(); - } - - public boolean isCodeLine(final int line) { - return this.codeLines.contains(line); - } - - public ClassIdentifier getId() { - return this.id; - } - - public ClassName getName() { - return this.id.getName(); - } - - public boolean isInterface() { - return (this.access & Opcodes.ACC_INTERFACE) != 0; - } - - public boolean isAbstract() { - return (this.access & Opcodes.ACC_ABSTRACT) != 0; - } - - public boolean isSynthetic() { - return (this.access & Opcodes.ACC_SYNTHETIC) != 0; - } - - public boolean isTopLevelClass() { - return !getOuterClass().isPresent(); - } - - public Optional getOuterClass() { - return this.outerClass.fetch(); - } - - public Optional getSuperClass() { - return getParent(); - } - - public String getSourceFileName() { - return this.sourceFile; - } - - public boolean hasAnnotation(final Class annotation) { - return hasAnnotation(ClassName.fromClass(annotation)); - } - - public boolean hasAnnotation(final ClassName annotation) { - return this.annotations.contains(annotation); - } - - public Object getClassAnnotationValue(final ClassName annotation) { - return this.classAnnotationValues.get(annotation); - } - - public boolean descendsFrom(final Class clazz) { - return descendsFrom(ClassName.fromClass(clazz)); - } - - public HierarchicalClassId getHierarchicalId() { - return new HierarchicalClassId(this.id, getDeepHash()); - } - - public BigInteger getDeepHash() { - BigInteger hash = getHash(); - final Optional parent = getParent(); - if (parent.isPresent()) { - hash = hash.add(parent.get().getHash()); - } - final Optional outer = getOuterClass(); - if (outer.isPresent()) { - hash = hash.add(outer.get().getHash()); - } - return hash; - } - - public BigInteger getHash() { - return BigInteger.valueOf(this.id.getHash()); - } - - private Optional getParent() { - if (this.superClass == null) { - return Optional.empty(); - } - return this.superClass.fetch(); - } - - private boolean descendsFrom(final ClassName clazz) { - - if (!this.getSuperClass().isPresent()) { - return false; - } - - if (this.getSuperClass().get().getName().equals(clazz)) { - return true; - } - - return getSuperClass().get().descendsFrom(clazz); - } - - public static Predicate matchIfAbstract() { - return a -> a.isAbstract(); - } - - @Override - public String toString() { - return this.id.getName().asJavaName(); - } - - public static Function toClassName() { - return a -> a.getName(); - } - - public static Function toFullClassId() { - return a -> a.getHierarchicalId(); - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.lang.annotation.Annotation; +import java.math.BigInteger; +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.objectweb.asm.Opcodes; +import org.pitest.functional.FCollection; +import java.util.Optional; + +/** + * Create a ClasInfo object from superClass, outerClass and a ClassInfoBuilder + * This is not the same as ClassInfo.java in package engine.gregor. + * + */ +public class ClassInfo { + + private final ClassIdentifier id; + + private final int access; + private final Set codeLines; + private final ClassPointer outerClass; + private final ClassPointer superClass; + private final Collection annotations; + private final String sourceFile; + private final Map classAnnotationValues; + + public ClassInfo(final ClassPointer superClass, final ClassPointer outerClass, final ClassInfoBuilder builder) { + this.superClass = superClass; + this.outerClass = outerClass; + this.id = builder.id; + this.access = builder.access; + this.codeLines = builder.codeLines; + this.annotations = FCollection.map(builder.annotations, ClassName.stringToClassName()); + this.sourceFile = builder.sourceFile; + this.classAnnotationValues = builder.classAnnotationValues; + } + + public int getNumberOfCodeLines() { + return this.codeLines.size(); + } + + public boolean isCodeLine(final int line) { + return this.codeLines.contains(line); + } + + public ClassIdentifier getId() { + return this.id; + } + + public ClassName getName() { + return this.id.getName(); + } + + public boolean isInterface() { + return (this.access & Opcodes.ACC_INTERFACE) != 0; + } + + public boolean isAbstract() { + return (this.access & Opcodes.ACC_ABSTRACT) != 0; + } + + public boolean isSynthetic() { + return (this.access & Opcodes.ACC_SYNTHETIC) != 0; + } + + public boolean isTopLevelClass() { + return !getOuterClass().isPresent(); + } + + public Optional getOuterClass() { + return this.outerClass.fetch(); + } + + public Optional getSuperClass() { + return getParent(); + } + + public String getSourceFileName() { + return this.sourceFile; + } + + public boolean hasAnnotation(final Class annotation) { + return hasAnnotation(ClassName.fromClass(annotation)); + } + + public boolean hasAnnotation(final ClassName annotation) { + return this.annotations.contains(annotation); + } + + public Object getClassAnnotationValue(final ClassName annotation) { + return this.classAnnotationValues.get(annotation); + } + + public boolean descendsFrom(final Class clazz) { + return descendsFrom(ClassName.fromClass(clazz)); + } + + public HierarchicalClassId getHierarchicalId() { + return new HierarchicalClassId(this.id, getDeepHash()); + } + + public BigInteger getDeepHash() { + BigInteger hash = getHash(); + final Optional parent = getParent(); + if (parent.isPresent()) { + hash = hash.add(parent.get().getHash()); + } + final Optional outer = getOuterClass(); + if (outer.isPresent()) { + hash = hash.add(outer.get().getHash()); + } + return hash; + } + + public BigInteger getHash() { + return BigInteger.valueOf(this.id.getHash()); + } + + private Optional getParent() { + if (this.superClass == null) { + return Optional.empty(); + } + return this.superClass.fetch(); + } + + private boolean descendsFrom(final ClassName clazz) { + + if (!this.getSuperClass().isPresent()) { + return false; + } + + if (this.getSuperClass().get().getName().equals(clazz)) { + return true; + } + + return getSuperClass().get().descendsFrom(clazz); + } + + public static Predicate matchIfAbstract() { + return a -> a.isAbstract(); + } + + @Override + public String toString() { + return this.id.getName().asJavaName(); + } + + public static Function toClassName() { + return a -> a.getName(); + } + + public static Function toFullClassId() { + return a -> a.getHierarchicalId(); + } +} diff --git a/pitest/src/main/java/org/pitest/classinfo/ClassInfoBuilder.java b/pitest/src/main/java/org/pitest/classinfo/ClassInfoBuilder.java index 72eaae314..fdcd9fe38 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ClassInfoBuilder.java +++ b/pitest/src/main/java/org/pitest/classinfo/ClassInfoBuilder.java @@ -1,47 +1,47 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -class ClassInfoBuilder { - - int access; - ClassIdentifier id; - String outerClass; - String superClass; - String sourceFile; - final Set codeLines = new HashSet<>(); - final Set annotations = new HashSet<>(0); - final Map classAnnotationValues = new HashMap<>( - 0); - - public void registerCodeLine(final int line) { - this.codeLines.add(line); - } - - public void registerAnnotation(final String annotation) { - this.annotations.add(annotation); - } - - public void registerClassAnnotationValue(final ClassName annotation, - final Object value) { - this.classAnnotationValues.put(annotation, value); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +class ClassInfoBuilder { + + int access; + ClassIdentifier id; + String outerClass; + String superClass; + String sourceFile; + final Set codeLines = new HashSet<>(); + final Set annotations = new HashSet<>(0); + final Map classAnnotationValues = new HashMap<>( + 0); + + public void registerCodeLine(final int line) { + this.codeLines.add(line); + } + + public void registerAnnotation(final String annotation) { + this.annotations.add(annotation); + } + + public void registerClassAnnotationValue(final ClassName annotation, + final Object value) { + this.classAnnotationValues.put(annotation, value); + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/ClassInfoSource.java b/pitest/src/main/java/org/pitest/classinfo/ClassInfoSource.java index 6c225c49d..8dac93fd2 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ClassInfoSource.java +++ b/pitest/src/main/java/org/pitest/classinfo/ClassInfoSource.java @@ -1,7 +1,7 @@ -package org.pitest.classinfo; - -import java.util.Optional; - -public interface ClassInfoSource { - Optional fetchClass(ClassName name); -} +package org.pitest.classinfo; + +import java.util.Optional; + +public interface ClassInfoSource { + Optional fetchClass(ClassName name); +} diff --git a/pitest/src/main/java/org/pitest/classinfo/ClassInfoVisitor.java b/pitest/src/main/java/org/pitest/classinfo/ClassInfoVisitor.java index e06593662..8c64c399c 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ClassInfoVisitor.java +++ b/pitest/src/main/java/org/pitest/classinfo/ClassInfoVisitor.java @@ -1,176 +1,176 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.util.ArrayList; -import java.util.List; - -import org.objectweb.asm.AnnotationVisitor; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.pitest.bytecode.NullVisitor; - -public final class ClassInfoVisitor extends MethodFilteringAdapter { - - private final ClassInfoBuilder classInfo; - - private ClassInfoVisitor(final ClassInfoBuilder classInfo, - final ClassVisitor writer) { - super(writer, BridgeMethodFilter.INSTANCE); - this.classInfo = classInfo; - } - - public static ClassInfoBuilder getClassInfo(final ClassName name, - final byte[] bytes, final long hash) { - final ClassReader reader = new ClassReader(bytes); - final ClassVisitor writer = new NullVisitor(); - - final ClassInfoBuilder info = new ClassInfoBuilder(); - info.id = new ClassIdentifier(hash, name); - reader.accept(new ClassInfoVisitor(info, writer), 0); - return info; - } - - @Override - public void visitSource(final String source, final String debug) { - super.visitSource(source, debug); - this.classInfo.sourceFile = source; - } - - @Override - public void visit(final int version, final int access, final String name, - final String signature, final String superName, final String[] interfaces) { - super.visit(version, access, name, signature, superName, interfaces); - this.classInfo.access = access; - this.classInfo.superClass = superName; - } - - @Override - public void visitOuterClass(final String owner, final String name, - final String desc) { - super.visitOuterClass(owner, name, desc); - this.classInfo.outerClass = owner; - } - - @Override - public void visitInnerClass(final String name, final String outerName, - final String innerName, final int access) { - super.visitInnerClass(name, outerName, innerName, access); - if ((outerName != null) - && this.classInfo.id.getName().equals(ClassName.fromString(name))) { - this.classInfo.outerClass = outerName; - } - } - - @Override - public AnnotationVisitor visitAnnotation(final String desc, - final boolean visible) { - final String type = desc.substring(1, desc.length() - 1); - this.classInfo.registerAnnotation(type); - return new ClassAnnotationValueVisitor(this.classInfo, ClassName.fromString(type)); - } - - @Override - public MethodVisitor visitMethodIfRequired(final int access, - final String name, final String desc, final String signature, - final String[] exceptions, final MethodVisitor methodVisitor) { - - return new InfoMethodVisitor(this.classInfo, methodVisitor); - - } - - private static class ClassAnnotationValueVisitor extends AnnotationVisitor { - private final ClassInfoBuilder classInfo; - private final ClassName annotation; - - ClassAnnotationValueVisitor(ClassInfoBuilder classInfo, - ClassName annotation) { - super(Opcodes.ASM6, null); - this.classInfo = classInfo; - this.annotation = annotation; - } - - @Override - public void visit(String name, Object value) { - if (name.equals("value")) { - this.classInfo.registerClassAnnotationValue(this.annotation, - simplify(value)); - } - super.visit(name, value); - } - - @Override - public AnnotationVisitor visitArray(String name) { - if (name.equals("value")) { - final List arrayValue = new ArrayList<>(); - - return new AnnotationVisitor(Opcodes.ASM6, null) { - @Override - public void visit(String name, Object value) { - arrayValue.add(simplify(value)); - super.visit(name, value); - } - - @Override - public void visitEnd() { - ClassAnnotationValueVisitor.this.classInfo - .registerClassAnnotationValue( - ClassAnnotationValueVisitor.this.annotation, - arrayValue.toArray()); - } - }; - } - return super.visitArray(name); - } - - private static Object simplify(Object value) { - Object newValue = value; - if (value instanceof Type) { - newValue = ((Type) value).getClassName(); - } - return newValue; - } - } -} - -class InfoMethodVisitor extends MethodVisitor { - private final ClassInfoBuilder classInfo; - - InfoMethodVisitor(final ClassInfoBuilder classInfo, - final MethodVisitor writer) { - super(Opcodes.ASM6, writer); - this.classInfo = classInfo; - } - - @Override - public void visitLineNumber(final int line, final Label start) { - - this.classInfo.registerCodeLine(line); - - } - - @Override - public AnnotationVisitor visitAnnotation(final String desc, - final boolean visible) { - final String type = desc.substring(1, desc.length() - 1); - this.classInfo.registerAnnotation(type); - return super.visitAnnotation(desc, visible); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.util.ArrayList; +import java.util.List; + +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.pitest.bytecode.NullVisitor; + +public final class ClassInfoVisitor extends MethodFilteringAdapter { + + private final ClassInfoBuilder classInfo; + + private ClassInfoVisitor(final ClassInfoBuilder classInfo, + final ClassVisitor writer) { + super(writer, BridgeMethodFilter.INSTANCE); + this.classInfo = classInfo; + } + + public static ClassInfoBuilder getClassInfo(final ClassName name, + final byte[] bytes, final long hash) { + final ClassReader reader = new ClassReader(bytes); + final ClassVisitor writer = new NullVisitor(); + + final ClassInfoBuilder info = new ClassInfoBuilder(); + info.id = new ClassIdentifier(hash, name); + reader.accept(new ClassInfoVisitor(info, writer), 0); + return info; + } + + @Override + public void visitSource(final String source, final String debug) { + super.visitSource(source, debug); + this.classInfo.sourceFile = source; + } + + @Override + public void visit(final int version, final int access, final String name, + final String signature, final String superName, final String[] interfaces) { + super.visit(version, access, name, signature, superName, interfaces); + this.classInfo.access = access; + this.classInfo.superClass = superName; + } + + @Override + public void visitOuterClass(final String owner, final String name, + final String desc) { + super.visitOuterClass(owner, name, desc); + this.classInfo.outerClass = owner; + } + + @Override + public void visitInnerClass(final String name, final String outerName, + final String innerName, final int access) { + super.visitInnerClass(name, outerName, innerName, access); + if ((outerName != null) + && this.classInfo.id.getName().equals(ClassName.fromString(name))) { + this.classInfo.outerClass = outerName; + } + } + + @Override + public AnnotationVisitor visitAnnotation(final String desc, + final boolean visible) { + final String type = desc.substring(1, desc.length() - 1); + this.classInfo.registerAnnotation(type); + return new ClassAnnotationValueVisitor(this.classInfo, ClassName.fromString(type)); + } + + @Override + public MethodVisitor visitMethodIfRequired(final int access, + final String name, final String desc, final String signature, + final String[] exceptions, final MethodVisitor methodVisitor) { + + return new InfoMethodVisitor(this.classInfo, methodVisitor); + + } + + private static class ClassAnnotationValueVisitor extends AnnotationVisitor { + private final ClassInfoBuilder classInfo; + private final ClassName annotation; + + ClassAnnotationValueVisitor(ClassInfoBuilder classInfo, + ClassName annotation) { + super(Opcodes.ASM6, null); + this.classInfo = classInfo; + this.annotation = annotation; + } + + @Override + public void visit(String name, Object value) { + if (name.equals("value")) { + this.classInfo.registerClassAnnotationValue(this.annotation, + simplify(value)); + } + super.visit(name, value); + } + + @Override + public AnnotationVisitor visitArray(String name) { + if (name.equals("value")) { + final List arrayValue = new ArrayList<>(); + + return new AnnotationVisitor(Opcodes.ASM6, null) { + @Override + public void visit(String name, Object value) { + arrayValue.add(simplify(value)); + super.visit(name, value); + } + + @Override + public void visitEnd() { + ClassAnnotationValueVisitor.this.classInfo + .registerClassAnnotationValue( + ClassAnnotationValueVisitor.this.annotation, + arrayValue.toArray()); + } + }; + } + return super.visitArray(name); + } + + private static Object simplify(Object value) { + Object newValue = value; + if (value instanceof Type) { + newValue = ((Type) value).getClassName(); + } + return newValue; + } + } +} + +class InfoMethodVisitor extends MethodVisitor { + private final ClassInfoBuilder classInfo; + + InfoMethodVisitor(final ClassInfoBuilder classInfo, + final MethodVisitor writer) { + super(Opcodes.ASM6, writer); + this.classInfo = classInfo; + } + + @Override + public void visitLineNumber(final int line, final Label start) { + + this.classInfo.registerCodeLine(line); + + } + + @Override + public AnnotationVisitor visitAnnotation(final String desc, + final boolean visible) { + final String type = desc.substring(1, desc.length() - 1); + this.classInfo.registerAnnotation(type); + return super.visitAnnotation(desc, visible); + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/ClassName.java b/pitest/src/main/java/org/pitest/classinfo/ClassName.java index ead03c65c..40a89a349 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ClassName.java +++ b/pitest/src/main/java/org/pitest/classinfo/ClassName.java @@ -1,170 +1,170 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.io.Serializable; -import java.util.function.Function; -import java.util.logging.Logger; -import java.util.stream.Stream; - -import org.pitest.util.IsolationUtils; -import org.pitest.util.Log; - -public final class ClassName implements Comparable, Serializable { - - private static final long serialVersionUID = 1L; - private static final Logger LOG = Log.getLogger(); - - private static final ClassName OBJECT = new ClassName("java/lang/Object"); - private static final ClassName STRING = new ClassName("java/lang/String"); - - private final String name; - - private ClassName(final String name) { - this.name = name; - } - - public static ClassName fromClass(final Class clazz) { - return ClassName.fromString(clazz.getName()); - } - - public static ClassName fromString(final String clazz) { - final String name = clazz.replace('.', '/'); - if (name.equals(OBJECT.asInternalName())) { - return OBJECT; - } - if (name.equals(STRING.asInternalName())) { - return STRING; - } - return new ClassName(name); - } - - - public String asJavaName() { - return this.name.replace('/', '.'); - } - - public String asInternalName() { - return this.name; - } - - public ClassName getNameWithoutPackage() { - final int lastSeparator = this.name.lastIndexOf('/'); - if (lastSeparator != -1) { - return ClassName.fromString(this.name.substring(lastSeparator + 1, - this.name.length())); - } - return this; - } - - public ClassName getPackage() { - final int lastSeparator = this.name.lastIndexOf('/'); - if (lastSeparator != -1) { - return ClassName.fromString(this.name.substring(0, lastSeparator)); - } - return ClassName.fromString(""); - } - - public ClassName withoutPrefixChars(final int prefixLength) { - final String nameWithoutPackage = this.getNameWithoutPackage().asJavaName(); - return ClassName.fromString(this.getPackage().asJavaName() - + "/" - + nameWithoutPackage.substring(prefixLength, - nameWithoutPackage.length())); - } - - public ClassName withoutSuffixChars(final int suffixLength) { - final String nameWithoutPacakge = this.getNameWithoutPackage().asJavaName(); - return ClassName.fromString(this.getPackage().asJavaName() - + "/" - + nameWithoutPacakge.substring(0, nameWithoutPacakge.length() - - suffixLength)); - } - - public static Function stringToClassName() { - return clazz -> ClassName.fromString(clazz); - } - - public static Function>> nameToClass() { - return nameToClass(IsolationUtils.getContextClassLoader()); - } - - public static Function>> nameToClass( - final ClassLoader loader) { - return className -> { - try { - final Class clazz = Class.forName(className.asJavaName(), false, - loader); - return Stream.of(clazz); - } catch (final ClassNotFoundException e1) { - LOG.warning("Could not load " + className - + " (ClassNotFoundException: " + e1.getMessage() + ")"); - return Stream.empty(); - } catch (final NoClassDefFoundError e2) { - LOG.warning("Could not load " + className - + " (NoClassDefFoundError: " + e2.getMessage() + ")"); - return Stream.empty(); - } catch (final LinkageError e3) { - LOG.warning("Could not load " + className + " " + e3.getMessage()); - return Stream.empty(); - } catch (final SecurityException e4) { - LOG.warning("Could not load " + className + " " + e4.getMessage()); - return Stream.empty(); - } - }; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.name == null) ? 0 : this.name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ClassName other = (ClassName) obj; - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - return asJavaName(); - } - - @Override - public int compareTo(final ClassName o) { - return this.asJavaName().compareTo(o.asJavaName()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.io.Serializable; +import java.util.function.Function; +import java.util.logging.Logger; +import java.util.stream.Stream; + +import org.pitest.util.IsolationUtils; +import org.pitest.util.Log; + +public final class ClassName implements Comparable, Serializable { + + private static final long serialVersionUID = 1L; + private static final Logger LOG = Log.getLogger(); + + private static final ClassName OBJECT = new ClassName("java/lang/Object"); + private static final ClassName STRING = new ClassName("java/lang/String"); + + private final String name; + + private ClassName(final String name) { + this.name = name; + } + + public static ClassName fromClass(final Class clazz) { + return ClassName.fromString(clazz.getName()); + } + + public static ClassName fromString(final String clazz) { + final String name = clazz.replace('.', '/'); + if (name.equals(OBJECT.asInternalName())) { + return OBJECT; + } + if (name.equals(STRING.asInternalName())) { + return STRING; + } + return new ClassName(name); + } + + + public String asJavaName() { + return this.name.replace('/', '.'); + } + + public String asInternalName() { + return this.name; + } + + public ClassName getNameWithoutPackage() { + final int lastSeparator = this.name.lastIndexOf('/'); + if (lastSeparator != -1) { + return ClassName.fromString(this.name.substring(lastSeparator + 1, + this.name.length())); + } + return this; + } + + public ClassName getPackage() { + final int lastSeparator = this.name.lastIndexOf('/'); + if (lastSeparator != -1) { + return ClassName.fromString(this.name.substring(0, lastSeparator)); + } + return ClassName.fromString(""); + } + + public ClassName withoutPrefixChars(final int prefixLength) { + final String nameWithoutPackage = this.getNameWithoutPackage().asJavaName(); + return ClassName.fromString(this.getPackage().asJavaName() + + "/" + + nameWithoutPackage.substring(prefixLength, + nameWithoutPackage.length())); + } + + public ClassName withoutSuffixChars(final int suffixLength) { + final String nameWithoutPacakge = this.getNameWithoutPackage().asJavaName(); + return ClassName.fromString(this.getPackage().asJavaName() + + "/" + + nameWithoutPacakge.substring(0, nameWithoutPacakge.length() + - suffixLength)); + } + + public static Function stringToClassName() { + return clazz -> ClassName.fromString(clazz); + } + + public static Function>> nameToClass() { + return nameToClass(IsolationUtils.getContextClassLoader()); + } + + public static Function>> nameToClass( + final ClassLoader loader) { + return className -> { + try { + final Class clazz = Class.forName(className.asJavaName(), false, + loader); + return Stream.of(clazz); + } catch (final ClassNotFoundException e1) { + LOG.warning("Could not load " + className + + " (ClassNotFoundException: " + e1.getMessage() + ")"); + return Stream.empty(); + } catch (final NoClassDefFoundError e2) { + LOG.warning("Could not load " + className + + " (NoClassDefFoundError: " + e2.getMessage() + ")"); + return Stream.empty(); + } catch (final LinkageError e3) { + LOG.warning("Could not load " + className + " " + e3.getMessage()); + return Stream.empty(); + } catch (final SecurityException e4) { + LOG.warning("Could not load " + className + " " + e4.getMessage()); + return Stream.empty(); + } + }; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.name == null) ? 0 : this.name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ClassName other = (ClassName) obj; + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + return asJavaName(); + } + + @Override + public int compareTo(final ClassName o) { + return this.asJavaName().compareTo(o.asJavaName()); + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/ClassPointer.java b/pitest/src/main/java/org/pitest/classinfo/ClassPointer.java index 82c76835a..bf2762c47 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ClassPointer.java +++ b/pitest/src/main/java/org/pitest/classinfo/ClassPointer.java @@ -1,52 +1,52 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.util.Optional; - -interface ClassPointer { - Optional fetch(); -} - -class DefaultClassPointer implements ClassPointer { - - private final ClassInfo clazz; - - DefaultClassPointer(final ClassInfo clazz) { - this.clazz = clazz; - } - - @Override - public Optional fetch() { - return Optional.ofNullable(this.clazz); - } - -} - -class DeferredClassPointer implements ClassPointer { - private final Repository repository; - private final ClassName name; - - DeferredClassPointer(final Repository repository, final ClassName name) { - this.repository = repository; - this.name = name; - } - - @Override - public Optional fetch() { - return this.repository.fetchClass(this.name); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.util.Optional; + +interface ClassPointer { + Optional fetch(); +} + +class DefaultClassPointer implements ClassPointer { + + private final ClassInfo clazz; + + DefaultClassPointer(final ClassInfo clazz) { + this.clazz = clazz; + } + + @Override + public Optional fetch() { + return Optional.ofNullable(this.clazz); + } + +} + +class DeferredClassPointer implements ClassPointer { + private final Repository repository; + private final ClassName name; + + DeferredClassPointer(final Repository repository, final ClassName name) { + this.repository = repository; + this.name = name; + } + + @Override + public Optional fetch() { + return this.repository.fetchClass(this.name); + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/ComputeClassWriter.java b/pitest/src/main/java/org/pitest/classinfo/ComputeClassWriter.java index 681e541af..dc6f3a64a 100644 --- a/pitest/src/main/java/org/pitest/classinfo/ComputeClassWriter.java +++ b/pitest/src/main/java/org/pitest/classinfo/ComputeClassWriter.java @@ -1,194 +1,194 @@ -/*** - * Extracted and modified from ASM 4 test suite. Original copyright notice preserved below - * - * ASM tests - * Copyright (c) 2000-2011 INRIA, France Telecom - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.pitest.classinfo; - -import java.util.Map; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Opcodes; -import java.util.Optional; -import org.pitest.util.PitError; - -/** - * A ClassWriter that computes the common super class of two classes without - * actually loading them with a ClassLoader. - * - * @author Eric Bruneton - * - * Modified to match behaviour of default ClassWriter and cache already - * calculated values - */ -public class ComputeClassWriter extends ClassWriter { - - private final ClassByteArraySource bytes; - private final Map cache; - - public ComputeClassWriter(final ClassByteArraySource bytes, - final Map cache, final int flags) { - super(flags); - this.bytes = bytes; - this.cache = cache; - } - - @Override - protected String getCommonSuperClass(final String type1, final String type2) { - final String key = type1 + "!_!" + type2; - final String previous = this.cache.get(key); - if (previous != null) { - return previous; - } - - final ClassReader info1 = typeInfo(type1); - final ClassReader info2 = typeInfo(type2); - - final String result = getCommonSuperClass(type1, info1, type2, info2); - this.cache.put(key, result); - return result; - - } - - private String getCommonSuperClass(final String type1, - final ClassReader info1, final String type2, final ClassReader info2) { - if (isInterface(info1)) { - if (typeImplements(type2, info2, type1)) { - return type1; - } else { - if (isInterface(info2)) { - if (typeImplements(type1, info1, type2)) { - return type2; - } else { - return "java/lang/Object"; - } - } - } - } - - final StringBuilder b1 = typeAncestors(type1, info1); - final StringBuilder b2 = typeAncestors(type2, info2); - String result = "java/lang/Object"; - int end1 = b1.length(); - int end2 = b2.length(); - while (true) { - final int start1 = b1.lastIndexOf(";", end1 - 1); - final int start2 = b2.lastIndexOf(";", end2 - 1); - if ((start1 != -1) && (start2 != -1) - && ((end1 - start1) == (end2 - start2))) { - final String p1 = b1.substring(start1 + 1, end1); - final String p2 = b2.substring(start2 + 1, end2); - if (p1.equals(p2)) { - result = p1; - end1 = start1; - end2 = start2; - } else { - return result; - } - } else { - return result; - } - } - - } - - private static boolean isInterface(final ClassReader info1) { - return (info1.getAccess() & Opcodes.ACC_INTERFACE) != 0; - } - - /** - * Returns the internal names of the ancestor classes of the given type. - * - * @param type - * the internal name of a class or interface. - * @param info - * the ClassReader corresponding to 'type'. - * @return a StringBuilder containing the ancestor classes of 'type', - * separated by ';'. The returned string has the following format: - * ";type1;type2 ... ;typeN", where type1 is 'type', and typeN is a - * direct subclass of Object. If 'type' is Object, the returned string - * is empty. - */ - private StringBuilder typeAncestors(String type, ClassReader info) { - final StringBuilder b = new StringBuilder(); - while (!"java/lang/Object".equals(type)) { - b.append(';').append(type); - type = info.getSuperName(); - info = typeInfo(type); - } - return b; - } - - /** - * Returns true if the given type implements the given interface. - * - * @param type - * the internal name of a class or interface. - * @param info - * the ClassReader corresponding to 'type'. - * @param itf - * the internal name of a interface. - * @return true if 'type' implements directly or indirectly 'itf' - */ - private boolean typeImplements(String type, ClassReader info, final String itf) { - final String cleanItf = itf.replace(".", "/"); - while (!"java/lang/Object".equals(type)) { - final String[] itfs = info.getInterfaces(); - for (final String itf2 : itfs) { - if (itf2.equals(cleanItf)) { - return true; - } - } - for (final String itf2 : itfs) { - if (typeImplements(itf2, typeInfo(itf2), cleanItf)) { - return true; - } - } - type = info.getSuperName(); - info = typeInfo(type); - } - return false; - } - - /** - * Returns a ClassReader corresponding to the given class or interface. - * - * @param type - * the internal name of a class or interface. - * @return the ClassReader corresponding to 'type'. - */ - private ClassReader typeInfo(final String type) { - final Optional maybeBytes = this.bytes.getBytes(type); - if (!maybeBytes.isPresent()) { - throw new PitError("Could not find class defintiion for " + type); - } - return new ClassReader(maybeBytes.get()); - } +/*** + * Extracted and modified from ASM 4 test suite. Original copyright notice preserved below + * + * ASM tests + * Copyright (c) 2000-2011 INRIA, France Telecom + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.pitest.classinfo; + +import java.util.Map; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import java.util.Optional; +import org.pitest.util.PitError; + +/** + * A ClassWriter that computes the common super class of two classes without + * actually loading them with a ClassLoader. + * + * @author Eric Bruneton + * + * Modified to match behaviour of default ClassWriter and cache already + * calculated values + */ +public class ComputeClassWriter extends ClassWriter { + + private final ClassByteArraySource bytes; + private final Map cache; + + public ComputeClassWriter(final ClassByteArraySource bytes, + final Map cache, final int flags) { + super(flags); + this.bytes = bytes; + this.cache = cache; + } + + @Override + protected String getCommonSuperClass(final String type1, final String type2) { + final String key = type1 + "!_!" + type2; + final String previous = this.cache.get(key); + if (previous != null) { + return previous; + } + + final ClassReader info1 = typeInfo(type1); + final ClassReader info2 = typeInfo(type2); + + final String result = getCommonSuperClass(type1, info1, type2, info2); + this.cache.put(key, result); + return result; + + } + + private String getCommonSuperClass(final String type1, + final ClassReader info1, final String type2, final ClassReader info2) { + if (isInterface(info1)) { + if (typeImplements(type2, info2, type1)) { + return type1; + } else { + if (isInterface(info2)) { + if (typeImplements(type1, info1, type2)) { + return type2; + } else { + return "java/lang/Object"; + } + } + } + } + + final StringBuilder b1 = typeAncestors(type1, info1); + final StringBuilder b2 = typeAncestors(type2, info2); + String result = "java/lang/Object"; + int end1 = b1.length(); + int end2 = b2.length(); + while (true) { + final int start1 = b1.lastIndexOf(";", end1 - 1); + final int start2 = b2.lastIndexOf(";", end2 - 1); + if ((start1 != -1) && (start2 != -1) + && ((end1 - start1) == (end2 - start2))) { + final String p1 = b1.substring(start1 + 1, end1); + final String p2 = b2.substring(start2 + 1, end2); + if (p1.equals(p2)) { + result = p1; + end1 = start1; + end2 = start2; + } else { + return result; + } + } else { + return result; + } + } + + } + + private static boolean isInterface(final ClassReader info1) { + return (info1.getAccess() & Opcodes.ACC_INTERFACE) != 0; + } + + /** + * Returns the internal names of the ancestor classes of the given type. + * + * @param type + * the internal name of a class or interface. + * @param info + * the ClassReader corresponding to 'type'. + * @return a StringBuilder containing the ancestor classes of 'type', + * separated by ';'. The returned string has the following format: + * ";type1;type2 ... ;typeN", where type1 is 'type', and typeN is a + * direct subclass of Object. If 'type' is Object, the returned string + * is empty. + */ + private StringBuilder typeAncestors(String type, ClassReader info) { + final StringBuilder b = new StringBuilder(); + while (!"java/lang/Object".equals(type)) { + b.append(';').append(type); + type = info.getSuperName(); + info = typeInfo(type); + } + return b; + } + + /** + * Returns true if the given type implements the given interface. + * + * @param type + * the internal name of a class or interface. + * @param info + * the ClassReader corresponding to 'type'. + * @param itf + * the internal name of a interface. + * @return true if 'type' implements directly or indirectly 'itf' + */ + private boolean typeImplements(String type, ClassReader info, final String itf) { + final String cleanItf = itf.replace(".", "/"); + while (!"java/lang/Object".equals(type)) { + final String[] itfs = info.getInterfaces(); + for (final String itf2 : itfs) { + if (itf2.equals(cleanItf)) { + return true; + } + } + for (final String itf2 : itfs) { + if (typeImplements(itf2, typeInfo(itf2), cleanItf)) { + return true; + } + } + type = info.getSuperName(); + info = typeInfo(type); + } + return false; + } + + /** + * Returns a ClassReader corresponding to the given class or interface. + * + * @param type + * the internal name of a class or interface. + * @return the ClassReader corresponding to 'type'. + */ + private ClassReader typeInfo(final String type) { + final Optional maybeBytes = this.bytes.getBytes(type); + if (!maybeBytes.isPresent()) { + throw new PitError("Could not find class defintiion for " + type); + } + return new ClassReader(maybeBytes.get()); + } } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/classinfo/HashFunction.java b/pitest/src/main/java/org/pitest/classinfo/HashFunction.java index 4180b729e..013042b44 100644 --- a/pitest/src/main/java/org/pitest/classinfo/HashFunction.java +++ b/pitest/src/main/java/org/pitest/classinfo/HashFunction.java @@ -1,7 +1,7 @@ -package org.pitest.classinfo; - -public interface HashFunction { - - long hash(byte[] value); - -} +package org.pitest.classinfo; + +public interface HashFunction { + + long hash(byte[] value); + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/HierarchicalClassId.java b/pitest/src/main/java/org/pitest/classinfo/HierarchicalClassId.java index cac5f97c1..a3f9e8574 100644 --- a/pitest/src/main/java/org/pitest/classinfo/HierarchicalClassId.java +++ b/pitest/src/main/java/org/pitest/classinfo/HierarchicalClassId.java @@ -1,87 +1,87 @@ -package org.pitest.classinfo; - -import java.io.Serializable; -import java.math.BigInteger; - -public final class HierarchicalClassId implements Serializable { - - private static final long serialVersionUID = 1L; - - private final ClassIdentifier classId; - private final String hierarchicalHash; - - public HierarchicalClassId(final ClassIdentifier classId, - final String hierarchicalHash) { - this.classId = classId; - this.hierarchicalHash = hierarchicalHash; - } - - public HierarchicalClassId(final ClassIdentifier id, final BigInteger deepHash) { - this(id, deepHash.toString(16)); - } - - public HierarchicalClassId(final long hash, final ClassName name, - final String hierarchicalHash) { - this(new ClassIdentifier(hash, name), hierarchicalHash); - } - - public String getHierarchicalHash() { - return this.hierarchicalHash; - } - - public ClassName getName() { - return this.classId.getName(); - } - - public ClassIdentifier getId() { - return this.classId; - } - - @Override - public String toString() { - return "HierarchicalClassId [classId=" + this.classId - + ", hierarchicalHash=" + this.hierarchicalHash + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.classId == null) ? 0 : this.classId.hashCode()); - result = (prime * result) - + ((this.hierarchicalHash == null) ? 0 : this.hierarchicalHash - .hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final HierarchicalClassId other = (HierarchicalClassId) obj; - if (this.classId == null) { - if (other.classId != null) { - return false; - } - } else if (!this.classId.equals(other.classId)) { - return false; - } - if (this.hierarchicalHash == null) { - if (other.hierarchicalHash != null) { - return false; - } - } else if (!this.hierarchicalHash.equals(other.hierarchicalHash)) { - return false; - } - return true; - } - -} +package org.pitest.classinfo; + +import java.io.Serializable; +import java.math.BigInteger; + +public final class HierarchicalClassId implements Serializable { + + private static final long serialVersionUID = 1L; + + private final ClassIdentifier classId; + private final String hierarchicalHash; + + public HierarchicalClassId(final ClassIdentifier classId, + final String hierarchicalHash) { + this.classId = classId; + this.hierarchicalHash = hierarchicalHash; + } + + public HierarchicalClassId(final ClassIdentifier id, final BigInteger deepHash) { + this(id, deepHash.toString(16)); + } + + public HierarchicalClassId(final long hash, final ClassName name, + final String hierarchicalHash) { + this(new ClassIdentifier(hash, name), hierarchicalHash); + } + + public String getHierarchicalHash() { + return this.hierarchicalHash; + } + + public ClassName getName() { + return this.classId.getName(); + } + + public ClassIdentifier getId() { + return this.classId; + } + + @Override + public String toString() { + return "HierarchicalClassId [classId=" + this.classId + + ", hierarchicalHash=" + this.hierarchicalHash + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.classId == null) ? 0 : this.classId.hashCode()); + result = (prime * result) + + ((this.hierarchicalHash == null) ? 0 : this.hierarchicalHash + .hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final HierarchicalClassId other = (HierarchicalClassId) obj; + if (this.classId == null) { + if (other.classId != null) { + return false; + } + } else if (!this.classId.equals(other.classId)) { + return false; + } + if (this.hierarchicalHash == null) { + if (other.hierarchicalHash != null) { + return false; + } + } else if (!this.hierarchicalHash.equals(other.hierarchicalHash)) { + return false; + } + return true; + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/MethodFilteringAdapter.java b/pitest/src/main/java/org/pitest/classinfo/MethodFilteringAdapter.java index a5a669645..45d79e9a8 100644 --- a/pitest/src/main/java/org/pitest/classinfo/MethodFilteringAdapter.java +++ b/pitest/src/main/java/org/pitest/classinfo/MethodFilteringAdapter.java @@ -1,54 +1,54 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.functional.F5; - -public abstract class MethodFilteringAdapter extends ClassVisitor { - - private final F5 filter; - - public MethodFilteringAdapter(final ClassVisitor writer, - final F5 filter) { - super(Opcodes.ASM6, writer); - this.filter = filter; - } - - private boolean shouldInstrument(final int access, final String name, - final String desc, final String signature, final String[] exceptions) { - return this.filter.apply(access, name, desc, signature, exceptions); - } - - @Override - public final MethodVisitor visitMethod(final int access, final String name, - final String desc, final String signature, final String[] exceptions) { - final MethodVisitor methodVisitor = this.cv.visitMethod(access, name, desc, - signature, exceptions); - if (shouldInstrument(access, name, desc, signature, exceptions)) { - return visitMethodIfRequired(access, name, desc, signature, exceptions, - methodVisitor); - } else { - return methodVisitor; - } - } - - public abstract MethodVisitor visitMethodIfRequired(int access, String name, - String desc, String signature, String[] exceptions, - MethodVisitor methodVisitor); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.functional.F5; + +public abstract class MethodFilteringAdapter extends ClassVisitor { + + private final F5 filter; + + public MethodFilteringAdapter(final ClassVisitor writer, + final F5 filter) { + super(Opcodes.ASM6, writer); + this.filter = filter; + } + + private boolean shouldInstrument(final int access, final String name, + final String desc, final String signature, final String[] exceptions) { + return this.filter.apply(access, name, desc, signature, exceptions); + } + + @Override + public final MethodVisitor visitMethod(final int access, final String name, + final String desc, final String signature, final String[] exceptions) { + final MethodVisitor methodVisitor = this.cv.visitMethod(access, name, desc, + signature, exceptions); + if (shouldInstrument(access, name, desc, signature, exceptions)) { + return visitMethodIfRequired(access, name, desc, signature, exceptions, + methodVisitor); + } else { + return methodVisitor; + } + } + + public abstract MethodVisitor visitMethodIfRequired(int access, String name, + String desc, String signature, String[] exceptions, + MethodVisitor methodVisitor); + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/NameToClassInfo.java b/pitest/src/main/java/org/pitest/classinfo/NameToClassInfo.java index 89e6da00c..b0c0a3f32 100644 --- a/pitest/src/main/java/org/pitest/classinfo/NameToClassInfo.java +++ b/pitest/src/main/java/org/pitest/classinfo/NameToClassInfo.java @@ -1,20 +1,20 @@ -package org.pitest.classinfo; - -import java.util.function.Function; - -import java.util.Optional; - -public class NameToClassInfo implements Function> { - - private final ClassInfoSource repository; - - public NameToClassInfo(final ClassInfoSource repository) { - this.repository = repository; - } - - @Override - public Optional apply(final ClassName a) { - return this.repository.fetchClass(a); - } - +package org.pitest.classinfo; + +import java.util.function.Function; + +import java.util.Optional; + +public class NameToClassInfo implements Function> { + + private final ClassInfoSource repository; + + public NameToClassInfo(final ClassInfoSource repository) { + this.repository = repository; + } + + @Override + public Optional apply(final ClassName a) { + return this.repository.fetchClass(a); + } + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/classinfo/Repository.java b/pitest/src/main/java/org/pitest/classinfo/Repository.java index db58a203b..71f20e374 100644 --- a/pitest/src/main/java/org/pitest/classinfo/Repository.java +++ b/pitest/src/main/java/org/pitest/classinfo/Repository.java @@ -1,110 +1,110 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import java.util.Optional; - -public class Repository implements ClassInfoSource { - - private final HashFunction hashFunction; - private final Map knownClasses = new HashMap<>(); - private final Set unknownClasses = new HashSet<>(); - private final ClassByteArraySource source; - - public Repository(final ClassByteArraySource source) { - this(source, new AddlerHash()); - } - - Repository(final ClassByteArraySource source, final HashFunction hashFunction) { - this.source = source; - this.hashFunction = hashFunction; - } - - public boolean hasClass(final ClassName name) { - return this.knownClasses.containsKey(name) || querySource(name).isPresent(); - } - - public Optional fetchClass(final Class clazz) { // NO_UCD (test - // only) - return fetchClass(clazz.getName()); - } - - private Optional fetchClass(final String name) { - return fetchClass(ClassName.fromString(name)); - } - - @Override - public Optional fetchClass(final ClassName name) { - final ClassInfo info = this.knownClasses.get(name); - if (info != null) { - return Optional.ofNullable(info); - } - - final Optional maybeInfo = nameToClassInfo(name); - if (maybeInfo.isPresent()) { - this.knownClasses.put(name, maybeInfo.get()); - } - return maybeInfo; - } - - private Optional nameToClassInfo(final ClassName name) { - final Optional bytes = querySource(name); - if (bytes.isPresent()) { - final ClassInfoBuilder classData = ClassInfoVisitor.getClassInfo(name, - bytes.get(), this.hashFunction.hash(bytes.get())); - return contructClassInfo(classData); - } else { - return Optional.empty(); - } - } - - public Optional querySource(final ClassName name) { - if (this.unknownClasses.contains(name)) { - return Optional.empty(); - } - final Optional option = this.source.getBytes(name.asJavaName()); - if (option.isPresent()) { - return option; - } - - this.unknownClasses.add(name); - return option; - } - - private Optional contructClassInfo(final ClassInfoBuilder classData) { - return Optional.ofNullable(new ClassInfo(resolveClass(classData.superClass), - resolveClass(classData.outerClass), classData)); - } - - private ClassPointer resolveClass(final String clazz) { - if (clazz == null) { - return new DefaultClassPointer(null); - } else { - final ClassInfo alreadyResolved = this.knownClasses.get(ClassName - .fromString(clazz)); - if (alreadyResolved != null) { - return new DefaultClassPointer(alreadyResolved); - } else { - return new DeferredClassPointer(this, ClassName.fromString(clazz)); - } - } - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import java.util.Optional; + +public class Repository implements ClassInfoSource { + + private final HashFunction hashFunction; + private final Map knownClasses = new HashMap<>(); + private final Set unknownClasses = new HashSet<>(); + private final ClassByteArraySource source; + + public Repository(final ClassByteArraySource source) { + this(source, new AddlerHash()); + } + + Repository(final ClassByteArraySource source, final HashFunction hashFunction) { + this.source = source; + this.hashFunction = hashFunction; + } + + public boolean hasClass(final ClassName name) { + return this.knownClasses.containsKey(name) || querySource(name).isPresent(); + } + + public Optional fetchClass(final Class clazz) { // NO_UCD (test + // only) + return fetchClass(clazz.getName()); + } + + private Optional fetchClass(final String name) { + return fetchClass(ClassName.fromString(name)); + } + + @Override + public Optional fetchClass(final ClassName name) { + final ClassInfo info = this.knownClasses.get(name); + if (info != null) { + return Optional.ofNullable(info); + } + + final Optional maybeInfo = nameToClassInfo(name); + if (maybeInfo.isPresent()) { + this.knownClasses.put(name, maybeInfo.get()); + } + return maybeInfo; + } + + private Optional nameToClassInfo(final ClassName name) { + final Optional bytes = querySource(name); + if (bytes.isPresent()) { + final ClassInfoBuilder classData = ClassInfoVisitor.getClassInfo(name, + bytes.get(), this.hashFunction.hash(bytes.get())); + return contructClassInfo(classData); + } else { + return Optional.empty(); + } + } + + public Optional querySource(final ClassName name) { + if (this.unknownClasses.contains(name)) { + return Optional.empty(); + } + final Optional option = this.source.getBytes(name.asJavaName()); + if (option.isPresent()) { + return option; + } + + this.unknownClasses.add(name); + return option; + } + + private Optional contructClassInfo(final ClassInfoBuilder classData) { + return Optional.ofNullable(new ClassInfo(resolveClass(classData.superClass), + resolveClass(classData.outerClass), classData)); + } + + private ClassPointer resolveClass(final String clazz) { + if (clazz == null) { + return new DefaultClassPointer(null); + } else { + final ClassInfo alreadyResolved = this.knownClasses.get(ClassName + .fromString(clazz)); + if (alreadyResolved != null) { + return new DefaultClassPointer(alreadyResolved); + } else { + return new DeferredClassPointer(this, ClassName.fromString(clazz)); + } + } + } + +} diff --git a/pitest/src/main/java/org/pitest/classinfo/TestToClassMapper.java b/pitest/src/main/java/org/pitest/classinfo/TestToClassMapper.java index d85999bee..c259c1ec8 100644 --- a/pitest/src/main/java/org/pitest/classinfo/TestToClassMapper.java +++ b/pitest/src/main/java/org/pitest/classinfo/TestToClassMapper.java @@ -1,49 +1,49 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import java.util.Optional; - -public class TestToClassMapper { - - private static final int TEST_LENGTH = "Test".length(); - private final Repository repository; - - public TestToClassMapper(final Repository repository) { - this.repository = repository; - } - - public Optional findTestee(final String className) { - - final ClassName name = ClassName.fromString(className); - - if (name.asJavaName().endsWith("Test") - && tryName(name.withoutSuffixChars(TEST_LENGTH))) { - return Optional.ofNullable(name.withoutSuffixChars(TEST_LENGTH)); - } - - if (name.getNameWithoutPackage().asJavaName().startsWith("Test") - && tryName(name.withoutPrefixChars(TEST_LENGTH))) { - return Optional.ofNullable(name.withoutPrefixChars(TEST_LENGTH)); - } - - return Optional.empty(); - } - - private boolean tryName(final ClassName name) { - return this.repository.hasClass(name); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import java.util.Optional; + +public class TestToClassMapper { + + private static final int TEST_LENGTH = "Test".length(); + private final Repository repository; + + public TestToClassMapper(final Repository repository) { + this.repository = repository; + } + + public Optional findTestee(final String className) { + + final ClassName name = ClassName.fromString(className); + + if (name.asJavaName().endsWith("Test") + && tryName(name.withoutSuffixChars(TEST_LENGTH))) { + return Optional.ofNullable(name.withoutSuffixChars(TEST_LENGTH)); + } + + if (name.getNameWithoutPackage().asJavaName().startsWith("Test") + && tryName(name.withoutPrefixChars(TEST_LENGTH))) { + return Optional.ofNullable(name.withoutPrefixChars(TEST_LENGTH)); + } + + return Optional.empty(); + } + + private boolean tryName(final ClassName name) { + return this.repository.hasClass(name); + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/ArchiveClassPathRoot.java b/pitest/src/main/java/org/pitest/classpath/ArchiveClassPathRoot.java index deed69b21..a206d8043 100644 --- a/pitest/src/main/java/org/pitest/classpath/ArchiveClassPathRoot.java +++ b/pitest/src/main/java/org/pitest/classpath/ArchiveClassPathRoot.java @@ -1,122 +1,122 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import java.util.Optional; -import org.pitest.util.StreamUtil; -import org.pitest.util.Unchecked; - -/** - * ClassPathRoot wrapping a jar or zip file - */ -public class ArchiveClassPathRoot implements ClassPathRoot, IOHeavyRoot { - - private final File file; - - public ArchiveClassPathRoot(final File file) { - this.file = file; - } - - @Override - public InputStream getData(final String name) throws IOException { - try (ZipFile zip = getRoot()) { - final ZipEntry entry = zip.getEntry(name.replace('.', '/') + ".class"); - if (entry == null) { - return null; - } - return StreamUtil.copyStream(zip.getInputStream(entry)); - } - } - - @Override - public URL getResource(final String name) throws MalformedURLException { - final ZipFile zip = getRoot(); - try { - final ZipEntry entry = zip.getEntry(name); - if (entry != null) { - return new URL("jar:file:" + zip.getName() + "!/" + entry.getName()); - } else { - return null; - } - } finally { - closeQuietly(zip); - } - - } - - private static void closeQuietly(final ZipFile zip) { - try { - zip.close(); - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - - @Override - public String toString() { - return "ArchiveClassPathRoot [file=" + this.file.getName() + "]"; - } - - @Override - public Collection classNames() { - final List names = new ArrayList<>(); - final ZipFile root = getRoot(); - try { - final Enumeration entries = root.entries(); - while (entries.hasMoreElements()) { - final ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory() && entry.getName().endsWith(".class")) { - names.add(stringToClassName(entry.getName())); - } - } - return names; - } finally { - closeQuietly(root); - } - - } - - private String stringToClassName(final String name) { - return name.substring(0, (name.length() - ".class".length())).replace('/', - '.'); - } - - @Override - public Optional cacheLocation() { - return Optional.ofNullable(this.file.getAbsolutePath()); - } - - private ZipFile getRoot() { - try { - return new ZipFile(this.file); - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex.getMessage() + " (" - + this.file + ")", ex); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import java.util.Optional; +import org.pitest.util.StreamUtil; +import org.pitest.util.Unchecked; + +/** + * ClassPathRoot wrapping a jar or zip file + */ +public class ArchiveClassPathRoot implements ClassPathRoot, IOHeavyRoot { + + private final File file; + + public ArchiveClassPathRoot(final File file) { + this.file = file; + } + + @Override + public InputStream getData(final String name) throws IOException { + try (ZipFile zip = getRoot()) { + final ZipEntry entry = zip.getEntry(name.replace('.', '/') + ".class"); + if (entry == null) { + return null; + } + return StreamUtil.copyStream(zip.getInputStream(entry)); + } + } + + @Override + public URL getResource(final String name) throws MalformedURLException { + final ZipFile zip = getRoot(); + try { + final ZipEntry entry = zip.getEntry(name); + if (entry != null) { + return new URL("jar:file:" + zip.getName() + "!/" + entry.getName()); + } else { + return null; + } + } finally { + closeQuietly(zip); + } + + } + + private static void closeQuietly(final ZipFile zip) { + try { + zip.close(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + + @Override + public String toString() { + return "ArchiveClassPathRoot [file=" + this.file.getName() + "]"; + } + + @Override + public Collection classNames() { + final List names = new ArrayList<>(); + final ZipFile root = getRoot(); + try { + final Enumeration entries = root.entries(); + while (entries.hasMoreElements()) { + final ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory() && entry.getName().endsWith(".class")) { + names.add(stringToClassName(entry.getName())); + } + } + return names; + } finally { + closeQuietly(root); + } + + } + + private String stringToClassName(final String name) { + return name.substring(0, (name.length() - ".class".length())).replace('/', + '.'); + } + + @Override + public Optional cacheLocation() { + return Optional.ofNullable(this.file.getAbsolutePath()); + } + + private ZipFile getRoot() { + try { + return new ZipFile(this.file); + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex.getMessage() + " (" + + this.file + ")", ex); + } + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/ClassFilter.java b/pitest/src/main/java/org/pitest/classpath/ClassFilter.java index 09f68ce0c..d960f5920 100644 --- a/pitest/src/main/java/org/pitest/classpath/ClassFilter.java +++ b/pitest/src/main/java/org/pitest/classpath/ClassFilter.java @@ -1,36 +1,36 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import java.util.function.Predicate; - -public class ClassFilter { - private final Predicate test; - private final Predicate code; - - public ClassFilter(final Predicate test, final Predicate code) { - this.test = test; - this.code = code; - - } - - public Predicate getTest() { - return this.test; - } - - public Predicate getCode() { - return this.code; - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import java.util.function.Predicate; + +public class ClassFilter { + private final Predicate test; + private final Predicate code; + + public ClassFilter(final Predicate test, final Predicate code) { + this.test = test; + this.code = code; + + } + + public Predicate getTest() { + return this.test; + } + + public Predicate getCode() { + return this.code; + } +} diff --git a/pitest/src/main/java/org/pitest/classpath/ClassPath.java b/pitest/src/main/java/org/pitest/classpath/ClassPath.java index 44caf0f25..97f2f1b37 100644 --- a/pitest/src/main/java/org/pitest/classpath/ClassPath.java +++ b/pitest/src/main/java/org/pitest/classpath/ClassPath.java @@ -1,170 +1,170 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.classpath; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.logging.Logger; -import java.util.zip.ZipException; - -import org.pitest.functional.FCollection; -import org.pitest.util.Log; -import org.pitest.util.PitError; -import org.pitest.util.StreamUtil; - -public class ClassPath { - - private static final Logger LOG = Log.getLogger(); - - private final CompoundClassPathRoot root; - - public ClassPath() { - this(ClassPath.getClassPathElementsAsFiles()); - } - - public ClassPath(final ClassPathRoot... roots) { - this(Arrays.asList(roots)); - } - - public ClassPath(final Collection files) { - this(createRoots(FCollection.filter(files, exists()))); - } - - public ClassPath(List roots) { - this.root = new CompoundClassPathRoot(roots); - } - - - public Collection classNames() { - return this.root.classNames(); - } - - // fixme should not be determining type here - private static List createRoots(final Collection files) { - File lastFile = null; - try { - final List rs = new ArrayList<>(); - - for (final File f : files) { - lastFile = f; - if (f.isDirectory()) { - rs.add(new DirectoryClassPathRoot(f)); - } else { - handleArchive(rs, f); - } - } - return rs; - } catch (final IOException ex) { - throw new PitError("Error handling file " + lastFile, ex); - } - } - - private static void handleArchive(final List rs, final File f) - throws IOException { - try { - if (!f.canRead()) { - throw new IOException("Can't read the file " + f); - } - rs.add(new ArchiveClassPathRoot(f)); - } catch (final ZipException ex) { - LOG.warning("Can't open the archive " + f); - } - } - - public byte[] getClassData(final String classname) throws IOException { - try (InputStream is = this.root.getData(classname)) { - if (is != null) { - return StreamUtil.streamToByteArray(is); - } else { - return null; - } - } - } - - public URL findResource(final String name) { - try { - return this.root.getResource(name); - } catch (final IOException exception) { - return null; - } - } - - public static Collection getClassPathElementsAsPaths() { - final Set filesAsString = new LinkedHashSet<>(); - FCollection.mapTo(getClassPathElementsAsFiles(), file -> file.getPath(), - filesAsString); - return filesAsString; - } - - - public static Collection getClassPathElementsAsFiles() { - final Set us = new LinkedHashSet<>(); - FCollection.mapTo(getClassPathElementsAsAre(), stringToCanonicalFile(), us); - return us; - } - - - public Collection findClasses(final Predicate nameFilter) { - return FCollection.filter(classNames(), nameFilter); - } - - public String getLocalClassPath() { - return this.root.cacheLocation().get(); - } - - public ClassPath getComponent(final Predicate predicate) { - return new ClassPath(FCollection.filter(this.root, predicate).toArray( - new ClassPathRoot[0])); - } - - private static Predicate exists() { - return a -> a.exists() && a.canRead(); - } - - private static Function stringToCanonicalFile() { - return fileAsString -> { - try { - return new File(fileAsString).getCanonicalFile(); - } catch (final IOException ex) { - throw new PitError("Error transforming classpath element " - + fileAsString, ex); - } - }; - } - - /** FIXME move somewhere common */ - private static List getClassPathElementsAsAre() { - final String classPath = System.getProperty("java.class.path"); - final String separator = File.pathSeparator; - if (classPath != null) { - return Arrays.asList(classPath.split(separator)); - } else { - return new ArrayList<>(); - } - - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.classpath; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.logging.Logger; +import java.util.zip.ZipException; + +import org.pitest.functional.FCollection; +import org.pitest.util.Log; +import org.pitest.util.PitError; +import org.pitest.util.StreamUtil; + +public class ClassPath { + + private static final Logger LOG = Log.getLogger(); + + private final CompoundClassPathRoot root; + + public ClassPath() { + this(ClassPath.getClassPathElementsAsFiles()); + } + + public ClassPath(final ClassPathRoot... roots) { + this(Arrays.asList(roots)); + } + + public ClassPath(final Collection files) { + this(createRoots(FCollection.filter(files, exists()))); + } + + public ClassPath(List roots) { + this.root = new CompoundClassPathRoot(roots); + } + + + public Collection classNames() { + return this.root.classNames(); + } + + // fixme should not be determining type here + private static List createRoots(final Collection files) { + File lastFile = null; + try { + final List rs = new ArrayList<>(); + + for (final File f : files) { + lastFile = f; + if (f.isDirectory()) { + rs.add(new DirectoryClassPathRoot(f)); + } else { + handleArchive(rs, f); + } + } + return rs; + } catch (final IOException ex) { + throw new PitError("Error handling file " + lastFile, ex); + } + } + + private static void handleArchive(final List rs, final File f) + throws IOException { + try { + if (!f.canRead()) { + throw new IOException("Can't read the file " + f); + } + rs.add(new ArchiveClassPathRoot(f)); + } catch (final ZipException ex) { + LOG.warning("Can't open the archive " + f); + } + } + + public byte[] getClassData(final String classname) throws IOException { + try (InputStream is = this.root.getData(classname)) { + if (is != null) { + return StreamUtil.streamToByteArray(is); + } else { + return null; + } + } + } + + public URL findResource(final String name) { + try { + return this.root.getResource(name); + } catch (final IOException exception) { + return null; + } + } + + public static Collection getClassPathElementsAsPaths() { + final Set filesAsString = new LinkedHashSet<>(); + FCollection.mapTo(getClassPathElementsAsFiles(), file -> file.getPath(), + filesAsString); + return filesAsString; + } + + + public static Collection getClassPathElementsAsFiles() { + final Set us = new LinkedHashSet<>(); + FCollection.mapTo(getClassPathElementsAsAre(), stringToCanonicalFile(), us); + return us; + } + + + public Collection findClasses(final Predicate nameFilter) { + return FCollection.filter(classNames(), nameFilter); + } + + public String getLocalClassPath() { + return this.root.cacheLocation().get(); + } + + public ClassPath getComponent(final Predicate predicate) { + return new ClassPath(FCollection.filter(this.root, predicate).toArray( + new ClassPathRoot[0])); + } + + private static Predicate exists() { + return a -> a.exists() && a.canRead(); + } + + private static Function stringToCanonicalFile() { + return fileAsString -> { + try { + return new File(fileAsString).getCanonicalFile(); + } catch (final IOException ex) { + throw new PitError("Error transforming classpath element " + + fileAsString, ex); + } + }; + } + + /** FIXME move somewhere common */ + private static List getClassPathElementsAsAre() { + final String classPath = System.getProperty("java.class.path"); + final String separator = File.pathSeparator; + if (classPath != null) { + return Arrays.asList(classPath.split(separator)); + } else { + return new ArrayList<>(); + } + + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/ClassPathByteArraySource.java b/pitest/src/main/java/org/pitest/classpath/ClassPathByteArraySource.java index d2c7f2d7d..c35c24e25 100644 --- a/pitest/src/main/java/org/pitest/classpath/ClassPathByteArraySource.java +++ b/pitest/src/main/java/org/pitest/classpath/ClassPathByteArraySource.java @@ -1,47 +1,47 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import java.io.IOException; -import java.util.logging.Logger; - -import org.pitest.classinfo.ClassByteArraySource; -import java.util.Optional; -import org.pitest.util.Log; - -public class ClassPathByteArraySource implements ClassByteArraySource { - - private static final Logger LOG = Log.getLogger(); - - private final ClassPath classPath; - - public ClassPathByteArraySource() { - this(new ClassPath()); - } - - public ClassPathByteArraySource(final ClassPath classPath) { - this.classPath = classPath; - } - - @Override - public Optional getBytes(final String classname) { - try { - return Optional.ofNullable(this.classPath.getClassData(classname)); - } catch (final IOException e) { - LOG.fine("Could not read class " + classname + ":" + e.getMessage()); - return Optional.empty(); - } - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import java.io.IOException; +import java.util.logging.Logger; + +import org.pitest.classinfo.ClassByteArraySource; +import java.util.Optional; +import org.pitest.util.Log; + +public class ClassPathByteArraySource implements ClassByteArraySource { + + private static final Logger LOG = Log.getLogger(); + + private final ClassPath classPath; + + public ClassPathByteArraySource() { + this(new ClassPath()); + } + + public ClassPathByteArraySource(final ClassPath classPath) { + this.classPath = classPath; + } + + @Override + public Optional getBytes(final String classname) { + try { + return Optional.ofNullable(this.classPath.getClassData(classname)); + } catch (final IOException e) { + LOG.fine("Could not read class " + classname + ":" + e.getMessage()); + return Optional.empty(); + } + } +} diff --git a/pitest/src/main/java/org/pitest/classpath/ClassPathRoot.java b/pitest/src/main/java/org/pitest/classpath/ClassPathRoot.java index d37125e8e..25dc93a09 100644 --- a/pitest/src/main/java/org/pitest/classpath/ClassPathRoot.java +++ b/pitest/src/main/java/org/pitest/classpath/ClassPathRoot.java @@ -1,35 +1,35 @@ -package org.pitest.classpath; - -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; - -import java.util.Optional; - -public interface ClassPathRoot { - - URL getResource(String name) throws MalformedURLException; - - InputStream getData(String name) throws IOException; - - Collection classNames(); - - Optional cacheLocation(); - -} +package org.pitest.classpath; + +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collection; + +import java.util.Optional; + +public interface ClassPathRoot { + + URL getResource(String name) throws MalformedURLException; + + InputStream getData(String name) throws IOException; + + Collection classNames(); + + Optional cacheLocation(); + +} diff --git a/pitest/src/main/java/org/pitest/classpath/ClassloaderByteArraySource.java b/pitest/src/main/java/org/pitest/classpath/ClassloaderByteArraySource.java index 121e988a3..0ad29cec0 100644 --- a/pitest/src/main/java/org/pitest/classpath/ClassloaderByteArraySource.java +++ b/pitest/src/main/java/org/pitest/classpath/ClassloaderByteArraySource.java @@ -1,45 +1,45 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import java.io.IOException; - -import org.pitest.classinfo.ClassByteArraySource; -import java.util.Optional; -import org.pitest.util.IsolationUtils; -import org.pitest.util.Unchecked; - -public class ClassloaderByteArraySource implements ClassByteArraySource { - - private final ClassPath cp; - - public ClassloaderByteArraySource(final ClassLoader loader) { - this.cp = new ClassPath(new OtherClassLoaderClassPathRoot(loader)); - } - - public static ClassloaderByteArraySource fromContext() { - return new ClassloaderByteArraySource(IsolationUtils.getContextClassLoader()); - } - - @Override - public Optional getBytes(final String classname) { - try { - return Optional.ofNullable(this.cp.getClassData(classname)); - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import java.io.IOException; + +import org.pitest.classinfo.ClassByteArraySource; +import java.util.Optional; +import org.pitest.util.IsolationUtils; +import org.pitest.util.Unchecked; + +public class ClassloaderByteArraySource implements ClassByteArraySource { + + private final ClassPath cp; + + public ClassloaderByteArraySource(final ClassLoader loader) { + this.cp = new ClassPath(new OtherClassLoaderClassPathRoot(loader)); + } + + public static ClassloaderByteArraySource fromContext() { + return new ClassloaderByteArraySource(IsolationUtils.getContextClassLoader()); + } + + @Override + public Optional getBytes(final String classname) { + try { + return Optional.ofNullable(this.cp.getClassData(classname)); + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex); + } + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/CodeSource.java b/pitest/src/main/java/org/pitest/classpath/CodeSource.java index 6157daefe..bd73b11ee 100644 --- a/pitest/src/main/java/org/pitest/classpath/CodeSource.java +++ b/pitest/src/main/java/org/pitest/classpath/CodeSource.java @@ -1,93 +1,93 @@ -package org.pitest.classpath; - -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassInfoSource; -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.NameToClassInfo; -import org.pitest.classinfo.Repository; -import org.pitest.classinfo.TestToClassMapper; -import org.pitest.functional.FCollection; -import org.pitest.functional.Streams; - -/** - * Provides access to code and tests on the classpath - */ -public class CodeSource implements ClassInfoSource { - - private final ProjectClassPaths classPath; - private final Repository classRepository; - - public CodeSource(final ProjectClassPaths classPath) { - this(classPath, new Repository(new ClassPathByteArraySource( - classPath.getClassPath()))); - } - - CodeSource(final ProjectClassPaths classPath, - final Repository classRepository) { - this.classPath = classPath; - this.classRepository = classRepository; - } - - public Collection getCode() { - return this.classPath.code().stream() - .flatMap(nameToClassInfo()) - .collect(Collectors.toList()); - } - - public Set getCodeUnderTestNames() { - final Set codeClasses = new HashSet<>(); - FCollection.mapTo(getCode(), ClassInfo.toClassName(), codeClasses); - return codeClasses; - } - - public List getTests() { - return this.classPath.test().stream() - .flatMap(nameToClassInfo()) - .filter(ClassInfo.matchIfAbstract().negate()) - .collect(Collectors.toList()); - } - - public ClassPath getClassPath() { - return this.classPath.getClassPath(); - } - - public ProjectClassPaths getProjectPaths() { - return this.classPath; - } - - public Optional findTestee(final String className) { - final TestToClassMapper mapper = new TestToClassMapper(this.classRepository); - return mapper.findTestee(className); - } - - public Collection getClassInfo(final Collection classes) { - return classes.stream() - .flatMap(nameToClassInfo()) - .collect(Collectors.toList()); - } - - // not used but keep to allow plugins to query bytecode - public Optional fetchClassBytes(final ClassName clazz) { - return this.classRepository.querySource(clazz); - } - - @Override - public Optional fetchClass(final ClassName clazz) { - return this.classRepository.fetchClass(clazz); - } - - private Function> nameToClassInfo() { - return new NameToClassInfo(this.classRepository) - .andThen(opt -> Streams.fromOptional(opt)); - } - -} +package org.pitest.classpath; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassInfoSource; +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.NameToClassInfo; +import org.pitest.classinfo.Repository; +import org.pitest.classinfo.TestToClassMapper; +import org.pitest.functional.FCollection; +import org.pitest.functional.Streams; + +/** + * Provides access to code and tests on the classpath. + */ +public class CodeSource implements ClassInfoSource { + + private final ProjectClassPaths classPath; + private final Repository classRepository; + + public CodeSource(final ProjectClassPaths classPath) { + this(classPath, new Repository(new ClassPathByteArraySource( + classPath.getClassPath()))); + } + + CodeSource(final ProjectClassPaths classPath, + final Repository classRepository) { + this.classPath = classPath; + this.classRepository = classRepository; + } + + public Collection getCode() { + return this.classPath.code().stream() + .flatMap(nameToClassInfo()) + .collect(Collectors.toList()); + } + + public Set getCodeUnderTestNames() { + final Set codeClasses = new HashSet<>(); + FCollection.mapTo(getCode(), ClassInfo.toClassName(), codeClasses); + return codeClasses; + } + + public List getTests() { + return this.classPath.test().stream() + .flatMap(nameToClassInfo()) + .filter(ClassInfo.matchIfAbstract().negate()) + .collect(Collectors.toList()); + } + + public ClassPath getClassPath() { + return this.classPath.getClassPath(); + } + + public ProjectClassPaths getProjectPaths() { + return this.classPath; + } + + public Optional findTestee(final String className) { + final TestToClassMapper mapper = new TestToClassMapper(this.classRepository); + return mapper.findTestee(className); + } + + public Collection getClassInfo(final Collection classes) { + return classes.stream() + .flatMap(nameToClassInfo()) + .collect(Collectors.toList()); + } + + // not used but keep to allow plugins to query bytecode + public Optional fetchClassBytes(final ClassName clazz) { + return this.classRepository.querySource(clazz); + } + + @Override + public Optional fetchClass(final ClassName clazz) { + return this.classRepository.fetchClass(clazz); + } + + private Function> nameToClassInfo() { + return new NameToClassInfo(this.classRepository) + .andThen(opt -> Streams.fromOptional(opt)); + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/CompoundClassPathRoot.java b/pitest/src/main/java/org/pitest/classpath/CompoundClassPathRoot.java index 3b9d1d000..3bb0178eb 100644 --- a/pitest/src/main/java/org/pitest/classpath/CompoundClassPathRoot.java +++ b/pitest/src/main/java/org/pitest/classpath/CompoundClassPathRoot.java @@ -1,88 +1,88 @@ -package org.pitest.classpath; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.pitest.functional.FCollection; -import java.util.Optional; - -public class CompoundClassPathRoot implements ClassPathRoot, - Iterable { - - private final List roots = new ArrayList<>(); - - public CompoundClassPathRoot(final List roots) { - this.roots.addAll(wrapToAvoidIOOperations(roots)); - } - - @Override - public InputStream getData(final String name) throws IOException { - for (final ClassPathRoot each : this.roots) { - final InputStream is = each.getData(name); - if (is != null) { - return is; - } - } - return null; - } - - @Override - public Collection classNames() { - final List arrayList = new ArrayList<>(); - for (final ClassPathRoot root : this.roots) { - arrayList.addAll(root.classNames()); - } - return arrayList; - } - - @Override - public URL getResource(String name) throws MalformedURLException { - try { - return findRootForResource(name); - } catch (final IOException exception) { - return null; - } - } - - private URL findRootForResource(final String name) throws IOException { - for (final ClassPathRoot root : this.roots) { - final URL u = root.getResource(name); - if (u != null) { - return u; - } - } - return null; - } - - @Override - public Optional cacheLocation() { - StringBuilder classpath = new StringBuilder(); - for (final ClassPathRoot each : this.roots) { - final Optional additional = each.cacheLocation(); - if (additional.isPresent()) { - classpath = classpath.append(File.pathSeparator + additional.get()); - } - } - - return Optional.ofNullable(classpath.toString()); - } - - @Override - public Iterator iterator() { - return this.roots.iterator(); - } - - private static List wrapToAvoidIOOperations( - List roots) { - return FCollection.map(roots, NameCachingRoot.toCachingRoot()); - } - - +package org.pitest.classpath; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.pitest.functional.FCollection; +import java.util.Optional; + +public class CompoundClassPathRoot implements ClassPathRoot, + Iterable { + + private final List roots = new ArrayList<>(); + + public CompoundClassPathRoot(final List roots) { + this.roots.addAll(wrapToAvoidIOOperations(roots)); + } + + @Override + public InputStream getData(final String name) throws IOException { + for (final ClassPathRoot each : this.roots) { + final InputStream is = each.getData(name); + if (is != null) { + return is; + } + } + return null; + } + + @Override + public Collection classNames() { + final List arrayList = new ArrayList<>(); + for (final ClassPathRoot root : this.roots) { + arrayList.addAll(root.classNames()); + } + return arrayList; + } + + @Override + public URL getResource(String name) throws MalformedURLException { + try { + return findRootForResource(name); + } catch (final IOException exception) { + return null; + } + } + + private URL findRootForResource(final String name) throws IOException { + for (final ClassPathRoot root : this.roots) { + final URL u = root.getResource(name); + if (u != null) { + return u; + } + } + return null; + } + + @Override + public Optional cacheLocation() { + StringBuilder classpath = new StringBuilder(); + for (final ClassPathRoot each : this.roots) { + final Optional additional = each.cacheLocation(); + if (additional.isPresent()) { + classpath = classpath.append(File.pathSeparator + additional.get()); + } + } + + return Optional.ofNullable(classpath.toString()); + } + + @Override + public Iterator iterator() { + return this.roots.iterator(); + } + + private static List wrapToAvoidIOOperations( + List roots) { + return FCollection.map(roots, NameCachingRoot.toCachingRoot()); + } + + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/classpath/DirectoryClassPathRoot.java b/pitest/src/main/java/org/pitest/classpath/DirectoryClassPathRoot.java index 010f16da7..50008540f 100644 --- a/pitest/src/main/java/org/pitest/classpath/DirectoryClassPathRoot.java +++ b/pitest/src/main/java/org/pitest/classpath/DirectoryClassPathRoot.java @@ -1,90 +1,90 @@ -package org.pitest.classpath; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import java.util.Optional; - -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -public class DirectoryClassPathRoot implements ClassPathRoot, IOHeavyRoot { - - private final File root; - - public DirectoryClassPathRoot(final File root) { - this.root = root; - } - - @Override - public InputStream getData(final String classname) throws IOException { - final String filename = classname.replace('.', File.separatorChar).concat( - ".class"); - final File file = new File(this.root, filename); - if (file.canRead()) { - return new FileInputStream(file); - } else { - return null; - } - } - - @Override - public URL getResource(final String name) throws MalformedURLException { - final File f = new File(this.root, name); - if (f.canRead()) { - // magically work around encoding issues - return f.toURI().toURL(); - } else { - return null; - } - } - - @Override - public Collection classNames() { - return classNames(this.root); - } - - private Collection classNames(final File file) { - final List classNames = new LinkedList<>(); - for (final File f : file.listFiles()) { - if (f.isDirectory()) { - classNames.addAll(classNames(f)); - } else if (f.getName().endsWith(".class")) { - classNames.add(fileToClassName(f)); - } - } - return classNames; - } - - private String fileToClassName(final File f) { - return f - .getAbsolutePath() - .substring(this.root.getAbsolutePath().length() + 1, - (f.getAbsolutePath().length() - ".class".length())) - .replace(File.separatorChar, '.'); - } - - @Override - public Optional cacheLocation() { - return Optional.ofNullable(this.root.getAbsolutePath()); - } - -} +package org.pitest.classpath; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import java.util.Optional; + +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +public class DirectoryClassPathRoot implements ClassPathRoot, IOHeavyRoot { + + private final File root; + + public DirectoryClassPathRoot(final File root) { + this.root = root; + } + + @Override + public InputStream getData(final String classname) throws IOException { + final String filename = classname.replace('.', File.separatorChar).concat( + ".class"); + final File file = new File(this.root, filename); + if (file.canRead()) { + return new FileInputStream(file); + } else { + return null; + } + } + + @Override + public URL getResource(final String name) throws MalformedURLException { + final File f = new File(this.root, name); + if (f.canRead()) { + // magically work around encoding issues + return f.toURI().toURL(); + } else { + return null; + } + } + + @Override + public Collection classNames() { + return classNames(this.root); + } + + private Collection classNames(final File file) { + final List classNames = new LinkedList<>(); + for (final File f : file.listFiles()) { + if (f.isDirectory()) { + classNames.addAll(classNames(f)); + } else if (f.getName().endsWith(".class")) { + classNames.add(fileToClassName(f)); + } + } + return classNames; + } + + private String fileToClassName(final File f) { + return f + .getAbsolutePath() + .substring(this.root.getAbsolutePath().length() + 1, + (f.getAbsolutePath().length() - ".class".length())) + .replace(File.separatorChar, '.'); + } + + @Override + public Optional cacheLocation() { + return Optional.ofNullable(this.root.getAbsolutePath()); + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/IOHeavyRoot.java b/pitest/src/main/java/org/pitest/classpath/IOHeavyRoot.java index 40f009147..e96d7da73 100644 --- a/pitest/src/main/java/org/pitest/classpath/IOHeavyRoot.java +++ b/pitest/src/main/java/org/pitest/classpath/IOHeavyRoot.java @@ -1,9 +1,9 @@ -package org.pitest.classpath; - -/** - * Marker interface for classpath roots that do - * expensive IO when searching - */ -public interface IOHeavyRoot extends ClassPathRoot { - -} +package org.pitest.classpath; + +/** + * Marker interface for classpath roots that do + * expensive IO when searching + */ +public interface IOHeavyRoot extends ClassPathRoot { + +} diff --git a/pitest/src/main/java/org/pitest/classpath/NameCachingRoot.java b/pitest/src/main/java/org/pitest/classpath/NameCachingRoot.java index d47f0546e..eef6017cf 100644 --- a/pitest/src/main/java/org/pitest/classpath/NameCachingRoot.java +++ b/pitest/src/main/java/org/pitest/classpath/NameCachingRoot.java @@ -1,71 +1,71 @@ -package org.pitest.classpath; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.SoftReference; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; -import java.util.function.Function; - -import org.pitest.classinfo.ClassName; -import java.util.Optional; - -/** - * Caches the classes provided by the decorated - * root to avoid expensive IO operations at the - * cost of higher memory consumption - */ -public class NameCachingRoot implements ClassPathRoot { - - private final ClassPathRoot child; - - private SoftReference> cache; - - public NameCachingRoot(ClassPathRoot child) { - this.child = child; - } - - @Override - public URL getResource(String name) throws MalformedURLException { - return this.child.getResource(name); - } - - @Override - public InputStream getData(String name) throws IOException { - final Collection names = classNames(); - if (!names.contains(ClassName.fromString(name).asJavaName())) { - return null; - } - return this.child.getData(name); - } - - @Override - public Collection classNames() { - if (this.cache != null) { - final Collection cachedNames = this.cache.get(); - if (cachedNames != null) { - return cachedNames; - } - } - final Collection names = this.child.classNames(); - this.cache = new SoftReference<>(names); - return names; - } - - @Override - public Optional cacheLocation() { - return this.child.cacheLocation(); - } - - public static Function toCachingRoot() { - return a -> { - // ugly hack to determine where caching will be useful - if (a instanceof IOHeavyRoot ) { - return new NameCachingRoot(a); - } - return a; - }; - } - -} +package org.pitest.classpath; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.ref.SoftReference; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collection; +import java.util.function.Function; + +import org.pitest.classinfo.ClassName; +import java.util.Optional; + +/** + * Caches the classes provided by the decorated + * root to avoid expensive IO operations at the + * cost of higher memory consumption + */ +public class NameCachingRoot implements ClassPathRoot { + + private final ClassPathRoot child; + + private SoftReference> cache; + + public NameCachingRoot(ClassPathRoot child) { + this.child = child; + } + + @Override + public URL getResource(String name) throws MalformedURLException { + return this.child.getResource(name); + } + + @Override + public InputStream getData(String name) throws IOException { + final Collection names = classNames(); + if (!names.contains(ClassName.fromString(name).asJavaName())) { + return null; + } + return this.child.getData(name); + } + + @Override + public Collection classNames() { + if (this.cache != null) { + final Collection cachedNames = this.cache.get(); + if (cachedNames != null) { + return cachedNames; + } + } + final Collection names = this.child.classNames(); + this.cache = new SoftReference<>(names); + return names; + } + + @Override + public Optional cacheLocation() { + return this.child.cacheLocation(); + } + + public static Function toCachingRoot() { + return a -> { + // ugly hack to determine where caching will be useful + if (a instanceof IOHeavyRoot ) { + return new NameCachingRoot(a); + } + return a; + }; + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/OtherClassLoaderClassPathRoot.java b/pitest/src/main/java/org/pitest/classpath/OtherClassLoaderClassPathRoot.java index cb0e0fe7e..962b1f770 100644 --- a/pitest/src/main/java/org/pitest/classpath/OtherClassLoaderClassPathRoot.java +++ b/pitest/src/main/java/org/pitest/classpath/OtherClassLoaderClassPathRoot.java @@ -1,54 +1,54 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; - -import java.util.Optional; - -public class OtherClassLoaderClassPathRoot implements ClassPathRoot { - - private final ClassLoader loader; - - public OtherClassLoaderClassPathRoot(final ClassLoader loader) { - this.loader = loader; - } - - @Override - public Collection classNames() { - throw new UnsupportedOperationException(); - } - - @Override - public InputStream getData(final String name) throws IOException { - // TODO will this work for archives? Need to consider remote hetrogenous os - return this.loader.getResourceAsStream(name.replace(".", "/") + ".class"); - } - - @Override - public URL getResource(final String name) throws MalformedURLException { - return this.loader.getResource(name); - } - - @Override - public Optional cacheLocation() { - return Optional.empty(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collection; + +import java.util.Optional; + +public class OtherClassLoaderClassPathRoot implements ClassPathRoot { + + private final ClassLoader loader; + + public OtherClassLoaderClassPathRoot(final ClassLoader loader) { + this.loader = loader; + } + + @Override + public Collection classNames() { + throw new UnsupportedOperationException(); + } + + @Override + public InputStream getData(final String name) throws IOException { + // TODO will this work for archives? Need to consider remote hetrogenous os + return this.loader.getResourceAsStream(name.replace(".", "/") + ".class"); + } + + @Override + public URL getResource(final String name) throws MalformedURLException { + return this.loader.getResource(name); + } + + @Override + public Optional cacheLocation() { + return Optional.empty(); + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/PathFilter.java b/pitest/src/main/java/org/pitest/classpath/PathFilter.java index 31f0f7087..a5a20ef08 100644 --- a/pitest/src/main/java/org/pitest/classpath/PathFilter.java +++ b/pitest/src/main/java/org/pitest/classpath/PathFilter.java @@ -1,38 +1,38 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import java.util.function.Predicate; - -public class PathFilter { - - private final Predicate codeFilter; - private final Predicate testFilter; - - public PathFilter(final Predicate codeFilter, - final Predicate testFilter) { - this.codeFilter = codeFilter; - this.testFilter = testFilter; - } - - public Predicate getCodeFilter() { - return this.codeFilter; - } - - public Predicate getTestFilter() { - return this.testFilter; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import java.util.function.Predicate; + +public class PathFilter { + + private final Predicate codeFilter; + private final Predicate testFilter; + + public PathFilter(final Predicate codeFilter, + final Predicate testFilter) { + this.codeFilter = codeFilter; + this.testFilter = testFilter; + } + + public Predicate getCodeFilter() { + return this.codeFilter; + } + + public Predicate getTestFilter() { + return this.testFilter; + } + +} diff --git a/pitest/src/main/java/org/pitest/classpath/ProjectClassPaths.java b/pitest/src/main/java/org/pitest/classpath/ProjectClassPaths.java index af56327d5..a255ecc03 100644 --- a/pitest/src/main/java/org/pitest/classpath/ProjectClassPaths.java +++ b/pitest/src/main/java/org/pitest/classpath/ProjectClassPaths.java @@ -1,62 +1,62 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import java.util.Collection; -import java.util.stream.Collectors; - -import org.pitest.classinfo.ClassName; -import org.pitest.functional.FCollection; - -public class ProjectClassPaths { - - private final ClassPath classPath; - private final ClassFilter classFilter; - private final PathFilter pathFilter; - - public ProjectClassPaths(final ClassPath classPath, - final ClassFilter classFilter, final PathFilter pathFilter) { - this.classPath = classPath; - this.classFilter = classFilter; - this.pathFilter = pathFilter; - } - - public Collection code() { - return FCollection.filter( - this.classPath.getComponent(this.pathFilter.getCodeFilter()) - .findClasses(this.classFilter.getCode()), - this.classFilter.getCode()).stream() - .map(ClassName.stringToClassName()) - .collect(Collectors.toList()); - } - - public Collection test() { - return FCollection.filter( - this.classPath.getComponent(this.pathFilter.getTestFilter()) - .findClasses(this.classFilter.getTest()), - this.classFilter.getTest()).stream() - .map(ClassName.stringToClassName()) - .collect(Collectors.toList()); - } - - public ClassPath getClassPath() { - return this.classPath; - } - - public ClassFilter getFilter() { - return this.classFilter; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import java.util.Collection; +import java.util.stream.Collectors; + +import org.pitest.classinfo.ClassName; +import org.pitest.functional.FCollection; + +public class ProjectClassPaths { + + private final ClassPath classPath; + private final ClassFilter classFilter; + private final PathFilter pathFilter; + + public ProjectClassPaths(final ClassPath classPath, + final ClassFilter classFilter, final PathFilter pathFilter) { + this.classPath = classPath; + this.classFilter = classFilter; + this.pathFilter = pathFilter; + } + + public Collection code() { + return FCollection.filter( + this.classPath.getComponent(this.pathFilter.getCodeFilter()) + .findClasses(this.classFilter.getCode()), + this.classFilter.getCode()).stream() + .map(ClassName.stringToClassName()) + .collect(Collectors.toList()); + } + + public Collection test() { + return FCollection.filter( + this.classPath.getComponent(this.pathFilter.getTestFilter()) + .findClasses(this.classFilter.getTest()), + this.classFilter.getTest()).stream() + .map(ClassName.stringToClassName()) + .collect(Collectors.toList()); + } + + public ClassPath getClassPath() { + return this.classPath; + } + + public ClassFilter getFilter() { + return this.classFilter; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/BlockCoverage.java b/pitest/src/main/java/org/pitest/coverage/BlockCoverage.java index 4da8e64d0..7a4879b70 100644 --- a/pitest/src/main/java/org/pitest/coverage/BlockCoverage.java +++ b/pitest/src/main/java/org/pitest/coverage/BlockCoverage.java @@ -1,23 +1,23 @@ -package org.pitest.coverage; - -import java.util.Collection; - -public class BlockCoverage { - - private final BlockLocation block; - private final Collection tests; - - public BlockCoverage(final BlockLocation block, final Collection tests) { - this.block = block; - this.tests = tests; - } - - public BlockLocation getBlock() { - return this.block; - } - - public Collection getTests() { - return this.tests; - } - -} +package org.pitest.coverage; + +import java.util.Collection; + +public class BlockCoverage { + + private final BlockLocation block; + private final Collection tests; + + public BlockCoverage(final BlockLocation block, final Collection tests) { + this.block = block; + this.tests = tests; + } + + public BlockLocation getBlock() { + return this.block; + } + + public Collection getTests() { + return this.tests; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/BlockLocation.java b/pitest/src/main/java/org/pitest/coverage/BlockLocation.java index 23b9a782e..48febebc6 100644 --- a/pitest/src/main/java/org/pitest/coverage/BlockLocation.java +++ b/pitest/src/main/java/org/pitest/coverage/BlockLocation.java @@ -1,74 +1,74 @@ -package org.pitest.coverage; - -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.Location; - -public final class BlockLocation { - - private final Location location; - private final int block; - - public BlockLocation(final Location location, final int block) { - this.location = location; - this.block = block; - } - - public static BlockLocation blockLocation(final Location location, - final int block) { - return new BlockLocation(location, block); - } - - public boolean isFor(final ClassName clazz) { - return this.location.getClassName().equals(clazz); - } - - public int getBlock() { - return this.block; - } - - public Location getLocation() { - return this.location; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + this.block; - result = (prime * result) - + ((this.location == null) ? 0 : this.location.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final BlockLocation other = (BlockLocation) obj; - if (this.block != other.block) { - return false; - } - if (this.location == null) { - if (other.location != null) { - return false; - } - } else if (!this.location.equals(other.location)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "BlockLocation [location=" + this.location + ", block=" + this.block - + "]"; - } - -} +package org.pitest.coverage; + +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.Location; + +public final class BlockLocation { + + private final Location location; + private final int block; + + public BlockLocation(final Location location, final int block) { + this.location = location; + this.block = block; + } + + public static BlockLocation blockLocation(final Location location, + final int block) { + return new BlockLocation(location, block); + } + + public boolean isFor(final ClassName clazz) { + return this.location.getClassName().equals(clazz); + } + + public int getBlock() { + return this.block; + } + + public Location getLocation() { + return this.location; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + this.block; + result = (prime * result) + + ((this.location == null) ? 0 : this.location.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final BlockLocation other = (BlockLocation) obj; + if (this.block != other.block) { + return false; + } + if (this.location == null) { + if (other.location != null) { + return false; + } + } else if (!this.location.equals(other.location)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "BlockLocation [location=" + this.location + ", block=" + this.block + + "]"; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/ClassLine.java b/pitest/src/main/java/org/pitest/coverage/ClassLine.java index 3809eb0f8..263f543d3 100644 --- a/pitest/src/main/java/org/pitest/coverage/ClassLine.java +++ b/pitest/src/main/java/org/pitest/coverage/ClassLine.java @@ -1,81 +1,81 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.coverage; - -import org.pitest.classinfo.ClassName; - -public final class ClassLine { - private final ClassName clazz; - private final int lineNumber; - - public ClassLine(final String clazz, final int lineNumber) { - this(ClassName.fromString(clazz), lineNumber); - } - - public ClassLine(final ClassName clazz, final int lineNumber) { - this.clazz = clazz; - this.lineNumber = lineNumber; - } - - public ClassName getClassName() { - return this.clazz; - } - - public int getLineNumber() { - return this.lineNumber; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.clazz == null) ? 0 : this.clazz.hashCode()); - result = (prime * result) + this.lineNumber; - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ClassLine other = (ClassLine) obj; - if (this.clazz == null) { - if (other.clazz != null) { - return false; - } - } else if (!this.clazz.equals(other.clazz)) { - return false; - } - if (this.lineNumber != other.lineNumber) { - return false; - } - return true; - } - - @Override - public String toString() { - return "ClassLine [" + this.clazz + ":" + this.lineNumber + "]"; - } - +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.coverage; + +import org.pitest.classinfo.ClassName; + +public final class ClassLine { + private final ClassName clazz; + private final int lineNumber; + + public ClassLine(final String clazz, final int lineNumber) { + this(ClassName.fromString(clazz), lineNumber); + } + + public ClassLine(final ClassName clazz, final int lineNumber) { + this.clazz = clazz; + this.lineNumber = lineNumber; + } + + public ClassName getClassName() { + return this.clazz; + } + + public int getLineNumber() { + return this.lineNumber; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.clazz == null) ? 0 : this.clazz.hashCode()); + result = (prime * result) + this.lineNumber; + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ClassLine other = (ClassLine) obj; + if (this.clazz == null) { + if (other.clazz != null) { + return false; + } + } else if (!this.clazz.equals(other.clazz)) { + return false; + } + if (this.lineNumber != other.lineNumber) { + return false; + } + return true; + } + + @Override + public String toString() { + return "ClassLine [" + this.clazz + ":" + this.lineNumber + "]"; + } + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/coverage/CoverageReceiver.java b/pitest/src/main/java/org/pitest/coverage/CoverageReceiver.java index d6dccd5b6..0f72eeb71 100644 --- a/pitest/src/main/java/org/pitest/coverage/CoverageReceiver.java +++ b/pitest/src/main/java/org/pitest/coverage/CoverageReceiver.java @@ -1,14 +1,14 @@ -package org.pitest.coverage; - -import org.pitest.testapi.Description; - -import sun.pitest.InvokeReceiver; - -public interface CoverageReceiver extends InvokeReceiver { - - void newTest(); - - void recordTestOutcome(Description description, boolean wasGreen, - int executionTime); - +package org.pitest.coverage; + +import org.pitest.testapi.Description; + +import sun.pitest.InvokeReceiver; + +public interface CoverageReceiver extends InvokeReceiver { + + void newTest(); + + void recordTestOutcome(Description description, boolean wasGreen, + int executionTime); + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/coverage/CoverageResult.java b/pitest/src/main/java/org/pitest/coverage/CoverageResult.java index 4558846ae..21e0c7e3e 100644 --- a/pitest/src/main/java/org/pitest/coverage/CoverageResult.java +++ b/pitest/src/main/java/org/pitest/coverage/CoverageResult.java @@ -1,50 +1,50 @@ -package org.pitest.coverage; - -import java.util.Collection; - -import org.pitest.testapi.Description; - -public class CoverageResult { - - private final Description testUnitDescription; - private final int executionTime; - private final Collection visitedBlocks; - private final boolean greenSuite; - - public CoverageResult(final Description testUnitDescription, - final int executionTime, final boolean greenSuite, - final Collection visitedBlocks) { - this.testUnitDescription = testUnitDescription; - this.executionTime = executionTime; - this.visitedBlocks = visitedBlocks; - this.greenSuite = greenSuite; - } - - public Description getTestUnitDescription() { - return this.testUnitDescription; - } - - public int getExecutionTime() { - return this.executionTime; - } - - public Collection getCoverage() { - return this.visitedBlocks; - } - - public boolean isGreenTest() { - return this.greenSuite; - } - - public int getNumberOfCoveredBlocks() { - return this.visitedBlocks.size(); - } - - @Override - public String toString() { - return "CoverageResult [testUnitDescription=" + this.testUnitDescription - + ", executionTime=" + this.executionTime + ", coverage=" - + this.visitedBlocks + ", greenSuite=" + this.greenSuite + "]"; - } - -} +package org.pitest.coverage; + +import java.util.Collection; + +import org.pitest.testapi.Description; + +public class CoverageResult { + + private final Description testUnitDescription; + private final int executionTime; + private final Collection visitedBlocks; + private final boolean greenSuite; + + public CoverageResult(final Description testUnitDescription, + final int executionTime, final boolean greenSuite, + final Collection visitedBlocks) { + this.testUnitDescription = testUnitDescription; + this.executionTime = executionTime; + this.visitedBlocks = visitedBlocks; + this.greenSuite = greenSuite; + } + + public Description getTestUnitDescription() { + return this.testUnitDescription; + } + + public int getExecutionTime() { + return this.executionTime; + } + + public Collection getCoverage() { + return this.visitedBlocks; + } + + public boolean isGreenTest() { + return this.greenSuite; + } + + public int getNumberOfCoveredBlocks() { + return this.visitedBlocks.size(); + } + + @Override + public String toString() { + return "CoverageResult [testUnitDescription=" + this.testUnitDescription + + ", executionTime=" + this.executionTime + ", coverage=" + + this.visitedBlocks + ", greenSuite=" + this.greenSuite + "]"; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/CoverageTransformer.java b/pitest/src/main/java/org/pitest/coverage/CoverageTransformer.java index e7e2d02df..983a88728 100644 --- a/pitest/src/main/java/org/pitest/coverage/CoverageTransformer.java +++ b/pitest/src/main/java/org/pitest/coverage/CoverageTransformer.java @@ -1,70 +1,70 @@ -package org.pitest.coverage; - -import java.lang.instrument.ClassFileTransformer; -import java.lang.instrument.IllegalClassFormatException; -import java.security.ProtectionDomain; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Predicate; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.pitest.bytecode.FrameOptions; -import org.pitest.classinfo.ComputeClassWriter; -import org.pitest.classpath.ClassloaderByteArraySource; - -import sun.pitest.CodeCoverageStore; - -public class CoverageTransformer implements ClassFileTransformer { - - private final Predicate filter; - private final Map computeCache = new ConcurrentHashMap<>(); - - public CoverageTransformer(final Predicate filter) { - this.filter = filter; - } - - @Override - public byte[] transform(final ClassLoader loader, final String className, - final Class classBeingRedefined, - final ProtectionDomain protectionDomain, final byte[] classfileBuffer) - throws IllegalClassFormatException { - final boolean include = shouldInclude(className); - if (include) { - try { - return transformBytes(pickLoader(loader), className, classfileBuffer); - } catch (final RuntimeException t) { - System.err.println("RuntimeException while transforming " + className); - t.printStackTrace(); - throw t; - } - } else { - return null; - } - } - - private byte[] transformBytes(final ClassLoader loader, - final String className, final byte[] classfileBuffer) { - final ClassReader reader = new ClassReader(classfileBuffer); - final ClassWriter writer = new ComputeClassWriter( - new ClassloaderByteArraySource(loader), this.computeCache, - FrameOptions.pickFlags(classfileBuffer)); - - final int id = CodeCoverageStore.registerClass(className); - reader.accept(new CoverageClassVisitor(id, writer), - ClassReader.EXPAND_FRAMES); - return writer.toByteArray(); - } - - private boolean shouldInclude(final String className) { - return this.filter.test(className); - } - - private ClassLoader pickLoader(ClassLoader loader) { - if (loader != null) { - return loader; - } - return ClassLoader.getSystemClassLoader(); - } - -} +package org.pitest.coverage; + +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.IllegalClassFormatException; +import java.security.ProtectionDomain; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.pitest.bytecode.FrameOptions; +import org.pitest.classinfo.ComputeClassWriter; +import org.pitest.classpath.ClassloaderByteArraySource; + +import sun.pitest.CodeCoverageStore; + +public class CoverageTransformer implements ClassFileTransformer { + + private final Predicate filter; + private final Map computeCache = new ConcurrentHashMap<>(); + + public CoverageTransformer(final Predicate filter) { + this.filter = filter; + } + + @Override + public byte[] transform(final ClassLoader loader, final String className, + final Class classBeingRedefined, + final ProtectionDomain protectionDomain, final byte[] classfileBuffer) + throws IllegalClassFormatException { + final boolean include = shouldInclude(className); + if (include) { + try { + return transformBytes(pickLoader(loader), className, classfileBuffer); + } catch (final RuntimeException t) { + System.err.println("RuntimeException while transforming " + className); + t.printStackTrace(); + throw t; + } + } else { + return null; + } + } + + private byte[] transformBytes(final ClassLoader loader, + final String className, final byte[] classfileBuffer) { + final ClassReader reader = new ClassReader(classfileBuffer); + final ClassWriter writer = new ComputeClassWriter( + new ClassloaderByteArraySource(loader), this.computeCache, + FrameOptions.pickFlags(classfileBuffer)); + + final int id = CodeCoverageStore.registerClass(className); + reader.accept(new CoverageClassVisitor(id, writer), + ClassReader.EXPAND_FRAMES); + return writer.toByteArray(); + } + + private boolean shouldInclude(final String className) { + return this.filter.test(className); + } + + private ClassLoader pickLoader(ClassLoader loader) { + if (loader != null) { + return loader; + } + return ClassLoader.getSystemClassLoader(); + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/LineMap.java b/pitest/src/main/java/org/pitest/coverage/LineMap.java index e54fa12e5..a99f64b90 100644 --- a/pitest/src/main/java/org/pitest/coverage/LineMap.java +++ b/pitest/src/main/java/org/pitest/coverage/LineMap.java @@ -1,12 +1,12 @@ -package org.pitest.coverage; - -import java.util.Map; -import java.util.Set; - -import org.pitest.classinfo.ClassName; - -public interface LineMap { - - Map> mapLines(ClassName clazz); - +package org.pitest.coverage; + +import java.util.Map; +import java.util.Set; + +import org.pitest.classinfo.ClassName; + +public interface LineMap { + + Map> mapLines(ClassName clazz); + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/coverage/TestInfo.java b/pitest/src/main/java/org/pitest/coverage/TestInfo.java index ff4d9e61c..cd8f0db29 100644 --- a/pitest/src/main/java/org/pitest/coverage/TestInfo.java +++ b/pitest/src/main/java/org/pitest/coverage/TestInfo.java @@ -1,121 +1,121 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage; - -import java.io.Serializable; -import java.util.function.Function; - -import org.pitest.classinfo.ClassName; -import java.util.Optional; - - -public final class TestInfo implements Serializable { - - private static final long serialVersionUID = 1L; - - private final String name; - private final String definingClass; - - private final int time; - private final int blocks; - - private final ClassName testee; - - public TestInfo(final String definingClass, final String name, - final int time, final Optional testee, final int blocksCovered) { - this.definingClass = internIfNotNull(definingClass); - this.name = name; - this.time = time; - this.testee = testee.orElse(null); - this.blocks = blocksCovered; - } - - public String getName() { - return this.name; - } - - public int getTime() { - return this.time; - } - - public int getNumberOfBlocksCovered() { - return this.blocks; - } - - @Override - public String toString() { - return this.name; - } - - public static Function toName() { - return a -> a.getName(); - } - - public static Function toDefiningClassName() { - return a -> ClassName.fromString(a.definingClass); - } - - public boolean directlyHits(final ClassName targetClass) { - return this.testee != null && this.testee.equals(targetClass); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.definingClass == null) ? 0 : this.definingClass.hashCode()); - result = (prime * result) - + ((this.name == null) ? 0 : this.name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final TestInfo other = (TestInfo) obj; - if (this.definingClass == null) { - if (other.definingClass != null) { - return false; - } - } else if (!this.definingClass.equals(other.definingClass)) { - return false; - } - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - return true; - } - - private static String internIfNotNull(final String string) { - if (string == null) { - return null; - } - return string.intern(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage; + +import java.io.Serializable; +import java.util.function.Function; + +import org.pitest.classinfo.ClassName; +import java.util.Optional; + + +public final class TestInfo implements Serializable { + + private static final long serialVersionUID = 1L; + + private final String name; + private final String definingClass; + + private final int time; + private final int blocks; + + private final ClassName testee; + + public TestInfo(final String definingClass, final String name, + final int time, final Optional testee, final int blocksCovered) { + this.definingClass = internIfNotNull(definingClass); + this.name = name; + this.time = time; + this.testee = testee.orElse(null); + this.blocks = blocksCovered; + } + + public String getName() { + return this.name; + } + + public int getTime() { + return this.time; + } + + public int getNumberOfBlocksCovered() { + return this.blocks; + } + + @Override + public String toString() { + return this.name; + } + + public static Function toName() { + return a -> a.getName(); + } + + public static Function toDefiningClassName() { + return a -> ClassName.fromString(a.definingClass); + } + + public boolean directlyHits(final ClassName targetClass) { + return this.testee != null && this.testee.equals(targetClass); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.definingClass == null) ? 0 : this.definingClass.hashCode()); + result = (prime * result) + + ((this.name == null) ? 0 : this.name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final TestInfo other = (TestInfo) obj; + if (this.definingClass == null) { + if (other.definingClass != null) { + return false; + } + } else if (!this.definingClass.equals(other.definingClass)) { + return false; + } + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + return true; + } + + private static String internIfNotNull(final String string) { + if (string == null) { + return null; + } + return string.intern(); + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/TestInfoNameComparator.java b/pitest/src/main/java/org/pitest/coverage/TestInfoNameComparator.java index 4725300f0..eac60aeac 100644 --- a/pitest/src/main/java/org/pitest/coverage/TestInfoNameComparator.java +++ b/pitest/src/main/java/org/pitest/coverage/TestInfoNameComparator.java @@ -1,30 +1,30 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.coverage; - -import java.io.Serializable; -import java.util.Comparator; - -class TestInfoNameComparator implements Comparator, Serializable { - - private static final long serialVersionUID = 1L; - - @Override - public int compare(final TestInfo lhs, final TestInfo rhs) { // NO_UCD - return lhs.getName().compareTo(rhs.getName()); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.coverage; + +import java.io.Serializable; +import java.util.Comparator; + +class TestInfoNameComparator implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(final TestInfo lhs, final TestInfo rhs) { // NO_UCD + return lhs.getName().compareTo(rhs.getName()); + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/analysis/AbstractCoverageStrategy.java b/pitest/src/main/java/org/pitest/coverage/analysis/AbstractCoverageStrategy.java index f6460220e..1ac3732e0 100644 --- a/pitest/src/main/java/org/pitest/coverage/analysis/AbstractCoverageStrategy.java +++ b/pitest/src/main/java/org/pitest/coverage/analysis/AbstractCoverageStrategy.java @@ -1,232 +1,232 @@ -package org.pitest.coverage.analysis; - -import java.util.List; - -import org.objectweb.asm.Handle; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.commons.AdviceAdapter; -import org.pitest.mutationtest.engine.gregor.analysis.InstructionCounter; - -abstract class AbstractCoverageStrategy extends AdviceAdapter { - - protected final MethodVisitor methodVisitor; - protected final int classId; - protected final int probeOffset; - protected final List blocks; - - private final InstructionCounter counter; - - /** - * label to mark start of try finally block that is added to each method - */ - private final Label before = new Label(); - - /** - * label to mark handler block of try finally - */ - private final Label handler = new Label(); - - protected int probeCount = 0; - - AbstractCoverageStrategy(List blocks, InstructionCounter counter, - final int classId, final MethodVisitor writer, final int access, - final String name, final String desc, final int probeOffset) { - super(Opcodes.ASM6, writer, access, name, desc); - - this.methodVisitor = writer; - this.classId = classId; - this.counter = counter; - this.blocks = blocks; - this.probeOffset = probeOffset; - } - - abstract void prepare(); - - abstract void generateProbeReportCode(); - - abstract void insertProbe(); - - @Override - public void visitCode() { - super.visitCode(); - - prepare(); - - this.mv.visitLabel(this.before); - } - - @Override - public void visitMaxs(final int maxStack, final int maxLocals) { - - this.mv.visitTryCatchBlock(this.before, this.handler, this.handler, null); - this.mv.visitLabel(this.handler); - - generateProbeReportCode(); - - this.mv.visitInsn(ATHROW); - - // values actually unimportant as we're using compute max - this.mv.visitMaxs(maxStack, this.nextLocal); - } - - @Override - protected void onMethodExit(final int opcode) { - // generated catch block will handle any throws ending block - if (opcode != ATHROW) { - generateProbeReportCode(); - } - } - - protected void pushConstant(final int value) { - switch (value) { - case 0: - this.mv.visitInsn(ICONST_0); - break; - case 1: - this.mv.visitInsn(ICONST_1); - break; - case 2: - this.mv.visitInsn(ICONST_2); - break; - case 3: - this.mv.visitInsn(ICONST_3); - break; - case 4: - this.mv.visitInsn(ICONST_4); - break; - case 5: - this.mv.visitInsn(ICONST_5); - break; - default: - if (value <= Byte.MAX_VALUE) { - this.mv.visitIntInsn(Opcodes.BIPUSH, value); - } else if (value <= Short.MAX_VALUE) { - this.mv.visitIntInsn(Opcodes.SIPUSH, value); - } else { - this.mv.visitLdcInsn(value); - } - } - } - - @Override - public void visitFrame(final int type, final int nLocal, - final Object[] local, final int nStack, final Object[] stack) { - insertProbeIfAppropriate(); - super.visitFrame(type, nLocal, local, nStack, stack); - } - - @Override - public void visitInsn(final int opcode) { - insertProbeIfAppropriate(); - super.visitInsn(opcode); - } - - @Override - public void visitIntInsn(final int opcode, final int operand) { - insertProbeIfAppropriate(); - super.visitIntInsn(opcode, operand); - } - - @Override - public void visitVarInsn(final int opcode, final int var) { - insertProbeIfAppropriate(); - super.visitVarInsn(opcode, var); - } - - @Override - public void visitTypeInsn(final int opcode, final String type) { - insertProbeIfAppropriate(); - super.visitTypeInsn(opcode, type); - } - - @Override - public void visitFieldInsn(final int opcode, final String owner, - final String name, final String desc) { - insertProbeIfAppropriate(); - super.visitFieldInsn(opcode, owner, name, desc); - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, - final String name, final String desc, boolean itf) { - insertProbeIfAppropriate(); - super.visitMethodInsn(opcode, owner, name, desc, itf); - } - - @Override - public void visitInvokeDynamicInsn(final String name, final String desc, - final Handle bsm, final Object... bsmArgs) { - insertProbeIfAppropriate(); - super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); - } - - @Override - public void visitJumpInsn(final int opcode, final Label label) { - insertProbeIfAppropriate(); - super.visitJumpInsn(opcode, label); - } - - @Override - public void visitLabel(final Label label) { - super.visitLabel(label); - // note - probe goes after the label - insertProbeIfAppropriate(); - } - - @Override - public void visitLdcInsn(final Object cst) { - insertProbeIfAppropriate(); - super.visitLdcInsn(cst); - } - - @Override - public void visitIincInsn(final int var, final int increment) { - insertProbeIfAppropriate(); - super.visitIincInsn(var, increment); - } - - @Override - public void visitTableSwitchInsn(final int min, final int max, - final Label dflt, final Label... labels) { - insertProbeIfAppropriate(); - super.visitTableSwitchInsn(min, max, dflt, labels); - } - - @Override - public void visitLookupSwitchInsn(final Label dflt, final int[] keys, - final Label[] labels) { - insertProbeIfAppropriate(); - super.visitLookupSwitchInsn(dflt, keys, labels); - } - - @Override - public void visitMultiANewArrayInsn(final String desc, final int dims) { - insertProbeIfAppropriate(); - super.visitMultiANewArrayInsn(desc, dims); - } - - @Override - public void visitLineNumber(final int line, final Label start) { - insertProbeIfAppropriate(); - super.visitLineNumber(line, start); - } - - private void insertProbeIfAppropriate() { - if (needsProbe(this.counter.currentInstructionCount())) { - insertProbe(); - this.probeCount++; - } - } - - private boolean needsProbe(int currentInstructionCount) { - for (final Block each : this.blocks) { - if (each.firstInstructionIs(currentInstructionCount - 1)) { - return true; - } - } - return false; - } - +package org.pitest.coverage.analysis; + +import java.util.List; + +import org.objectweb.asm.Handle; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.commons.AdviceAdapter; +import org.pitest.mutationtest.engine.gregor.analysis.InstructionCounter; + +abstract class AbstractCoverageStrategy extends AdviceAdapter { + + protected final MethodVisitor methodVisitor; + protected final int classId; + protected final int probeOffset; + protected final List blocks; + + private final InstructionCounter counter; + + /** + * label to mark start of try finally block that is added to each method + */ + private final Label before = new Label(); + + /** + * label to mark handler block of try finally + */ + private final Label handler = new Label(); + + protected int probeCount = 0; + + AbstractCoverageStrategy(List blocks, InstructionCounter counter, + final int classId, final MethodVisitor writer, final int access, + final String name, final String desc, final int probeOffset) { + super(Opcodes.ASM6, writer, access, name, desc); + + this.methodVisitor = writer; + this.classId = classId; + this.counter = counter; + this.blocks = blocks; + this.probeOffset = probeOffset; + } + + abstract void prepare(); + + abstract void generateProbeReportCode(); + + abstract void insertProbe(); + + @Override + public void visitCode() { + super.visitCode(); + + prepare(); + + this.mv.visitLabel(this.before); + } + + @Override + public void visitMaxs(final int maxStack, final int maxLocals) { + + this.mv.visitTryCatchBlock(this.before, this.handler, this.handler, null); + this.mv.visitLabel(this.handler); + + generateProbeReportCode(); + + this.mv.visitInsn(ATHROW); + + // values actually unimportant as we're using compute max + this.mv.visitMaxs(maxStack, this.nextLocal); + } + + @Override + protected void onMethodExit(final int opcode) { + // generated catch block will handle any throws ending block + if (opcode != ATHROW) { + generateProbeReportCode(); + } + } + + protected void pushConstant(final int value) { + switch (value) { + case 0: + this.mv.visitInsn(ICONST_0); + break; + case 1: + this.mv.visitInsn(ICONST_1); + break; + case 2: + this.mv.visitInsn(ICONST_2); + break; + case 3: + this.mv.visitInsn(ICONST_3); + break; + case 4: + this.mv.visitInsn(ICONST_4); + break; + case 5: + this.mv.visitInsn(ICONST_5); + break; + default: + if (value <= Byte.MAX_VALUE) { + this.mv.visitIntInsn(Opcodes.BIPUSH, value); + } else if (value <= Short.MAX_VALUE) { + this.mv.visitIntInsn(Opcodes.SIPUSH, value); + } else { + this.mv.visitLdcInsn(value); + } + } + } + + @Override + public void visitFrame(final int type, final int nLocal, + final Object[] local, final int nStack, final Object[] stack) { + insertProbeIfAppropriate(); + super.visitFrame(type, nLocal, local, nStack, stack); + } + + @Override + public void visitInsn(final int opcode) { + insertProbeIfAppropriate(); + super.visitInsn(opcode); + } + + @Override + public void visitIntInsn(final int opcode, final int operand) { + insertProbeIfAppropriate(); + super.visitIntInsn(opcode, operand); + } + + @Override + public void visitVarInsn(final int opcode, final int var) { + insertProbeIfAppropriate(); + super.visitVarInsn(opcode, var); + } + + @Override + public void visitTypeInsn(final int opcode, final String type) { + insertProbeIfAppropriate(); + super.visitTypeInsn(opcode, type); + } + + @Override + public void visitFieldInsn(final int opcode, final String owner, + final String name, final String desc) { + insertProbeIfAppropriate(); + super.visitFieldInsn(opcode, owner, name, desc); + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, + final String name, final String desc, boolean itf) { + insertProbeIfAppropriate(); + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + + @Override + public void visitInvokeDynamicInsn(final String name, final String desc, + final Handle bsm, final Object... bsmArgs) { + insertProbeIfAppropriate(); + super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); + } + + @Override + public void visitJumpInsn(final int opcode, final Label label) { + insertProbeIfAppropriate(); + super.visitJumpInsn(opcode, label); + } + + @Override + public void visitLabel(final Label label) { + super.visitLabel(label); + // note - probe goes after the label + insertProbeIfAppropriate(); + } + + @Override + public void visitLdcInsn(final Object cst) { + insertProbeIfAppropriate(); + super.visitLdcInsn(cst); + } + + @Override + public void visitIincInsn(final int var, final int increment) { + insertProbeIfAppropriate(); + super.visitIincInsn(var, increment); + } + + @Override + public void visitTableSwitchInsn(final int min, final int max, + final Label dflt, final Label... labels) { + insertProbeIfAppropriate(); + super.visitTableSwitchInsn(min, max, dflt, labels); + } + + @Override + public void visitLookupSwitchInsn(final Label dflt, final int[] keys, + final Label[] labels) { + insertProbeIfAppropriate(); + super.visitLookupSwitchInsn(dflt, keys, labels); + } + + @Override + public void visitMultiANewArrayInsn(final String desc, final int dims) { + insertProbeIfAppropriate(); + super.visitMultiANewArrayInsn(desc, dims); + } + + @Override + public void visitLineNumber(final int line, final Label start) { + insertProbeIfAppropriate(); + super.visitLineNumber(line, start); + } + + private void insertProbeIfAppropriate() { + if (needsProbe(this.counter.currentInstructionCount())) { + insertProbe(); + this.probeCount++; + } + } + + private boolean needsProbe(int currentInstructionCount) { + for (final Block each : this.blocks) { + if (each.firstInstructionIs(currentInstructionCount - 1)) { + return true; + } + } + return false; + } + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/coverage/analysis/Block.java b/pitest/src/main/java/org/pitest/coverage/analysis/Block.java index d48bb34b9..bf6d01040 100644 --- a/pitest/src/main/java/org/pitest/coverage/analysis/Block.java +++ b/pitest/src/main/java/org/pitest/coverage/analysis/Block.java @@ -1,68 +1,68 @@ -package org.pitest.coverage.analysis; - -import java.util.Set; - -public final class Block { - private final int firstInstruction; - private final int lastInstruction; - private final Set lines; - - public Block(final int firstInstruction, final int lastInstruction, - final Set lines) { - this.firstInstruction = firstInstruction; - this.lastInstruction = lastInstruction; - this.lines = lines; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + this.firstInstruction; - result = (prime * result) + this.lastInstruction; - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Block other = (Block) obj; - if (this.firstInstruction != other.firstInstruction) { - return false; - } - if (this.lastInstruction != other.lastInstruction) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Block [firstInstruction=" + this.firstInstruction - + ", lastInstruction=" + this.lastInstruction + "]"; - } - - public boolean firstInstructionIs(final int ins) { - return this.firstInstruction == ins; - } - - public Set getLines() { - return this.lines; - } - - public int getFirstInstruction() { - return this.firstInstruction; - } - - public int getLastInstruction() { - return this.lastInstruction; - } -} +package org.pitest.coverage.analysis; + +import java.util.Set; + +public final class Block { + private final int firstInstruction; + private final int lastInstruction; + private final Set lines; + + public Block(final int firstInstruction, final int lastInstruction, + final Set lines) { + this.firstInstruction = firstInstruction; + this.lastInstruction = lastInstruction; + this.lines = lines; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + this.firstInstruction; + result = (prime * result) + this.lastInstruction; + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Block other = (Block) obj; + if (this.firstInstruction != other.firstInstruction) { + return false; + } + if (this.lastInstruction != other.lastInstruction) { + return false; + } + return true; + } + + @Override + public String toString() { + return "Block [firstInstruction=" + this.firstInstruction + + ", lastInstruction=" + this.lastInstruction + "]"; + } + + public boolean firstInstructionIs(final int ins) { + return this.firstInstruction == ins; + } + + public Set getLines() { + return this.lines; + } + + public int getFirstInstruction() { + return this.firstInstruction; + } + + public int getLastInstruction() { + return this.lastInstruction; + } +} diff --git a/pitest/src/main/java/org/pitest/coverage/analysis/ControlFlowAnalyser.java b/pitest/src/main/java/org/pitest/coverage/analysis/ControlFlowAnalyser.java index 382209f0a..2149ad354 100644 --- a/pitest/src/main/java/org/pitest/coverage/analysis/ControlFlowAnalyser.java +++ b/pitest/src/main/java/org/pitest/coverage/analysis/ControlFlowAnalyser.java @@ -1,139 +1,139 @@ -package org.pitest.coverage.analysis; - -import static org.objectweb.asm.Opcodes.ARETURN; -import static org.objectweb.asm.Opcodes.ATHROW; -import static org.objectweb.asm.Opcodes.DRETURN; -import static org.objectweb.asm.Opcodes.FRETURN; -import static org.objectweb.asm.Opcodes.IRETURN; -import static org.objectweb.asm.Opcodes.LRETURN; -import static org.objectweb.asm.Opcodes.RETURN; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.InsnList; -import org.objectweb.asm.tree.JumpInsnNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.LineNumberNode; -import org.objectweb.asm.tree.LookupSwitchInsnNode; -import org.objectweb.asm.tree.MethodNode; -import org.objectweb.asm.tree.TableSwitchInsnNode; -import org.objectweb.asm.tree.TryCatchBlockNode; - -public class ControlFlowAnalyser { - - private static final int LIKELY_NUMBER_OF_LINES_PER_BLOCK = 7; - - public static List analyze(final MethodNode mn) { - final List blocks = new ArrayList<>(mn.instructions.size()); - - final Set jumpTargets = findJumpTargets(mn.instructions); - - // not managed to construct bytecode to show need for this - // as try catch blocks usually have jumps at their boundaries anyway. - // so possibly useless, but here for now. Because fear. - addtryCatchBoundaries(mn, jumpTargets); - - Set blockLines = smallSet(); - int lastLine = Integer.MIN_VALUE; - - final int lastInstruction = mn.instructions.size() - 1; - - int blockStart = 0; - for (int i = 0; i != mn.instructions.size(); i++) { - - final AbstractInsnNode ins = mn.instructions.get(i); - - if (ins instanceof LineNumberNode) { - final LineNumberNode lnn = (LineNumberNode) ins; - blockLines.add(lnn.line); - lastLine = lnn.line; - } else if (jumpTargets.contains(ins) && (blockStart != i)) { - blocks.add(new Block(blockStart, i - 1, blockLines)); - blockStart = i; - blockLines = smallSet(); - } else if (endsBlock(ins)) { - blocks.add(new Block(blockStart, i, blockLines)); - blockStart = i + 1; - blockLines = smallSet(); - } else if ((lastLine != Integer.MIN_VALUE) && isInstruction(ins)) { - blockLines.add(lastLine); - } - } - - // this will not create a block if the last block contains only a single - // instruction. - // In the case of the hanging labels that eclipse compiler seems to generate - // this is desirable. - // Not clear if this will create problems in other scenarios - if (blockStart != lastInstruction) { - blocks.add(new Block(blockStart, lastInstruction, blockLines)); - } - - return blocks; - - } - - private static HashSet smallSet() { - return new HashSet<>(LIKELY_NUMBER_OF_LINES_PER_BLOCK); - } - - private static boolean isInstruction(final AbstractInsnNode ins) { - return !((ins instanceof LabelNode) || (ins instanceof FrameNode)); - } - - private static void addtryCatchBoundaries(final MethodNode mn, - final Set jumpTargets) { - for (final Object each : mn.tryCatchBlocks) { - final TryCatchBlockNode tcb = (TryCatchBlockNode) each; - jumpTargets.add(tcb.handler); - } - } - - private static boolean endsBlock(final AbstractInsnNode ins) { - return (ins instanceof JumpInsnNode) || isReturn(ins); - } - - private static boolean isReturn(final AbstractInsnNode ins) { - final int opcode = ins.getOpcode(); - switch (opcode) { - case RETURN: - case ARETURN: - case DRETURN: - case FRETURN: - case IRETURN: - case LRETURN: - case ATHROW: - return true; - } - - return false; - - } - - private static Set findJumpTargets(final InsnList instructions) { - final Set jumpTargets = new HashSet<>(); - final ListIterator it = instructions.iterator(); - while (it.hasNext()) { - final AbstractInsnNode o = it.next(); - if (o instanceof JumpInsnNode) { - jumpTargets.add(((JumpInsnNode) o).label); - } else if (o instanceof TableSwitchInsnNode) { - final TableSwitchInsnNode twn = (TableSwitchInsnNode) o; - jumpTargets.add(twn.dflt); - jumpTargets.addAll(twn.labels); - } else if (o instanceof LookupSwitchInsnNode) { - final LookupSwitchInsnNode lsn = (LookupSwitchInsnNode) o; - jumpTargets.add(lsn.dflt); - jumpTargets.addAll(lsn.labels); - } - } - return jumpTargets; - } - -} +package org.pitest.coverage.analysis; + +import static org.objectweb.asm.Opcodes.ARETURN; +import static org.objectweb.asm.Opcodes.ATHROW; +import static org.objectweb.asm.Opcodes.DRETURN; +import static org.objectweb.asm.Opcodes.FRETURN; +import static org.objectweb.asm.Opcodes.IRETURN; +import static org.objectweb.asm.Opcodes.LRETURN; +import static org.objectweb.asm.Opcodes.RETURN; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.LookupSwitchInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TableSwitchInsnNode; +import org.objectweb.asm.tree.TryCatchBlockNode; + +public class ControlFlowAnalyser { + + private static final int LIKELY_NUMBER_OF_LINES_PER_BLOCK = 7; + + public static List analyze(final MethodNode mn) { + final List blocks = new ArrayList<>(mn.instructions.size()); + + final Set jumpTargets = findJumpTargets(mn.instructions); + + // not managed to construct bytecode to show need for this + // as try catch blocks usually have jumps at their boundaries anyway. + // so possibly useless, but here for now. Because fear. + addtryCatchBoundaries(mn, jumpTargets); + + Set blockLines = smallSet(); + int lastLine = Integer.MIN_VALUE; + + final int lastInstruction = mn.instructions.size() - 1; + + int blockStart = 0; + for (int i = 0; i != mn.instructions.size(); i++) { + + final AbstractInsnNode ins = mn.instructions.get(i); + + if (ins instanceof LineNumberNode) { + final LineNumberNode lnn = (LineNumberNode) ins; + blockLines.add(lnn.line); + lastLine = lnn.line; + } else if (jumpTargets.contains(ins) && (blockStart != i)) { + blocks.add(new Block(blockStart, i - 1, blockLines)); + blockStart = i; + blockLines = smallSet(); + } else if (endsBlock(ins)) { + blocks.add(new Block(blockStart, i, blockLines)); + blockStart = i + 1; + blockLines = smallSet(); + } else if ((lastLine != Integer.MIN_VALUE) && isInstruction(ins)) { + blockLines.add(lastLine); + } + } + + // this will not create a block if the last block contains only a single + // instruction. + // In the case of the hanging labels that eclipse compiler seems to generate + // this is desirable. + // Not clear if this will create problems in other scenarios + if (blockStart != lastInstruction) { + blocks.add(new Block(blockStart, lastInstruction, blockLines)); + } + + return blocks; + + } + + private static HashSet smallSet() { + return new HashSet<>(LIKELY_NUMBER_OF_LINES_PER_BLOCK); + } + + private static boolean isInstruction(final AbstractInsnNode ins) { + return !((ins instanceof LabelNode) || (ins instanceof FrameNode)); + } + + private static void addtryCatchBoundaries(final MethodNode mn, + final Set jumpTargets) { + for (final Object each : mn.tryCatchBlocks) { + final TryCatchBlockNode tcb = (TryCatchBlockNode) each; + jumpTargets.add(tcb.handler); + } + } + + private static boolean endsBlock(final AbstractInsnNode ins) { + return (ins instanceof JumpInsnNode) || isReturn(ins); + } + + private static boolean isReturn(final AbstractInsnNode ins) { + final int opcode = ins.getOpcode(); + switch (opcode) { + case RETURN: + case ARETURN: + case DRETURN: + case FRETURN: + case IRETURN: + case LRETURN: + case ATHROW: + return true; + } + + return false; + + } + + private static Set findJumpTargets(final InsnList instructions) { + final Set jumpTargets = new HashSet<>(); + final ListIterator it = instructions.iterator(); + while (it.hasNext()) { + final AbstractInsnNode o = it.next(); + if (o instanceof JumpInsnNode) { + jumpTargets.add(((JumpInsnNode) o).label); + } else if (o instanceof TableSwitchInsnNode) { + final TableSwitchInsnNode twn = (TableSwitchInsnNode) o; + jumpTargets.add(twn.dflt); + jumpTargets.addAll(twn.labels); + } else if (o instanceof LookupSwitchInsnNode) { + final LookupSwitchInsnNode lsn = (LookupSwitchInsnNode) o; + jumpTargets.add(lsn.dflt); + jumpTargets.addAll(lsn.labels); + } + } + return jumpTargets; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/analysis/CoverageAnalyser.java b/pitest/src/main/java/org/pitest/coverage/analysis/CoverageAnalyser.java index 143d6b3e1..776f63c7e 100644 --- a/pitest/src/main/java/org/pitest/coverage/analysis/CoverageAnalyser.java +++ b/pitest/src/main/java/org/pitest/coverage/analysis/CoverageAnalyser.java @@ -1,81 +1,81 @@ -package org.pitest.coverage.analysis; - -import java.util.List; - -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.MethodNode; -import org.pitest.coverage.CoverageClassVisitor; -import org.pitest.mutationtest.engine.gregor.analysis.DefaultInstructionCounter; -import org.pitest.mutationtest.engine.gregor.analysis.InstructionTrackingMethodVisitor; - -import sun.pitest.CodeCoverageStore; - -/** - * Need to count the number of blocks in the method. Storing method as a tree - * enables a second scan by the instrumenting visitor - * - */ -public class CoverageAnalyser extends MethodNode { - - private static final int MAX_SUPPORTED_LOCAL_PROBES = 15; - - private final CoverageClassVisitor parent; - private final int classId; - private final MethodVisitor mv; - private final int probeOffset; - - public CoverageAnalyser(final CoverageClassVisitor parent, final int classId, - final int probeOffset, final MethodVisitor mv, final int access, - final String name, final String desc, final String signature, - final String[] exceptions) { - super(Opcodes.ASM6, access, name, desc, signature, exceptions); - this.mv = mv; - this.parent = parent; - this.classId = classId; - this.probeOffset = probeOffset; - } - - @Override - public void visitEnd() { - final List blocks = findRequriedProbeLocations(); - - this.parent.registerProbes(blocks.size()); - final int blockCount = blocks.size(); - CodeCoverageStore.registerMethod(this.classId, this.name, this.desc, - this.probeOffset, (this.probeOffset + blocks.size()) - 1); - - // according to the jvm spec - // "There must never be an uninitialized class instance in a local variable in code protected by an exception handler" - // the code to add finally blocks used by the local variable and array based - // probe approaches is not currently - // able to meet this guarantee for constructors. Although they appear to - // work, they are rejected by the - // java 7 verifier - hence fall back to a simple but slow approach. - final DefaultInstructionCounter counter = new DefaultInstructionCounter(); - - if ((blockCount == 1) || this.name.equals("")) { - accept(new InstructionTrackingMethodVisitor( - new SimpleBlockCoverageVisitor(blocks, counter, this.classId, - this.mv, this.access, this.name, this.desc, this.probeOffset), - counter)); - } else if ((blockCount <= MAX_SUPPORTED_LOCAL_PROBES) && (blockCount >= 1)) { - accept(new InstructionTrackingMethodVisitor( - new LocalVariableCoverageMethodVisitor(blocks, counter, this.classId, - this.mv, this.access, this.name, this.desc, this.probeOffset), - counter)); - } else { - // for now fall back to the naive implementation - could instead use array - // passing version - accept(new InstructionTrackingMethodVisitor( - new ArrayProbeCoverageMethodVisitor(blocks, counter, this.classId, - this.mv, this.access, this.name, this.desc, this.probeOffset), - counter)); - } - - } - - private List findRequriedProbeLocations() { - return ControlFlowAnalyser.analyze(this); - } -} +package org.pitest.coverage.analysis; + +import java.util.List; + +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.MethodNode; +import org.pitest.coverage.CoverageClassVisitor; +import org.pitest.mutationtest.engine.gregor.analysis.DefaultInstructionCounter; +import org.pitest.mutationtest.engine.gregor.analysis.InstructionTrackingMethodVisitor; + +import sun.pitest.CodeCoverageStore; + +/** + * Need to count the number of blocks in the method. Storing method as a tree + * enables a second scan by the instrumenting visitor + * + */ +public class CoverageAnalyser extends MethodNode { + + private static final int MAX_SUPPORTED_LOCAL_PROBES = 15; + + private final CoverageClassVisitor parent; + private final int classId; + private final MethodVisitor mv; + private final int probeOffset; + + public CoverageAnalyser(final CoverageClassVisitor parent, final int classId, + final int probeOffset, final MethodVisitor mv, final int access, + final String name, final String desc, final String signature, + final String[] exceptions) { + super(Opcodes.ASM6, access, name, desc, signature, exceptions); + this.mv = mv; + this.parent = parent; + this.classId = classId; + this.probeOffset = probeOffset; + } + + @Override + public void visitEnd() { + final List blocks = findRequriedProbeLocations(); + + this.parent.registerProbes(blocks.size()); + final int blockCount = blocks.size(); + CodeCoverageStore.registerMethod(this.classId, this.name, this.desc, + this.probeOffset, (this.probeOffset + blocks.size()) - 1); + + // according to the jvm spec + // "There must never be an uninitialized class instance in a local variable in code protected by an exception handler" + // the code to add finally blocks used by the local variable and array based + // probe approaches is not currently + // able to meet this guarantee for constructors. Although they appear to + // work, they are rejected by the + // java 7 verifier - hence fall back to a simple but slow approach. + final DefaultInstructionCounter counter = new DefaultInstructionCounter(); + + if ((blockCount == 1) || this.name.equals("")) { + accept(new InstructionTrackingMethodVisitor( + new SimpleBlockCoverageVisitor(blocks, counter, this.classId, + this.mv, this.access, this.name, this.desc, this.probeOffset), + counter)); + } else if ((blockCount <= MAX_SUPPORTED_LOCAL_PROBES) && (blockCount >= 1)) { + accept(new InstructionTrackingMethodVisitor( + new LocalVariableCoverageMethodVisitor(blocks, counter, this.classId, + this.mv, this.access, this.name, this.desc, this.probeOffset), + counter)); + } else { + // for now fall back to the naive implementation - could instead use array + // passing version + accept(new InstructionTrackingMethodVisitor( + new ArrayProbeCoverageMethodVisitor(blocks, counter, this.classId, + this.mv, this.access, this.name, this.desc, this.probeOffset), + counter)); + } + + } + + private List findRequriedProbeLocations() { + return ControlFlowAnalyser.analyze(this); + } +} diff --git a/pitest/src/main/java/org/pitest/coverage/analysis/LineMapper.java b/pitest/src/main/java/org/pitest/coverage/analysis/LineMapper.java index 817a30ece..d0519d62a 100644 --- a/pitest/src/main/java/org/pitest/coverage/analysis/LineMapper.java +++ b/pitest/src/main/java/org/pitest/coverage/analysis/LineMapper.java @@ -1,56 +1,56 @@ -package org.pitest.coverage.analysis; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.BlockLocation; -import org.pitest.coverage.LineMap; -import java.util.Optional; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; - -public class LineMapper implements LineMap { - - private final CodeSource source; - - public LineMapper(final CodeSource source) { - this.source = source; - } - - @Override - public Map> mapLines(final ClassName clazz) { - - final Map> map = new HashMap<>(); - - final Optional maybeBytes = this.source.fetchClassBytes(clazz); - // classes generated at runtime eg by mocking frameworks - // will be instrumented but not available on the classpath - if (maybeBytes.isPresent()) { - final ClassReader cr = new ClassReader(maybeBytes.get()); - final ClassNode classNode = new ClassNode(); - - cr.accept(classNode, ClassReader.EXPAND_FRAMES); - for (final Object m : classNode.methods) { - final MethodNode mn = (MethodNode) m; - final Location l = Location.location(clazz, - MethodName.fromString(mn.name), mn.desc); - final List blocks = ControlFlowAnalyser.analyze(mn); - for (int i = 0; i != blocks.size(); i++) { - final BlockLocation bl = new BlockLocation(l, i); - map.put(bl, blocks.get(i).getLines()); - } - - } - } - - return map; - } - -} +package org.pitest.coverage.analysis; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.BlockLocation; +import org.pitest.coverage.LineMap; +import java.util.Optional; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; + +public class LineMapper implements LineMap { + + private final CodeSource source; + + public LineMapper(final CodeSource source) { + this.source = source; + } + + @Override + public Map> mapLines(final ClassName clazz) { + + final Map> map = new HashMap<>(); + + final Optional maybeBytes = this.source.fetchClassBytes(clazz); + // classes generated at runtime eg by mocking frameworks + // will be instrumented but not available on the classpath + if (maybeBytes.isPresent()) { + final ClassReader cr = new ClassReader(maybeBytes.get()); + final ClassNode classNode = new ClassNode(); + + cr.accept(classNode, ClassReader.EXPAND_FRAMES); + for (final Object m : classNode.methods) { + final MethodNode mn = (MethodNode) m; + final Location l = Location.location(clazz, + MethodName.fromString(mn.name), mn.desc); + final List blocks = ControlFlowAnalyser.analyze(mn); + for (int i = 0; i != blocks.size(); i++) { + final BlockLocation bl = new BlockLocation(l, i); + map.put(bl, blocks.get(i).getLines()); + } + + } + } + + return map; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/analysis/LocalVariableCoverageMethodVisitor.java b/pitest/src/main/java/org/pitest/coverage/analysis/LocalVariableCoverageMethodVisitor.java index 171d3a477..b909c6855 100644 --- a/pitest/src/main/java/org/pitest/coverage/analysis/LocalVariableCoverageMethodVisitor.java +++ b/pitest/src/main/java/org/pitest/coverage/analysis/LocalVariableCoverageMethodVisitor.java @@ -1,65 +1,65 @@ -package org.pitest.coverage.analysis; - -import java.util.List; - -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.pitest.mutationtest.engine.gregor.analysis.InstructionCounter; - -import sun.pitest.CodeCoverageStore; - -/** - * Uses local variables as block probes within methods. - * - * Inserts a finally block the method, posting the probes hits to the code - * coverage store via specialised methods for each number of probes. - * - * The range of methods this approach can be applied to is limited by the - * maximum airty of the overloaded methods on the coverage store. - */ -class LocalVariableCoverageMethodVisitor extends AbstractCoverageStrategy { - - private int[] locals; - - LocalVariableCoverageMethodVisitor(final List blocks, - final InstructionCounter counter, final int classId, - final MethodVisitor writer, final int access, final String name, - final String desc, final int probeOffset) { - super(blocks, counter, classId, writer, access, name, desc, probeOffset); - } - - @Override - void prepare() { - this.locals = new int[this.blocks.size()]; - for (int i = 0; i != this.blocks.size(); i++) { - this.locals[i] = newLocal(Type.getType("Z")); - pushConstant(0); - this.mv.visitVarInsn(ISTORE, this.locals[i]); - } - } - - @Override - void insertProbe() { - pushConstant(1); - this.mv.visitVarInsn(ISTORE, this.locals[this.probeCount]); - } - - @Override - protected void generateProbeReportCode() { - - pushConstant(this.classId); - pushConstant(this.probeOffset); - - for (final int i : this.locals) { - this.mv.visitVarInsn(ILOAD, i); - } - - this.methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, - CodeCoverageStore.CLASS_NAME, CodeCoverageStore.PROBE_METHOD_NAME, - "(II" - + String.format(String.format("%%0%dd", this.blocks.size()), 0) - .replace("0", "Z") + ")V", false); - } - -} +package org.pitest.coverage.analysis; + +import java.util.List; + +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.pitest.mutationtest.engine.gregor.analysis.InstructionCounter; + +import sun.pitest.CodeCoverageStore; + +/** + * Uses local variables as block probes within methods. + * + * Inserts a finally block the method, posting the probes hits to the code + * coverage store via specialised methods for each number of probes. + * + * The range of methods this approach can be applied to is limited by the + * maximum airty of the overloaded methods on the coverage store. + */ +class LocalVariableCoverageMethodVisitor extends AbstractCoverageStrategy { + + private int[] locals; + + LocalVariableCoverageMethodVisitor(final List blocks, + final InstructionCounter counter, final int classId, + final MethodVisitor writer, final int access, final String name, + final String desc, final int probeOffset) { + super(blocks, counter, classId, writer, access, name, desc, probeOffset); + } + + @Override + void prepare() { + this.locals = new int[this.blocks.size()]; + for (int i = 0; i != this.blocks.size(); i++) { + this.locals[i] = newLocal(Type.getType("Z")); + pushConstant(0); + this.mv.visitVarInsn(ISTORE, this.locals[i]); + } + } + + @Override + void insertProbe() { + pushConstant(1); + this.mv.visitVarInsn(ISTORE, this.locals[this.probeCount]); + } + + @Override + protected void generateProbeReportCode() { + + pushConstant(this.classId); + pushConstant(this.probeOffset); + + for (final int i : this.locals) { + this.mv.visitVarInsn(ILOAD, i); + } + + this.methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, + CodeCoverageStore.CLASS_NAME, CodeCoverageStore.PROBE_METHOD_NAME, + "(II" + + String.format(String.format("%%0%dd", this.blocks.size()), 0) + .replace("0", "Z") + ")V", false); + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/analysis/SimpleBlockCoverageVisitor.java b/pitest/src/main/java/org/pitest/coverage/analysis/SimpleBlockCoverageVisitor.java index 3624b0d8d..b65a25072 100644 --- a/pitest/src/main/java/org/pitest/coverage/analysis/SimpleBlockCoverageVisitor.java +++ b/pitest/src/main/java/org/pitest/coverage/analysis/SimpleBlockCoverageVisitor.java @@ -1,171 +1,171 @@ -package org.pitest.coverage.analysis; - -import java.util.List; - -import org.objectweb.asm.Handle; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.mutationtest.engine.gregor.analysis.InstructionCounter; - -import sun.pitest.CodeCoverageStore; - -/** - * Instruments via a method call at each line. - * - * This simplistic approach is generally slow, but does not require finally - * blocks that are difficult to generate correctly for constructors. - * - * This simple approach should however provide better performance for single - * line methods. - */ -public class SimpleBlockCoverageVisitor extends MethodVisitor { - private final MethodVisitor methodVisitor; - private final int classId; - - private final int probeOffset; - - private final InstructionCounter counter; - private final List blocks; - - private int probeCount = 0; - - public SimpleBlockCoverageVisitor(List blocks, - InstructionCounter counter, final int classId, - final MethodVisitor writer, final int access, final String name, - final String desc, final int probeOffset) { - super(Opcodes.ASM6, writer); - - this.counter = counter; - this.methodVisitor = writer; - this.classId = classId; - this.blocks = blocks; - - this.probeOffset = probeOffset; - } - - @Override - public void visitFrame(final int type, final int nLocal, - final Object[] local, final int nStack, final Object[] stack) { - insertProbeIfAppropriate(); - super.visitFrame(type, nLocal, local, nStack, stack); - } - - @Override - public void visitInsn(final int opcode) { - insertProbeIfAppropriate(); - super.visitInsn(opcode); - } - - @Override - public void visitIntInsn(final int opcode, final int operand) { - insertProbeIfAppropriate(); - super.visitIntInsn(opcode, operand); - } - - @Override - public void visitVarInsn(final int opcode, final int var) { - insertProbeIfAppropriate(); - super.visitVarInsn(opcode, var); - } - - @Override - public void visitTypeInsn(final int opcode, final String type) { - insertProbeIfAppropriate(); - super.visitTypeInsn(opcode, type); - } - - @Override - public void visitFieldInsn(final int opcode, final String owner, - final String name, final String desc) { - insertProbeIfAppropriate(); - super.visitFieldInsn(opcode, owner, name, desc); - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, - final String name, final String desc, boolean itf) { - insertProbeIfAppropriate(); - super.visitMethodInsn(opcode, owner, name, desc, itf); - } - - @Override - public void visitInvokeDynamicInsn(final String name, final String desc, - final Handle bsm, final Object... bsmArgs) { - insertProbeIfAppropriate(); - super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); - } - - @Override - public void visitJumpInsn(final int opcode, final Label label) { - insertProbeIfAppropriate(); - super.visitJumpInsn(opcode, label); - } - - @Override - public void visitLabel(final Label label) { - super.visitLabel(label); - // note - probe goes after the label - insertProbeIfAppropriate(); - } - - @Override - public void visitLdcInsn(final Object cst) { - insertProbeIfAppropriate(); - super.visitLdcInsn(cst); - } - - @Override - public void visitIincInsn(final int var, final int increment) { - insertProbeIfAppropriate(); - super.visitIincInsn(var, increment); - } - - @Override - public void visitTableSwitchInsn(final int min, final int max, - final Label dflt, final Label... labels) { - insertProbeIfAppropriate(); - super.visitTableSwitchInsn(min, max, dflt, labels); - } - - @Override - public void visitLookupSwitchInsn(final Label dflt, final int[] keys, - final Label[] labels) { - insertProbeIfAppropriate(); - super.visitLookupSwitchInsn(dflt, keys, labels); - } - - @Override - public void visitMultiANewArrayInsn(final String desc, final int dims) { - insertProbeIfAppropriate(); - super.visitMultiANewArrayInsn(desc, dims); - } - - @Override - public void visitLineNumber(final int line, final Label start) { - insertProbeIfAppropriate(); - super.visitLineNumber(line, start); - } - - private void insertProbeIfAppropriate() { - if (needsProbe(this.counter.currentInstructionCount())) { - this.methodVisitor.visitLdcInsn(this.classId); - this.methodVisitor.visitLdcInsn(this.probeCount + this.probeOffset); - - this.methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, - CodeCoverageStore.CLASS_NAME, "visitSingleProbe", "(II)V", false); - - this.probeCount++; - } - } - - private boolean needsProbe(int currentInstructionCount) { - for (final Block each : this.blocks) { - if (each.firstInstructionIs(currentInstructionCount - 1)) { - return true; - } - } - return false; - } - -} +package org.pitest.coverage.analysis; + +import java.util.List; + +import org.objectweb.asm.Handle; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.mutationtest.engine.gregor.analysis.InstructionCounter; + +import sun.pitest.CodeCoverageStore; + +/** + * Instruments via a method call at each line. + * + * This simplistic approach is generally slow, but does not require finally + * blocks that are difficult to generate correctly for constructors. + * + * This simple approach should however provide better performance for single + * line methods. + */ +public class SimpleBlockCoverageVisitor extends MethodVisitor { + private final MethodVisitor methodVisitor; + private final int classId; + + private final int probeOffset; + + private final InstructionCounter counter; + private final List blocks; + + private int probeCount = 0; + + public SimpleBlockCoverageVisitor(List blocks, + InstructionCounter counter, final int classId, + final MethodVisitor writer, final int access, final String name, + final String desc, final int probeOffset) { + super(Opcodes.ASM6, writer); + + this.counter = counter; + this.methodVisitor = writer; + this.classId = classId; + this.blocks = blocks; + + this.probeOffset = probeOffset; + } + + @Override + public void visitFrame(final int type, final int nLocal, + final Object[] local, final int nStack, final Object[] stack) { + insertProbeIfAppropriate(); + super.visitFrame(type, nLocal, local, nStack, stack); + } + + @Override + public void visitInsn(final int opcode) { + insertProbeIfAppropriate(); + super.visitInsn(opcode); + } + + @Override + public void visitIntInsn(final int opcode, final int operand) { + insertProbeIfAppropriate(); + super.visitIntInsn(opcode, operand); + } + + @Override + public void visitVarInsn(final int opcode, final int var) { + insertProbeIfAppropriate(); + super.visitVarInsn(opcode, var); + } + + @Override + public void visitTypeInsn(final int opcode, final String type) { + insertProbeIfAppropriate(); + super.visitTypeInsn(opcode, type); + } + + @Override + public void visitFieldInsn(final int opcode, final String owner, + final String name, final String desc) { + insertProbeIfAppropriate(); + super.visitFieldInsn(opcode, owner, name, desc); + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, + final String name, final String desc, boolean itf) { + insertProbeIfAppropriate(); + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + + @Override + public void visitInvokeDynamicInsn(final String name, final String desc, + final Handle bsm, final Object... bsmArgs) { + insertProbeIfAppropriate(); + super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); + } + + @Override + public void visitJumpInsn(final int opcode, final Label label) { + insertProbeIfAppropriate(); + super.visitJumpInsn(opcode, label); + } + + @Override + public void visitLabel(final Label label) { + super.visitLabel(label); + // note - probe goes after the label + insertProbeIfAppropriate(); + } + + @Override + public void visitLdcInsn(final Object cst) { + insertProbeIfAppropriate(); + super.visitLdcInsn(cst); + } + + @Override + public void visitIincInsn(final int var, final int increment) { + insertProbeIfAppropriate(); + super.visitIincInsn(var, increment); + } + + @Override + public void visitTableSwitchInsn(final int min, final int max, + final Label dflt, final Label... labels) { + insertProbeIfAppropriate(); + super.visitTableSwitchInsn(min, max, dflt, labels); + } + + @Override + public void visitLookupSwitchInsn(final Label dflt, final int[] keys, + final Label[] labels) { + insertProbeIfAppropriate(); + super.visitLookupSwitchInsn(dflt, keys, labels); + } + + @Override + public void visitMultiANewArrayInsn(final String desc, final int dims) { + insertProbeIfAppropriate(); + super.visitMultiANewArrayInsn(desc, dims); + } + + @Override + public void visitLineNumber(final int line, final Label start) { + insertProbeIfAppropriate(); + super.visitLineNumber(line, start); + } + + private void insertProbeIfAppropriate() { + if (needsProbe(this.counter.currentInstructionCount())) { + this.methodVisitor.visitLdcInsn(this.classId); + this.methodVisitor.visitLdcInsn(this.probeCount + this.probeOffset); + + this.methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, + CodeCoverageStore.CLASS_NAME, "visitSingleProbe", "(II)V", false); + + this.probeCount++; + } + } + + private boolean needsProbe(int currentInstructionCount) { + for (final Block each : this.blocks) { + if (each.firstInstructionIs(currentInstructionCount - 1)) { + return true; + } + } + return false; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/execute/CoverageDecorator.java b/pitest/src/main/java/org/pitest/coverage/execute/CoverageDecorator.java index 5240e72e5..fe03920a6 100644 --- a/pitest/src/main/java/org/pitest/coverage/execute/CoverageDecorator.java +++ b/pitest/src/main/java/org/pitest/coverage/execute/CoverageDecorator.java @@ -1,66 +1,66 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.execute; - -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadMXBean; -import java.util.logging.Logger; - -import org.pitest.coverage.CoverageReceiver; -import org.pitest.extension.common.TestUnitDecorator; -import org.pitest.testapi.ResultCollector; -import org.pitest.testapi.TestUnit; -import org.pitest.testapi.execute.ExitingResultCollector; -import org.pitest.util.Log; - -public class CoverageDecorator extends TestUnitDecorator { - - private static final Logger LOG = Log.getLogger(); - - private final CoverageReceiver invokeQueue; - private final ThreadMXBean threads = ManagementFactory.getThreadMXBean(); - - protected CoverageDecorator(final CoverageReceiver queue, final TestUnit child) { - super(child); - this.invokeQueue = queue; - } - - @Override - public void execute(final ResultCollector rc) { - LOG.fine("Gathering coverage for test " + child().getDescription()); - this.invokeQueue.newTest(); - - final int threadsBeforeTest = this.threads.getThreadCount(); - - final long t0 = System.currentTimeMillis(); - final ExitingResultCollector wrappedCollector = new ExitingResultCollector( - rc); - this.child().execute(wrappedCollector); - - final int executionTime = (int) (System.currentTimeMillis() - t0); - - final int threadsAfterTest = this.threads.getThreadCount(); - if (threadsAfterTest > threadsBeforeTest) { - LOG.warning("More threads at end of test (" + threadsAfterTest + ") " - + child().getDescription().getName() + " than start. (" - + threadsBeforeTest + ")"); - } - - this.invokeQueue.recordTestOutcome(child().getDescription(), - !wrappedCollector.shouldExit(), executionTime); - - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.execute; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadMXBean; +import java.util.logging.Logger; + +import org.pitest.coverage.CoverageReceiver; +import org.pitest.extension.common.TestUnitDecorator; +import org.pitest.testapi.ResultCollector; +import org.pitest.testapi.TestUnit; +import org.pitest.testapi.execute.ExitingResultCollector; +import org.pitest.util.Log; + +public class CoverageDecorator extends TestUnitDecorator { + + private static final Logger LOG = Log.getLogger(); + + private final CoverageReceiver invokeQueue; + private final ThreadMXBean threads = ManagementFactory.getThreadMXBean(); + + protected CoverageDecorator(final CoverageReceiver queue, final TestUnit child) { + super(child); + this.invokeQueue = queue; + } + + @Override + public void execute(final ResultCollector rc) { + LOG.fine("Gathering coverage for test " + child().getDescription()); + this.invokeQueue.newTest(); + + final int threadsBeforeTest = this.threads.getThreadCount(); + + final long t0 = System.currentTimeMillis(); + final ExitingResultCollector wrappedCollector = new ExitingResultCollector( + rc); + this.child().execute(wrappedCollector); + + final int executionTime = (int) (System.currentTimeMillis() - t0); + + final int threadsAfterTest = this.threads.getThreadCount(); + if (threadsAfterTest > threadsBeforeTest) { + LOG.warning("More threads at end of test (" + threadsAfterTest + ") " + + child().getDescription().getName() + " than start. (" + + threadsBeforeTest + ")"); + } + + this.invokeQueue.recordTestOutcome(child().getDescription(), + !wrappedCollector.shouldExit(), executionTime); + + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/execute/CoverageMinion.java b/pitest/src/main/java/org/pitest/coverage/execute/CoverageMinion.java index bcadbb929..ea80b00e4 100644 --- a/pitest/src/main/java/org/pitest/coverage/execute/CoverageMinion.java +++ b/pitest/src/main/java/org/pitest/coverage/execute/CoverageMinion.java @@ -1,190 +1,190 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.execute; - -import static org.pitest.util.Unchecked.translateCheckedException; - -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.net.Socket; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.function.Predicate; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; - -import org.pitest.boot.HotSwapAgent; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassPathByteArraySource; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.coverage.CoverageTransformer; -import org.pitest.dependency.DependencyExtractor; -import org.pitest.functional.prelude.Prelude; -import org.pitest.help.PitHelpError; -import org.pitest.mutationtest.config.ClientPluginServices; -import org.pitest.mutationtest.config.MinionSettings; -import org.pitest.mutationtest.mocksupport.BendJavassistToMyWillTransformer; -import org.pitest.mutationtest.mocksupport.JavassistInputStreamInterceptorAdapater; -import org.pitest.testapi.Configuration; -import org.pitest.testapi.TestUnit; -import org.pitest.testapi.execute.FindTestUnits; -import org.pitest.util.ExitCode; -import org.pitest.util.Glob; -import org.pitest.util.IsolationUtils; -import org.pitest.util.Log; -import org.pitest.util.SafeDataInputStream; - -import sun.pitest.CodeCoverageStore; - -public class CoverageMinion { - - private static final Logger LOG = Log.getLogger(); - - public static void main(final String[] args) { - - enablePowerMockSupport(); - - ExitCode exitCode = ExitCode.OK; - Socket s = null; - CoveragePipe invokeQueue = null; - try { - - final int port = Integer.parseInt(args[0]); - s = new Socket("localhost", port); - - final SafeDataInputStream dis = new SafeDataInputStream( - s.getInputStream()); - - final CoverageOptions paramsFromParent = dis.read(CoverageOptions.class); - - Log.setVerbose(paramsFromParent.isVerbose()); - - invokeQueue = new CoveragePipe(new BufferedOutputStream( - s.getOutputStream())); - - CodeCoverageStore.init(invokeQueue); - - HotSwapAgent.addTransformer(new CoverageTransformer( - convertToJVMClassFilter(paramsFromParent.getFilter()))); - - final List tus = getTestsFromParent(dis, paramsFromParent); - - LOG.info(tus.size() + " tests received"); - - final CoverageWorker worker = new CoverageWorker(invokeQueue, tus); - - worker.run(); - - } catch (final PitHelpError phe) { - LOG.log(Level.SEVERE, phe.getMessage()); - exitCode = ExitCode.JUNIT_ISSUE; - } catch (final Throwable ex) { - ex.printStackTrace(System.out); - LOG.log(Level.SEVERE, "Error calculating coverage. Process will exit.", - ex); - exitCode = ExitCode.UNKNOWN_ERROR; - } finally { - if (invokeQueue != null) { - invokeQueue.end(exitCode); - } - try { - if (s != null) { - s.close(); - } - } catch (final IOException e) { - throw translateCheckedException(e); - } - } - - System.exit(exitCode.getCode()); - - } - - private static void enablePowerMockSupport() { - // Bwahahahahahahaha - HotSwapAgent.addTransformer(new BendJavassistToMyWillTransformer(Prelude - .or(new Glob("javassist/*")), - JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistCoverageInterceptor.class))); - } - - private static Predicate convertToJVMClassFilter( - final Predicate child) { - return a -> child.test(a.replace("/", ".")); - } - - private static List getTestsFromParent( - final SafeDataInputStream dis, final CoverageOptions paramsFromParent) - throws IOException { - final List classes = receiveTestClassesFromParent(dis); - Collections.sort(classes); // ensure classes loaded in a consistent order - - final Configuration testPlugin = createTestPlugin(paramsFromParent); - verifyEnvironment(testPlugin); - - final List tus = discoverTests(testPlugin, classes); - - final DependencyFilter filter = new DependencyFilter( - new DependencyExtractor(new ClassPathByteArraySource(), - paramsFromParent.getDependencyAnalysisMaxDistance()), - paramsFromParent.getFilter()); - final List filteredTus = filter - .filterTestsByDependencyAnalysis(tus); - - LOG.info("Dependency analysis reduced number of potential tests by " - + (tus.size() - filteredTus.size())); - return filteredTus; - - } - - private static List discoverTests(final Configuration testPlugin, - final List classes) { - final FindTestUnits finder = new FindTestUnits(testPlugin); - final List tus = finder - .findTestUnitsForAllSuppliedClasses(classes.stream().flatMap(ClassName.nameToClass()).collect(Collectors.toList())); - LOG.info("Found " + tus.size() + " tests"); - return tus; - } - - private static Configuration createTestPlugin( - final CoverageOptions paramsFromParent) { - final ClientPluginServices plugins = new ClientPluginServices(IsolationUtils.getContextClassLoader()); - final MinionSettings factory = new MinionSettings(plugins); - final Configuration testPlugin = factory.getTestFrameworkPlugin(paramsFromParent.getPitConfig(), ClassloaderByteArraySource.fromContext()); - return testPlugin; - } - - private static void verifyEnvironment(Configuration config) { - LOG.info("Checking environment"); - if (config.verifyEnvironment().isPresent()) { - throw config.verifyEnvironment().get(); - } - } - - private static List receiveTestClassesFromParent( - final SafeDataInputStream dis) { - final int count = dis.readInt(); - LOG.fine("Expecting " + count + " tests classes from parent"); - final List classes = new ArrayList<>(count); - for (int i = 0; i != count; i++) { - classes.add(ClassName.fromString(dis.readString())); - } - LOG.fine("Tests classes received"); - - return classes; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.execute; + +import static org.pitest.util.Unchecked.translateCheckedException; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +import org.pitest.boot.HotSwapAgent; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassPathByteArraySource; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.coverage.CoverageTransformer; +import org.pitest.dependency.DependencyExtractor; +import org.pitest.functional.prelude.Prelude; +import org.pitest.help.PitHelpError; +import org.pitest.mutationtest.config.ClientPluginServices; +import org.pitest.mutationtest.config.MinionSettings; +import org.pitest.mutationtest.mocksupport.BendJavassistToMyWillTransformer; +import org.pitest.mutationtest.mocksupport.JavassistInputStreamInterceptorAdapater; +import org.pitest.testapi.Configuration; +import org.pitest.testapi.TestUnit; +import org.pitest.testapi.execute.FindTestUnits; +import org.pitest.util.ExitCode; +import org.pitest.util.Glob; +import org.pitest.util.IsolationUtils; +import org.pitest.util.Log; +import org.pitest.util.SafeDataInputStream; + +import sun.pitest.CodeCoverageStore; + +public class CoverageMinion { + + private static final Logger LOG = Log.getLogger(); + + public static void main(final String[] args) { + + enablePowerMockSupport(); + + ExitCode exitCode = ExitCode.OK; + Socket s = null; + CoveragePipe invokeQueue = null; + try { + + final int port = Integer.parseInt(args[0]); + s = new Socket("localhost", port); + + final SafeDataInputStream dis = new SafeDataInputStream( + s.getInputStream()); + + final CoverageOptions paramsFromParent = dis.read(CoverageOptions.class); + + Log.setVerbose(paramsFromParent.isVerbose()); + + invokeQueue = new CoveragePipe(new BufferedOutputStream( + s.getOutputStream())); + + CodeCoverageStore.init(invokeQueue); + + HotSwapAgent.addTransformer(new CoverageTransformer( + convertToJVMClassFilter(paramsFromParent.getFilter()))); + + final List tus = getTestsFromParent(dis, paramsFromParent); + + LOG.info(tus.size() + " tests received"); + + final CoverageWorker worker = new CoverageWorker(invokeQueue, tus); + + worker.run(); + + } catch (final PitHelpError phe) { + LOG.log(Level.SEVERE, phe.getMessage()); + exitCode = ExitCode.JUNIT_ISSUE; + } catch (final Throwable ex) { + ex.printStackTrace(System.out); + LOG.log(Level.SEVERE, "Error calculating coverage. Process will exit.", + ex); + exitCode = ExitCode.UNKNOWN_ERROR; + } finally { + if (invokeQueue != null) { + invokeQueue.end(exitCode); + } + try { + if (s != null) { + s.close(); + } + } catch (final IOException e) { + throw translateCheckedException(e); + } + } + + System.exit(exitCode.getCode()); + + } + + private static void enablePowerMockSupport() { + // Bwahahahahahahaha + HotSwapAgent.addTransformer(new BendJavassistToMyWillTransformer(Prelude + .or(new Glob("javassist/*")), + JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistCoverageInterceptor.class))); + } + + private static Predicate convertToJVMClassFilter( + final Predicate child) { + return a -> child.test(a.replace("/", ".")); + } + + private static List getTestsFromParent( + final SafeDataInputStream dis, final CoverageOptions paramsFromParent) + throws IOException { + final List classes = receiveTestClassesFromParent(dis); + Collections.sort(classes); // ensure classes loaded in a consistent order + + final Configuration testPlugin = createTestPlugin(paramsFromParent); + verifyEnvironment(testPlugin); + + final List tus = discoverTests(testPlugin, classes); + + final DependencyFilter filter = new DependencyFilter( + new DependencyExtractor(new ClassPathByteArraySource(), + paramsFromParent.getDependencyAnalysisMaxDistance()), + paramsFromParent.getFilter()); + final List filteredTus = filter + .filterTestsByDependencyAnalysis(tus); + + LOG.info("Dependency analysis reduced number of potential tests by " + + (tus.size() - filteredTus.size())); + return filteredTus; + + } + + private static List discoverTests(final Configuration testPlugin, + final List classes) { + final FindTestUnits finder = new FindTestUnits(testPlugin); + final List tus = finder + .findTestUnitsForAllSuppliedClasses(classes.stream().flatMap(ClassName.nameToClass()).collect(Collectors.toList())); + LOG.info("Found " + tus.size() + " tests"); + return tus; + } + + private static Configuration createTestPlugin( + final CoverageOptions paramsFromParent) { + final ClientPluginServices plugins = new ClientPluginServices(IsolationUtils.getContextClassLoader()); + final MinionSettings factory = new MinionSettings(plugins); + final Configuration testPlugin = factory.getTestFrameworkPlugin(paramsFromParent.getPitConfig(), ClassloaderByteArraySource.fromContext()); + return testPlugin; + } + + private static void verifyEnvironment(Configuration config) { + LOG.info("Checking environment"); + if (config.verifyEnvironment().isPresent()) { + throw config.verifyEnvironment().get(); + } + } + + private static List receiveTestClassesFromParent( + final SafeDataInputStream dis) { + final int count = dis.readInt(); + LOG.fine("Expecting " + count + " tests classes from parent"); + final List classes = new ArrayList<>(count); + for (int i = 0; i != count; i++) { + classes.add(ClassName.fromString(dis.readString())); + } + LOG.fine("Tests classes received"); + + return classes; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/execute/CoverageOptions.java b/pitest/src/main/java/org/pitest/coverage/execute/CoverageOptions.java index 797aecdcc..c24f17952 100644 --- a/pitest/src/main/java/org/pitest/coverage/execute/CoverageOptions.java +++ b/pitest/src/main/java/org/pitest/coverage/execute/CoverageOptions.java @@ -1,80 +1,80 @@ -package org.pitest.coverage.execute; - -import java.io.Serializable; -import java.util.Collection; - -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -import java.util.function.Predicate; - -import org.pitest.functional.prelude.Prelude; -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.util.Glob; -import org.pitest.util.Preconditions; - -public class CoverageOptions implements Serializable { - - private static final long serialVersionUID = 1L; - - private final Collection include; - private final Collection exclude; - private final boolean verbose; - private final TestPluginArguments pitConfig; - private final int maxDependencyDistance; - - public CoverageOptions(final Collection include, final Collection exclude, - final TestPluginArguments pitConfig, final boolean verbose, - final int maxDependencyDistance) { - Preconditions.checkNotNull(pitConfig); - this.include = include; - this.exclude = exclude; - this.verbose = verbose; - this.pitConfig = pitConfig; - this.maxDependencyDistance = maxDependencyDistance; - } - - public Predicate getFilter() { - return Prelude.and(Prelude.or(Glob.toGlobPredicates(this.include)), - Prelude.not(Prelude.or(Glob.toGlobPredicates(this.exclude))), - Prelude.not(commonClasses())); - } - - public boolean isVerbose() { - return this.verbose; - } - - public TestPluginArguments getPitConfig() { - return this.pitConfig; - } - - public int getDependencyAnalysisMaxDistance() { - return this.maxDependencyDistance; - } - - private static Predicate commonClasses() { - return Prelude.or( - glob("java/*"), - glob("sun/*"), - glob("org/pitest/coverage/*"), - glob("org/pitest/reloc/*"), - glob("org/pitest/boot/*")); - } - - private static Glob glob(String match) { - return new Glob(match); - } - -} +package org.pitest.coverage.execute; + +import java.io.Serializable; +import java.util.Collection; + +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +import java.util.function.Predicate; + +import org.pitest.functional.prelude.Prelude; +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.util.Glob; +import org.pitest.util.Preconditions; + +public class CoverageOptions implements Serializable { + + private static final long serialVersionUID = 1L; + + private final Collection include; + private final Collection exclude; + private final boolean verbose; + private final TestPluginArguments pitConfig; + private final int maxDependencyDistance; + + public CoverageOptions(final Collection include, final Collection exclude, + final TestPluginArguments pitConfig, final boolean verbose, + final int maxDependencyDistance) { + Preconditions.checkNotNull(pitConfig); + this.include = include; + this.exclude = exclude; + this.verbose = verbose; + this.pitConfig = pitConfig; + this.maxDependencyDistance = maxDependencyDistance; + } + + public Predicate getFilter() { + return Prelude.and(Prelude.or(Glob.toGlobPredicates(this.include)), + Prelude.not(Prelude.or(Glob.toGlobPredicates(this.exclude))), + Prelude.not(commonClasses())); + } + + public boolean isVerbose() { + return this.verbose; + } + + public TestPluginArguments getPitConfig() { + return this.pitConfig; + } + + public int getDependencyAnalysisMaxDistance() { + return this.maxDependencyDistance; + } + + private static Predicate commonClasses() { + return Prelude.or( + glob("java/*"), + glob("sun/*"), + glob("org/pitest/coverage/*"), + glob("org/pitest/reloc/*"), + glob("org/pitest/boot/*")); + } + + private static Glob glob(String match) { + return new Glob(match); + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/execute/CoveragePipe.java b/pitest/src/main/java/org/pitest/coverage/execute/CoveragePipe.java index 2834bec1a..35f3817e2 100644 --- a/pitest/src/main/java/org/pitest/coverage/execute/CoveragePipe.java +++ b/pitest/src/main/java/org/pitest/coverage/execute/CoveragePipe.java @@ -1,69 +1,69 @@ -package org.pitest.coverage.execute; - -import java.io.OutputStream; -import java.util.Collection; - -import org.pitest.coverage.CoverageReceiver; -import org.pitest.testapi.Description; -import org.pitest.util.ExitCode; -import org.pitest.util.Id; -import org.pitest.util.SafeDataOutputStream; - -import sun.pitest.CodeCoverageStore; - -public class CoveragePipe implements CoverageReceiver { - - private final SafeDataOutputStream dos; - - public CoveragePipe(final OutputStream dos) { - this.dos = new SafeDataOutputStream(dos); - } - - @Override - public synchronized void newTest() { - CodeCoverageStore.reset(); - } - - @Override - public synchronized void recordTestOutcome(final Description description, - final boolean wasGreen, final int executionTime) { - final Collection hits = CodeCoverageStore.getHits(); - - this.dos.writeByte(Id.OUTCOME); - this.dos.write(description); - this.dos.writeInt(hits.size()); - for (final Long each : hits) { - this.dos.writeLong(each); - } - this.dos.writeBoolean(wasGreen); - this.dos.writeInt(executionTime); - - } - - public synchronized void end(final ExitCode exitCode) { - this.dos.writeByte(Id.DONE); - this.dos.writeInt(exitCode.getCode()); - this.dos.flush(); - } - - @Override - public synchronized void registerClass(final int id, final String className) { - - this.dos.writeByte(Id.CLAZZ); - this.dos.writeInt(id); - this.dos.writeString(className); - - } - - @Override - public synchronized void registerProbes(int classId, String methodName, - String methodDesc, int firstProbe, int lastProbe) { - this.dos.writeByte(Id.PROBES); - this.dos.writeInt(classId); - this.dos.writeString(methodName); - this.dos.writeString(methodDesc); - this.dos.writeInt(firstProbe); - this.dos.writeInt(lastProbe); - } - -} +package org.pitest.coverage.execute; + +import java.io.OutputStream; +import java.util.Collection; + +import org.pitest.coverage.CoverageReceiver; +import org.pitest.testapi.Description; +import org.pitest.util.ExitCode; +import org.pitest.util.Id; +import org.pitest.util.SafeDataOutputStream; + +import sun.pitest.CodeCoverageStore; + +public class CoveragePipe implements CoverageReceiver { + + private final SafeDataOutputStream dos; + + public CoveragePipe(final OutputStream dos) { + this.dos = new SafeDataOutputStream(dos); + } + + @Override + public synchronized void newTest() { + CodeCoverageStore.reset(); + } + + @Override + public synchronized void recordTestOutcome(final Description description, + final boolean wasGreen, final int executionTime) { + final Collection hits = CodeCoverageStore.getHits(); + + this.dos.writeByte(Id.OUTCOME); + this.dos.write(description); + this.dos.writeInt(hits.size()); + for (final Long each : hits) { + this.dos.writeLong(each); + } + this.dos.writeBoolean(wasGreen); + this.dos.writeInt(executionTime); + + } + + public synchronized void end(final ExitCode exitCode) { + this.dos.writeByte(Id.DONE); + this.dos.writeInt(exitCode.getCode()); + this.dos.flush(); + } + + @Override + public synchronized void registerClass(final int id, final String className) { + + this.dos.writeByte(Id.CLAZZ); + this.dos.writeInt(id); + this.dos.writeString(className); + + } + + @Override + public synchronized void registerProbes(int classId, String methodName, + String methodDesc, int firstProbe, int lastProbe) { + this.dos.writeByte(Id.PROBES); + this.dos.writeInt(classId); + this.dos.writeString(methodName); + this.dos.writeString(methodDesc); + this.dos.writeInt(firstProbe); + this.dos.writeInt(lastProbe); + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/execute/CoverageWorker.java b/pitest/src/main/java/org/pitest/coverage/execute/CoverageWorker.java index 50f5b06a7..b34d94573 100644 --- a/pitest/src/main/java/org/pitest/coverage/execute/CoverageWorker.java +++ b/pitest/src/main/java/org/pitest/coverage/execute/CoverageWorker.java @@ -1,72 +1,72 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.execute; - -import static org.pitest.util.Unchecked.translateCheckedException; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.pitest.coverage.CoverageReceiver; -import org.pitest.testapi.TestUnit; -import org.pitest.testapi.execute.Container; -import org.pitest.testapi.execute.Pitest; -import org.pitest.testapi.execute.containers.UnContainer; - -public class CoverageWorker { - - private final CoveragePipe pipe; - private final List tests; - - public CoverageWorker(final CoveragePipe pipe, final List tests) { - this.pipe = pipe; - this.tests = tests; - } - - public void run() { - - try { - final List decoratedTests = decorateForCoverage(this.tests, - this.pipe); - - Collections.sort(decoratedTests, testComparator()); - - final Container c = new UnContainer(); - - final Pitest pit = new Pitest(new ErrorListener()); - pit.run(c, decoratedTests); - - } catch (final Exception ex) { - throw translateCheckedException(ex); - } - - } - - private static Comparator testComparator() { - return (o1, o2) -> o1.getDescription().getQualifiedName() - .compareTo(o2.getDescription().getQualifiedName()); - } - - private static List decorateForCoverage(final List plainTests, - final CoverageReceiver queue) { - final List decorated = new ArrayList<>(plainTests.size()); - for (final TestUnit each : plainTests) { - decorated.add(new CoverageDecorator(queue, each)); - } - return decorated; - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.execute; + +import static org.pitest.util.Unchecked.translateCheckedException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.pitest.coverage.CoverageReceiver; +import org.pitest.testapi.TestUnit; +import org.pitest.testapi.execute.Container; +import org.pitest.testapi.execute.Pitest; +import org.pitest.testapi.execute.containers.UnContainer; + +public class CoverageWorker { + + private final CoveragePipe pipe; + private final List tests; + + public CoverageWorker(final CoveragePipe pipe, final List tests) { + this.pipe = pipe; + this.tests = tests; + } + + public void run() { + + try { + final List decoratedTests = decorateForCoverage(this.tests, + this.pipe); + + Collections.sort(decoratedTests, testComparator()); + + final Container c = new UnContainer(); + + final Pitest pit = new Pitest(new ErrorListener()); + pit.run(c, decoratedTests); + + } catch (final Exception ex) { + throw translateCheckedException(ex); + } + + } + + private static Comparator testComparator() { + return (o1, o2) -> o1.getDescription().getQualifiedName() + .compareTo(o2.getDescription().getQualifiedName()); + } + + private static List decorateForCoverage(final List plainTests, + final CoverageReceiver queue) { + final List decorated = new ArrayList<>(plainTests.size()); + for (final TestUnit each : plainTests) { + decorated.add(new CoverageDecorator(queue, each)); + } + return decorated; + } +} diff --git a/pitest/src/main/java/org/pitest/coverage/execute/DependencyFilter.java b/pitest/src/main/java/org/pitest/coverage/execute/DependencyFilter.java index d5096e5a2..fd478f7ec 100644 --- a/pitest/src/main/java/org/pitest/coverage/execute/DependencyFilter.java +++ b/pitest/src/main/java/org/pitest/coverage/execute/DependencyFilter.java @@ -1,60 +1,60 @@ -package org.pitest.coverage.execute; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; - -import org.pitest.dependency.DependencyExtractor; -import org.pitest.functional.FCollection; -import org.pitest.testapi.TestUnit; -import org.pitest.util.Unchecked; - -class DependencyFilter { - - private final DependencyExtractor analyser; - private final Predicate filter; - - DependencyFilter(final DependencyExtractor analyser, - final Predicate filter) { - this.analyser = analyser; - this.filter = filter; - } - - List filterTestsByDependencyAnalysis(final List tus) { - if (this.analyser.getMaxDistance() < 0) { - return tus; - } else { - return FCollection.filter(tus, isWithinReach()); - } - } - - private Predicate isWithinReach() { - - return new Predicate() { - private final Map cache = new HashMap<>(); - - @Override - public boolean test(final TestUnit testUnit) { - final String testClass = testUnit.getDescription().getFirstTestClass(); - try { - if (this.cache.containsKey(testClass)) { - return this.cache.get(testClass); - } else { - final boolean inReach = !DependencyFilter.this.analyser - .extractCallDependenciesForPackages(testClass, - DependencyFilter.this.filter).isEmpty(); - this.cache.put(testClass, inReach); - return inReach; - } - - } catch (final IOException e) { - throw Unchecked.translateCheckedException(e); - } - } - - }; - } - -} +package org.pitest.coverage.execute; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +import org.pitest.dependency.DependencyExtractor; +import org.pitest.functional.FCollection; +import org.pitest.testapi.TestUnit; +import org.pitest.util.Unchecked; + +class DependencyFilter { + + private final DependencyExtractor analyser; + private final Predicate filter; + + DependencyFilter(final DependencyExtractor analyser, + final Predicate filter) { + this.analyser = analyser; + this.filter = filter; + } + + List filterTestsByDependencyAnalysis(final List tus) { + if (this.analyser.getMaxDistance() < 0) { + return tus; + } else { + return FCollection.filter(tus, isWithinReach()); + } + } + + private Predicate isWithinReach() { + + return new Predicate() { + private final Map cache = new HashMap<>(); + + @Override + public boolean test(final TestUnit testUnit) { + final String testClass = testUnit.getDescription().getFirstTestClass(); + try { + if (this.cache.containsKey(testClass)) { + return this.cache.get(testClass); + } else { + final boolean inReach = !DependencyFilter.this.analyser + .extractCallDependenciesForPackages(testClass, + DependencyFilter.this.filter).isEmpty(); + this.cache.put(testClass, inReach); + return inReach; + } + + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + + }; + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/execute/ErrorListener.java b/pitest/src/main/java/org/pitest/coverage/execute/ErrorListener.java index 8e3678e84..d78f9b71c 100644 --- a/pitest/src/main/java/org/pitest/coverage/execute/ErrorListener.java +++ b/pitest/src/main/java/org/pitest/coverage/execute/ErrorListener.java @@ -1,40 +1,40 @@ -package org.pitest.coverage.execute; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.pitest.testapi.Description; -import org.pitest.testapi.TestListener; -import org.pitest.testapi.TestResult; -import org.pitest.util.Log; - -public class ErrorListener implements TestListener { - private static final Logger LOG = Log.getLogger(); - - @Override - public void onRunStart() { - } - - @Override - public void onTestStart(final Description d) { - } - - @Override - public void onTestFailure(final TestResult tr) { - LOG.log(Level.SEVERE, tr.getDescription().toString(), tr.getThrowable()); - } - - @Override - public void onTestSkipped(final TestResult tr) { - } - - @Override - public void onTestSuccess(final TestResult tr) { - - } - - @Override - public void onRunEnd() { - } - -} +package org.pitest.coverage.execute; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.pitest.testapi.Description; +import org.pitest.testapi.TestListener; +import org.pitest.testapi.TestResult; +import org.pitest.util.Log; + +public class ErrorListener implements TestListener { + private static final Logger LOG = Log.getLogger(); + + @Override + public void onRunStart() { + } + + @Override + public void onTestStart(final Description d) { + } + + @Override + public void onTestFailure(final TestResult tr) { + LOG.log(Level.SEVERE, tr.getDescription().toString(), tr.getThrowable()); + } + + @Override + public void onTestSkipped(final TestResult tr) { + } + + @Override + public void onTestSuccess(final TestResult tr) { + + } + + @Override + public void onRunEnd() { + } + +} diff --git a/pitest/src/main/java/org/pitest/coverage/execute/JavassistCoverageInterceptor.java b/pitest/src/main/java/org/pitest/coverage/execute/JavassistCoverageInterceptor.java index 0a05de8c9..9d6aec029 100644 --- a/pitest/src/main/java/org/pitest/coverage/execute/JavassistCoverageInterceptor.java +++ b/pitest/src/main/java/org/pitest/coverage/execute/JavassistCoverageInterceptor.java @@ -1,103 +1,103 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.execute; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.pitest.bytecode.FrameOptions; -import org.pitest.classinfo.ComputeClassWriter; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.coverage.CoverageClassVisitor; -import org.pitest.reflection.Reflection; -import org.pitest.util.IsolationUtils; -import org.pitest.util.StreamUtil; -import org.pitest.util.Unchecked; - -import sun.pitest.CodeCoverageStore; - -public final class JavassistCoverageInterceptor { - - private static final Map COMPUTE_CACHE = new ConcurrentHashMap<>(); - - private JavassistCoverageInterceptor() { - - } - - public static InputStream openClassfile(final Object classPath, // NO_UCD - final String name) { - - try { - if (isInstrumentedClass(name)) { - final byte[] bs = getOriginalBytes(classPath, name); - return new ByteArrayInputStream( - transformBytes(IsolationUtils.getContextClassLoader(), name, bs)); - } else { - return returnNormalBytes(classPath, name); - } - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex); - } - - } - - private static byte[] getOriginalBytes(final Object classPath, - final String name) throws IOException { - try (InputStream is = returnNormalBytes(classPath,name)) { - final byte[] bs = StreamUtil.streamToByteArray(is); - return bs; - } - } - - private static byte[] transformBytes(final ClassLoader loader, - final String className, final byte[] classfileBuffer) { - final ClassReader reader = new ClassReader(classfileBuffer); - final ClassWriter writer = new ComputeClassWriter( - new ClassloaderByteArraySource(loader), COMPUTE_CACHE, - FrameOptions.pickFlags(classfileBuffer)); - - // The transformed classes will be given a different id than the one already loaded. - // Not clear if this is desirable or not. At the point of writing this comment - // pitest will merge coverage of all classes with the same fully qualified name. - // If this changes this might become a bug, however it would also probably not be possible - // to support powermock if this assumption changed, so this code would most likely be deleted. - - final int id = CodeCoverageStore.registerClass(className); - reader.accept(new CoverageClassVisitor(id, writer), - ClassReader.EXPAND_FRAMES); - return writer.toByteArray(); - } - - private static InputStream returnNormalBytes(final Object classPath, - final String name) { - try { - return (InputStream) Reflection.publicMethod(classPath.getClass(), - "openClassfile").invoke(classPath, name); - } catch (final Exception e) { - throw Unchecked.translateCheckedException(e); - } - } - - private static boolean isInstrumentedClass(final String name) { - return true; - } - - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.execute; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.pitest.bytecode.FrameOptions; +import org.pitest.classinfo.ComputeClassWriter; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.coverage.CoverageClassVisitor; +import org.pitest.reflection.Reflection; +import org.pitest.util.IsolationUtils; +import org.pitest.util.StreamUtil; +import org.pitest.util.Unchecked; + +import sun.pitest.CodeCoverageStore; + +public final class JavassistCoverageInterceptor { + + private static final Map COMPUTE_CACHE = new ConcurrentHashMap<>(); + + private JavassistCoverageInterceptor() { + + } + + public static InputStream openClassfile(final Object classPath, // NO_UCD + final String name) { + + try { + if (isInstrumentedClass(name)) { + final byte[] bs = getOriginalBytes(classPath, name); + return new ByteArrayInputStream( + transformBytes(IsolationUtils.getContextClassLoader(), name, bs)); + } else { + return returnNormalBytes(classPath, name); + } + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex); + } + + } + + private static byte[] getOriginalBytes(final Object classPath, + final String name) throws IOException { + try (InputStream is = returnNormalBytes(classPath,name)) { + final byte[] bs = StreamUtil.streamToByteArray(is); + return bs; + } + } + + private static byte[] transformBytes(final ClassLoader loader, + final String className, final byte[] classfileBuffer) { + final ClassReader reader = new ClassReader(classfileBuffer); + final ClassWriter writer = new ComputeClassWriter( + new ClassloaderByteArraySource(loader), COMPUTE_CACHE, + FrameOptions.pickFlags(classfileBuffer)); + + // The transformed classes will be given a different id than the one already loaded. + // Not clear if this is desirable or not. At the point of writing this comment + // pitest will merge coverage of all classes with the same fully qualified name. + // If this changes this might become a bug, however it would also probably not be possible + // to support powermock if this assumption changed, so this code would most likely be deleted. + + final int id = CodeCoverageStore.registerClass(className); + reader.accept(new CoverageClassVisitor(id, writer), + ClassReader.EXPAND_FRAMES); + return writer.toByteArray(); + } + + private static InputStream returnNormalBytes(final Object classPath, + final String name) { + try { + return (InputStream) Reflection.publicMethod(classPath.getClass(), + "openClassfile").invoke(classPath, name); + } catch (final Exception e) { + throw Unchecked.translateCheckedException(e); + } + } + + private static boolean isInstrumentedClass(final String name) { + return true; + } + + +} diff --git a/pitest/src/main/java/org/pitest/dependency/DependencyAccess.java b/pitest/src/main/java/org/pitest/dependency/DependencyAccess.java index 950db36a1..404857215 100644 --- a/pitest/src/main/java/org/pitest/dependency/DependencyAccess.java +++ b/pitest/src/main/java/org/pitest/dependency/DependencyAccess.java @@ -1,140 +1,140 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.dependency; - -final class DependencyAccess { - - static class Member implements Comparable { - private final String owner; - private final String name; - - protected Member(final String owner, final String name) { - this.owner = owner; - this.name = name; - } - - public String getOwner() { - return this.owner; - } - - public String getName() { - return this.name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.name == null) ? 0 : this.name.hashCode()); - result = (prime * result) - + ((this.owner == null) ? 0 : this.owner.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Member other = (Member) obj; - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - if (this.owner == null) { - if (other.owner != null) { - return false; - } - } else if (!this.owner.equals(other.owner)) { - return false; - } - return true; - } - - @Override - public int compareTo(final Member other) { - return (other.name.compareTo(this.name) * 100) - + (other.owner.compareTo(this.owner) * 1000); - } - - } - - private final Member source; - private final Member dest; - - protected DependencyAccess(final Member source, final Member dest) { - this.source = source; - this.dest = dest; - } - - public Member getSource() { - return this.source; - } - - public Member getDest() { - return this.dest; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.dest == null) ? 0 : this.dest.hashCode()); - result = (prime * result) - + ((this.source == null) ? 0 : this.source.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final DependencyAccess other = (DependencyAccess) obj; - if (this.dest == null) { - if (other.dest != null) { - return false; - } - } else if (!this.dest.equals(other.dest)) { - return false; - } - if (this.source == null) { - if (other.source != null) { - return false; - } - } else if (!this.source.equals(other.source)) { - return false; - } - return true; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.dependency; + +final class DependencyAccess { + + static class Member implements Comparable { + private final String owner; + private final String name; + + protected Member(final String owner, final String name) { + this.owner = owner; + this.name = name; + } + + public String getOwner() { + return this.owner; + } + + public String getName() { + return this.name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.name == null) ? 0 : this.name.hashCode()); + result = (prime * result) + + ((this.owner == null) ? 0 : this.owner.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Member other = (Member) obj; + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + if (this.owner == null) { + if (other.owner != null) { + return false; + } + } else if (!this.owner.equals(other.owner)) { + return false; + } + return true; + } + + @Override + public int compareTo(final Member other) { + return (other.name.compareTo(this.name) * 100) + + (other.owner.compareTo(this.owner) * 1000); + } + + } + + private final Member source; + private final Member dest; + + protected DependencyAccess(final Member source, final Member dest) { + this.source = source; + this.dest = dest; + } + + public Member getSource() { + return this.source; + } + + public Member getDest() { + return this.dest; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.dest == null) ? 0 : this.dest.hashCode()); + result = (prime * result) + + ((this.source == null) ? 0 : this.source.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final DependencyAccess other = (DependencyAccess) obj; + if (this.dest == null) { + if (other.dest != null) { + return false; + } + } else if (!this.dest.equals(other.dest)) { + return false; + } + if (this.source == null) { + if (other.source != null) { + return false; + } + } else if (!this.source.equals(other.source)) { + return false; + } + return true; + } + +} diff --git a/pitest/src/main/java/org/pitest/dependency/DependencyClassVisitor.java b/pitest/src/main/java/org/pitest/dependency/DependencyClassVisitor.java index a3174191c..3d9c2a656 100644 --- a/pitest/src/main/java/org/pitest/dependency/DependencyClassVisitor.java +++ b/pitest/src/main/java/org/pitest/dependency/DependencyClassVisitor.java @@ -1,91 +1,91 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.dependency; - -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.dependency.DependencyAccess.Member; -import org.pitest.functional.SideEffect1; - -class DependencyClassVisitor extends ClassVisitor { - - private final SideEffect1 typeReceiver; - private String className; - - protected DependencyClassVisitor(final ClassVisitor visitor, - final SideEffect1 typeReceiver) { - super(Opcodes.ASM6, visitor); - this.typeReceiver = filterOutJavaLangObject(typeReceiver); - } - - private SideEffect1 filterOutJavaLangObject( - final SideEffect1 child) { - return a -> { - if (!a.getDest().getOwner().equals("java/lang/Object")) { - child.apply(a); - } - - }; - } - - @Override - public void visit(final int version, final int access, final String name, - final String signature, final String superName, final String[] interfaces) { - this.className = name; - } - - @Override - public MethodVisitor visitMethod(final int access, final String name, - final String desc, final String signature, final String[] exceptions) { - final MethodVisitor methodVisitor = this.cv.visitMethod(access, name, desc, - signature, exceptions); - - final Member me = new Member(this.className, name); - return new DependencyAnalysisMethodVisitor(me, methodVisitor, - this.typeReceiver); - } - - private static class DependencyAnalysisMethodVisitor extends MethodVisitor { - - private final Member member; - private final SideEffect1 typeReceiver; - - DependencyAnalysisMethodVisitor(final Member member, - final MethodVisitor methodVisitor, - final SideEffect1 typeReceiver) { - super(Opcodes.ASM6, methodVisitor); - this.typeReceiver = typeReceiver; - this.member = member; - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, - final String name, final String desc, boolean itf) { - this.typeReceiver.apply(new DependencyAccess(this.member, new Member( - owner, name))); - this.mv.visitMethodInsn(opcode, owner, name, desc, itf); - } - - @Override - public void visitFieldInsn(final int opcode, final String owner, - final String name, final String desc) { - this.typeReceiver.apply(new DependencyAccess(this.member, new Member( - owner, name))); - this.mv.visitFieldInsn(opcode, owner, name, desc); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.dependency; + +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.dependency.DependencyAccess.Member; +import org.pitest.functional.SideEffect1; + +class DependencyClassVisitor extends ClassVisitor { + + private final SideEffect1 typeReceiver; + private String className; + + protected DependencyClassVisitor(final ClassVisitor visitor, + final SideEffect1 typeReceiver) { + super(Opcodes.ASM6, visitor); + this.typeReceiver = filterOutJavaLangObject(typeReceiver); + } + + private SideEffect1 filterOutJavaLangObject( + final SideEffect1 child) { + return a -> { + if (!a.getDest().getOwner().equals("java/lang/Object")) { + child.apply(a); + } + + }; + } + + @Override + public void visit(final int version, final int access, final String name, + final String signature, final String superName, final String[] interfaces) { + this.className = name; + } + + @Override + public MethodVisitor visitMethod(final int access, final String name, + final String desc, final String signature, final String[] exceptions) { + final MethodVisitor methodVisitor = this.cv.visitMethod(access, name, desc, + signature, exceptions); + + final Member me = new Member(this.className, name); + return new DependencyAnalysisMethodVisitor(me, methodVisitor, + this.typeReceiver); + } + + private static class DependencyAnalysisMethodVisitor extends MethodVisitor { + + private final Member member; + private final SideEffect1 typeReceiver; + + DependencyAnalysisMethodVisitor(final Member member, + final MethodVisitor methodVisitor, + final SideEffect1 typeReceiver) { + super(Opcodes.ASM6, methodVisitor); + this.typeReceiver = typeReceiver; + this.member = member; + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, + final String name, final String desc, boolean itf) { + this.typeReceiver.apply(new DependencyAccess(this.member, new Member( + owner, name))); + this.mv.visitMethodInsn(opcode, owner, name, desc, itf); + } + + @Override + public void visitFieldInsn(final int opcode, final String owner, + final String name, final String desc) { + this.typeReceiver.apply(new DependencyAccess(this.member, new Member( + owner, name))); + this.mv.visitFieldInsn(opcode, owner, name, desc); + } + } + +} diff --git a/pitest/src/main/java/org/pitest/dependency/DependencyExtractor.java b/pitest/src/main/java/org/pitest/dependency/DependencyExtractor.java index eb60816c4..26128b8b5 100644 --- a/pitest/src/main/java/org/pitest/dependency/DependencyExtractor.java +++ b/pitest/src/main/java/org/pitest/dependency/DependencyExtractor.java @@ -1,202 +1,202 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.dependency; - -import static org.pitest.functional.prelude.Prelude.and; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.BiFunction; -import java.util.function.Predicate; -import java.util.logging.Logger; - -import org.objectweb.asm.ClassReader; -import org.pitest.bytecode.NullVisitor; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.functional.SideEffect1; -import org.pitest.util.Functions; -import org.pitest.util.Log; - -public class DependencyExtractor { - private static final Logger LOG = Log.getLogger(); - private final int depth; - private final ClassByteArraySource classToBytes; - - public DependencyExtractor(final ClassByteArraySource classToBytes, - final int depth) { - this.depth = depth; - this.classToBytes = classToBytes; - } - - public Collection extractCallDependenciesForPackages( - final String clazz, final Predicate targetPackages) - throws IOException { - final Set allDependencies = extractCallDependencies(clazz, - new IgnoreCoreClasses()); - return FCollection.filter(allDependencies, - and(asJVMNamePredicate(targetPackages), notSuppliedClass(clazz))); - } - - private static Predicate notSuppliedClass(final String clazz) { - return a -> !Functions.jvmClassToClassName().apply(a).equals(clazz); - } - - private static Predicate asJVMNamePredicate( - final Predicate predicate) { - return a -> predicate.test(Functions.jvmClassToClassName().apply(a)); - } - - public Collection extractCallDependenciesForPackages( - final String clazz, final Predicate targetPackages, - final Predicate doNotTraverse) throws IOException { - final Set allDependencies = extractCallDependencies(clazz, - doNotTraverse); - return FCollection.filter(allDependencies, targetPackages); - } - - Set extractCallDependencies(final String clazz, - final Predicate filter) throws IOException { - - return this - .extractCallDependencies(clazz, new TreeSet(), filter, 0); - } - - public int getMaxDistance() { - return this.depth; - } - - private Set extractCallDependencies(final String clazz, - final TreeSet visited, final Predicate filter, - final int currentDepth) throws IOException { - - final Map> classesToAccesses = groupDependenciesByClass(extractRelevantDependencies( - clazz, filter)); - final Set dependencies = new HashSet<>( - classesToAccesses.keySet()); - - dependencies.removeAll(visited); - visited.addAll(dependencies); - - if ((currentDepth < (this.depth - 1)) || (this.depth == 0)) { - - dependencies.addAll(examineChildDependencies(currentDepth, dependencies, - visited, filter)); - - } - - return dependencies; - - } - - private Set examineChildDependencies(final int currentDepth, - final Set classes, final TreeSet visited, - final Predicate filter) throws IOException { - - final Set deps = new HashSet<>(); - for (final String each : classes) { - final Set childDependencies = extractCallDependencies(each, - visited, filter, currentDepth + 1); - deps.addAll(childDependencies); - } - return deps; - } - - private Set extractRelevantDependencies(final String clazz, - final Predicate filter) throws IOException { - final List dependencies = extract(clazz, filter); - final Set relevantDependencies = new TreeSet<>( - equalDestinationComparator()); - FCollection.filter(dependencies, filter, relevantDependencies); - return relevantDependencies; - } - - private static Comparator equalDestinationComparator() { - return (o1, o2) -> o1.getDest().compareTo(o2.getDest()); - } - - private List extract(final String clazz, - final Predicate filter) throws IOException { - final Optional bytes = this.classToBytes.getBytes(clazz); - if (!bytes.isPresent()) { - LOG.warning("No bytes found for " + clazz); - return Collections.emptyList(); - } - final ClassReader reader = new ClassReader(bytes.get()); - final List dependencies = new ArrayList<>(); - - final SideEffect1 se = constructCollectingSideEffectForVisitor( - dependencies, and(nameIsEqual(clazz).negate(), filter)); - final DependencyClassVisitor dcv = new DependencyClassVisitor( - new NullVisitor(), se); - reader.accept(dcv, ClassReader.EXPAND_FRAMES); - return dependencies; - } - - private Map> groupDependenciesByClass( - final Set relevantDependencies) { - final List sortedByClass = new ArrayList<>( - relevantDependencies.size()); - Collections.sort(sortedByClass, classNameComparator()); - - return FCollection.fold(addDependenciesToMap(), - new HashMap>(), relevantDependencies); - - } - - private static BiFunction>, DependencyAccess, Map>> addDependenciesToMap() { - - return (map, access) -> { - - List list = map.get(access.getDest().getOwner()); - if (list == null) { - list = new ArrayList<>(); - } - list.add(access); - map.put(access.getDest().getOwner(), list); - return map; - }; - } - - private static Comparator classNameComparator() { - return (lhs, rhs) -> lhs.getDest().getOwner().compareTo(rhs.getDest().getOwner()); - } - - private static Predicate nameIsEqual(final String clazz) { - return a -> a.getDest().getOwner().equals(clazz); - } - - private static SideEffect1 constructCollectingSideEffectForVisitor( - final List dependencies, - final Predicate predicate) { - final SideEffect1 se = a -> { - if (predicate.test(a)) { - dependencies.add(a); - } - }; - return se; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.dependency; + +import static org.pitest.functional.prelude.Prelude.and; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.BiFunction; +import java.util.function.Predicate; +import java.util.logging.Logger; + +import org.objectweb.asm.ClassReader; +import org.pitest.bytecode.NullVisitor; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.functional.SideEffect1; +import org.pitest.util.Functions; +import org.pitest.util.Log; + +public class DependencyExtractor { + private static final Logger LOG = Log.getLogger(); + private final int depth; + private final ClassByteArraySource classToBytes; + + public DependencyExtractor(final ClassByteArraySource classToBytes, + final int depth) { + this.depth = depth; + this.classToBytes = classToBytes; + } + + public Collection extractCallDependenciesForPackages( + final String clazz, final Predicate targetPackages) + throws IOException { + final Set allDependencies = extractCallDependencies(clazz, + new IgnoreCoreClasses()); + return FCollection.filter(allDependencies, + and(asJVMNamePredicate(targetPackages), notSuppliedClass(clazz))); + } + + private static Predicate notSuppliedClass(final String clazz) { + return a -> !Functions.jvmClassToClassName().apply(a).equals(clazz); + } + + private static Predicate asJVMNamePredicate( + final Predicate predicate) { + return a -> predicate.test(Functions.jvmClassToClassName().apply(a)); + } + + public Collection extractCallDependenciesForPackages( + final String clazz, final Predicate targetPackages, + final Predicate doNotTraverse) throws IOException { + final Set allDependencies = extractCallDependencies(clazz, + doNotTraverse); + return FCollection.filter(allDependencies, targetPackages); + } + + Set extractCallDependencies(final String clazz, + final Predicate filter) throws IOException { + + return this + .extractCallDependencies(clazz, new TreeSet(), filter, 0); + } + + public int getMaxDistance() { + return this.depth; + } + + private Set extractCallDependencies(final String clazz, + final TreeSet visited, final Predicate filter, + final int currentDepth) throws IOException { + + final Map> classesToAccesses = groupDependenciesByClass(extractRelevantDependencies( + clazz, filter)); + final Set dependencies = new HashSet<>( + classesToAccesses.keySet()); + + dependencies.removeAll(visited); + visited.addAll(dependencies); + + if ((currentDepth < (this.depth - 1)) || (this.depth == 0)) { + + dependencies.addAll(examineChildDependencies(currentDepth, dependencies, + visited, filter)); + + } + + return dependencies; + + } + + private Set examineChildDependencies(final int currentDepth, + final Set classes, final TreeSet visited, + final Predicate filter) throws IOException { + + final Set deps = new HashSet<>(); + for (final String each : classes) { + final Set childDependencies = extractCallDependencies(each, + visited, filter, currentDepth + 1); + deps.addAll(childDependencies); + } + return deps; + } + + private Set extractRelevantDependencies(final String clazz, + final Predicate filter) throws IOException { + final List dependencies = extract(clazz, filter); + final Set relevantDependencies = new TreeSet<>( + equalDestinationComparator()); + FCollection.filter(dependencies, filter, relevantDependencies); + return relevantDependencies; + } + + private static Comparator equalDestinationComparator() { + return (o1, o2) -> o1.getDest().compareTo(o2.getDest()); + } + + private List extract(final String clazz, + final Predicate filter) throws IOException { + final Optional bytes = this.classToBytes.getBytes(clazz); + if (!bytes.isPresent()) { + LOG.warning("No bytes found for " + clazz); + return Collections.emptyList(); + } + final ClassReader reader = new ClassReader(bytes.get()); + final List dependencies = new ArrayList<>(); + + final SideEffect1 se = constructCollectingSideEffectForVisitor( + dependencies, and(nameIsEqual(clazz).negate(), filter)); + final DependencyClassVisitor dcv = new DependencyClassVisitor( + new NullVisitor(), se); + reader.accept(dcv, ClassReader.EXPAND_FRAMES); + return dependencies; + } + + private Map> groupDependenciesByClass( + final Set relevantDependencies) { + final List sortedByClass = new ArrayList<>( + relevantDependencies.size()); + Collections.sort(sortedByClass, classNameComparator()); + + return FCollection.fold(addDependenciesToMap(), + new HashMap>(), relevantDependencies); + + } + + private static BiFunction>, DependencyAccess, Map>> addDependenciesToMap() { + + return (map, access) -> { + + List list = map.get(access.getDest().getOwner()); + if (list == null) { + list = new ArrayList<>(); + } + list.add(access); + map.put(access.getDest().getOwner(), list); + return map; + }; + } + + private static Comparator classNameComparator() { + return (lhs, rhs) -> lhs.getDest().getOwner().compareTo(rhs.getDest().getOwner()); + } + + private static Predicate nameIsEqual(final String clazz) { + return a -> a.getDest().getOwner().equals(clazz); + } + + private static SideEffect1 constructCollectingSideEffectForVisitor( + final List dependencies, + final Predicate predicate) { + final SideEffect1 se = a -> { + if (predicate.test(a)) { + dependencies.add(a); + } + }; + return se; + } + +} diff --git a/pitest/src/main/java/org/pitest/dependency/IgnoreCoreClasses.java b/pitest/src/main/java/org/pitest/dependency/IgnoreCoreClasses.java index cc0018028..093bb66f1 100644 --- a/pitest/src/main/java/org/pitest/dependency/IgnoreCoreClasses.java +++ b/pitest/src/main/java/org/pitest/dependency/IgnoreCoreClasses.java @@ -1,43 +1,43 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.dependency; - -import java.util.Arrays; -import java.util.Collection; -import java.util.function.Predicate; - -import org.pitest.functional.prelude.Prelude; -import org.pitest.util.Glob; - -public class IgnoreCoreClasses implements Predicate { - - private final Predicate impl; - private final Collection filtered = Arrays.asList("java.*", "sun.*", - "javax.*", "org.junit.*", - "junit.*", "org.mockito.*", - "org.powermock.*", - "org.jmock.*", "com.sun.*"); - - IgnoreCoreClasses() { - this.impl = Prelude.not(Prelude.or(Glob.toGlobPredicates(this.filtered))); - } - - @Override - public boolean test(final DependencyAccess a) { - final String owner = a.getDest().getOwner().replace("/", "."); - return this.impl.test(owner); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.dependency; + +import java.util.Arrays; +import java.util.Collection; +import java.util.function.Predicate; + +import org.pitest.functional.prelude.Prelude; +import org.pitest.util.Glob; + +public class IgnoreCoreClasses implements Predicate { + + private final Predicate impl; + private final Collection filtered = Arrays.asList("java.*", "sun.*", + "javax.*", "org.junit.*", + "junit.*", "org.mockito.*", + "org.powermock.*", + "org.jmock.*", "com.sun.*"); + + IgnoreCoreClasses() { + this.impl = Prelude.not(Prelude.or(Glob.toGlobPredicates(this.filtered))); + } + + @Override + public boolean test(final DependencyAccess a) { + final String owner = a.getDest().getOwner().replace("/", "."); + return this.impl.test(owner); + } + +} diff --git a/pitest/src/main/java/org/pitest/extension/common/CompoundTestSuiteFinder.java b/pitest/src/main/java/org/pitest/extension/common/CompoundTestSuiteFinder.java index 2b0c3a728..9db212b2e 100644 --- a/pitest/src/main/java/org/pitest/extension/common/CompoundTestSuiteFinder.java +++ b/pitest/src/main/java/org/pitest/extension/common/CompoundTestSuiteFinder.java @@ -1,30 +1,30 @@ -package org.pitest.extension.common; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.pitest.testapi.TestSuiteFinder; - -public final class CompoundTestSuiteFinder implements TestSuiteFinder { - - private final Collection children; - - public CompoundTestSuiteFinder(final Collection children) { - this.children = children; - } - - @Override - public List> apply(final Class a) { - for (final TestSuiteFinder i : this.children) { - final List> found = i.apply(a); - if (!found.isEmpty()) { - return found; - } - - } - - return Collections.emptyList(); - } - -} +package org.pitest.extension.common; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.pitest.testapi.TestSuiteFinder; + +public final class CompoundTestSuiteFinder implements TestSuiteFinder { + + private final Collection children; + + public CompoundTestSuiteFinder(final Collection children) { + this.children = children; + } + + @Override + public List> apply(final Class a) { + for (final TestSuiteFinder i : this.children) { + final List> found = i.apply(a); + if (!found.isEmpty()) { + return found; + } + + } + + return Collections.emptyList(); + } + +} diff --git a/pitest/src/main/java/org/pitest/extension/common/NoTestSuiteFinder.java b/pitest/src/main/java/org/pitest/extension/common/NoTestSuiteFinder.java index ee4d9ab5a..54021308a 100644 --- a/pitest/src/main/java/org/pitest/extension/common/NoTestSuiteFinder.java +++ b/pitest/src/main/java/org/pitest/extension/common/NoTestSuiteFinder.java @@ -1,15 +1,15 @@ -package org.pitest.extension.common; - -import java.util.Collections; -import java.util.List; - -import org.pitest.testapi.TestSuiteFinder; - -public class NoTestSuiteFinder implements TestSuiteFinder { - - @Override - public List> apply(final Class a) { - return Collections.emptyList(); - } - -} +package org.pitest.extension.common; + +import java.util.Collections; +import java.util.List; + +import org.pitest.testapi.TestSuiteFinder; + +public class NoTestSuiteFinder implements TestSuiteFinder { + + @Override + public List> apply(final Class a) { + return Collections.emptyList(); + } + +} diff --git a/pitest/src/main/java/org/pitest/extension/common/TestUnitDecorator.java b/pitest/src/main/java/org/pitest/extension/common/TestUnitDecorator.java index 6085155c3..7a04bd354 100644 --- a/pitest/src/main/java/org/pitest/extension/common/TestUnitDecorator.java +++ b/pitest/src/main/java/org/pitest/extension/common/TestUnitDecorator.java @@ -1,41 +1,41 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.extension.common; - -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; -import org.pitest.testapi.TestUnit; - -public abstract class TestUnitDecorator implements TestUnit { - - private final TestUnit child; - - protected TestUnitDecorator(final TestUnit child) { - this.child = child; - } - - @Override - public Description getDescription() { - return this.child.getDescription(); - } - - public TestUnit child() { - return this.child; - } - - @Override - public abstract void execute(ResultCollector rc); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.extension.common; + +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; +import org.pitest.testapi.TestUnit; + +public abstract class TestUnitDecorator implements TestUnit { + + private final TestUnit child; + + protected TestUnitDecorator(final TestUnit child) { + this.child = child; + } + + @Override + public Description getDescription() { + return this.child.getDescription(); + } + + public TestUnit child() { + return this.child; + } + + @Override + public abstract void execute(ResultCollector rc); + +} diff --git a/pitest/src/main/java/org/pitest/functional/F3.java b/pitest/src/main/java/org/pitest/functional/F3.java index 6bdb202c4..539f9789d 100644 --- a/pitest/src/main/java/org/pitest/functional/F3.java +++ b/pitest/src/main/java/org/pitest/functional/F3.java @@ -1,21 +1,21 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -public interface F3 { // NO_UCD - - D apply(A a, B b, C c); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +public interface F3 { // NO_UCD + + D apply(A a, B b, C c); + +} diff --git a/pitest/src/main/java/org/pitest/functional/F4.java b/pitest/src/main/java/org/pitest/functional/F4.java index b9f81b384..e046d9868 100644 --- a/pitest/src/main/java/org/pitest/functional/F4.java +++ b/pitest/src/main/java/org/pitest/functional/F4.java @@ -1,21 +1,21 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -public interface F4 { // NO_UCD - - E apply(A a, B b, C c, D d); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +public interface F4 { // NO_UCD + + E apply(A a, B b, C c, D d); + +} diff --git a/pitest/src/main/java/org/pitest/functional/F5.java b/pitest/src/main/java/org/pitest/functional/F5.java index c27332528..7ed65c75f 100644 --- a/pitest/src/main/java/org/pitest/functional/F5.java +++ b/pitest/src/main/java/org/pitest/functional/F5.java @@ -1,21 +1,21 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -public interface F5 { - - FF apply(A a, B b, C c, D d, E e); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +public interface F5 { + + FF apply(A a, B b, C c, D d, E e); + +} diff --git a/pitest/src/main/java/org/pitest/functional/F6.java b/pitest/src/main/java/org/pitest/functional/F6.java index a96036880..af602a0d3 100644 --- a/pitest/src/main/java/org/pitest/functional/F6.java +++ b/pitest/src/main/java/org/pitest/functional/F6.java @@ -1,21 +1,21 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -public interface F6 { // NO_UCD - - G apply(A a, B b, C c, D d, E e, FF f); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +public interface F6 { // NO_UCD + + G apply(A a, B b, C c, D d, E e, FF f); + +} diff --git a/pitest/src/main/java/org/pitest/functional/FArray.java b/pitest/src/main/java/org/pitest/functional/FArray.java index 3cc5921cc..467f04633 100644 --- a/pitest/src/main/java/org/pitest/functional/FArray.java +++ b/pitest/src/main/java/org/pitest/functional/FArray.java @@ -1,77 +1,77 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.function.Function; -import java.util.function.Predicate; - -/** - * Slightly functional style operations for arrays. - */ -public abstract class FArray { - - public static void filter(final T[] xs, final Predicate predicate, - final Collection dest) { - if (xs != null) { - for (final T x : xs) { - if (predicate.test(x)) { - dest.add(x); - } - } - } - } - - public static List filter(final T[] xs, final Predicate predicate) { - final List dest = new ArrayList<>(); - filter(xs, predicate, dest); - return dest; - } - - public static boolean contains(final T[] xs, final Predicate predicate) { - for (final T x : xs) { - if (predicate.test(x)) { - return true; - } - } - return false; - - } - - public static void flatMapTo(final A[] as, - final Function> f, final Collection bs) { - if (as != null) { - for (final A a : as) { - for (final B each : f.apply(a)) { - bs.add(each); - } - } - } - } - - public static List flatMap(final A[] as, - final Function> f) { - final List bs = emptyList(); - flatMapTo(as, f, bs); - return bs; - } - - private static List emptyList() { - return new ArrayList<>(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * Slightly functional style operations for arrays. + */ +public abstract class FArray { + + public static void filter(final T[] xs, final Predicate predicate, + final Collection dest) { + if (xs != null) { + for (final T x : xs) { + if (predicate.test(x)) { + dest.add(x); + } + } + } + } + + public static List filter(final T[] xs, final Predicate predicate) { + final List dest = new ArrayList<>(); + filter(xs, predicate, dest); + return dest; + } + + public static boolean contains(final T[] xs, final Predicate predicate) { + for (final T x : xs) { + if (predicate.test(x)) { + return true; + } + } + return false; + + } + + public static void flatMapTo(final A[] as, + final Function> f, final Collection bs) { + if (as != null) { + for (final A a : as) { + for (final B each : f.apply(a)) { + bs.add(each); + } + } + } + } + + public static List flatMap(final A[] as, + final Function> f) { + final List bs = emptyList(); + flatMapTo(as, f, bs); + return bs; + } + + private static List emptyList() { + return new ArrayList<>(); + } + +} diff --git a/pitest/src/main/java/org/pitest/functional/FCollection.java b/pitest/src/main/java/org/pitest/functional/FCollection.java index 4ccddbe4d..d99269fd0 100644 --- a/pitest/src/main/java/org/pitest/functional/FCollection.java +++ b/pitest/src/main/java/org/pitest/functional/FCollection.java @@ -1,170 +1,170 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Predicate; - -/** - * Functional programming style operations for plain old Java iterables. - */ -public abstract class FCollection { - - public static void forEach(final Iterable as, - final SideEffect1 e) { - for (final A a : as) { - e.apply(a); - } - } - - public static void mapTo(final Iterable as, - final Function f, final Collection bs) { - if (as != null) { - for (final A a : as) { - bs.add(f.apply(a)); - } - } - } - - public static List map(final Iterable as, - final Function f) { - final List bs = emptyList(); - mapTo(as, f, bs); - return bs; - } - - public static void flatMapTo(final Iterable as, - final Function> f, final Collection bs) { - if (as != null) { - for (final A a : as) { - for (final B each : f.apply(a)) { - bs.add(each); - } - } - } - } - - public static List flatMap( - final Iterable as, final Function> f) { - final List bs = emptyList(); - flatMapTo(as, f, bs); - return bs; - } - - private static List emptyList() { - return new ArrayList<>(); - } - - public static List filter(final Iterable xs, - final Predicate predicate) { - final List dest = emptyList(); - filter(xs, predicate, dest); - return dest; - } - - public static void filter(final Iterable xs, - final Predicate predicate, final Collection dest) { - for (final T x : xs) { - if (predicate.test(x)) { - dest.add(x); - } - } - } - - - public static java.util.Optional findFirst(final Iterable xs, - final Predicate predicate) { - for (final T x : xs) { - if (predicate.test(x)) { - return java.util.Optional.ofNullable(x); - } - } - return java.util.Optional.empty(); - } - - - public static boolean contains(final Iterable xs, - final Predicate predicate) { - for (final T x : xs) { - if (predicate.test(x)) { - return true; - } - } - return false; - - } - - public static A fold(final BiFunction f, final A z, - final Iterable xs) { - A p = z; - for (final B x : xs) { - p = f.apply(p, x); - } - return p; - } - - public static Collection flatten( - final Iterable> ts) { - final List list = new ArrayList<>(); - for (final Iterable it : ts) { - for (final T each : it) { - list.add(each); - } - } - return list; - } - - public static List> splitToLength( - final int targetLength, final Iterable ts) { - final List> list = new ArrayList<>(); - List temp = new ArrayList<>(); - int i = 0; - for (final T each : ts) { - if (i == targetLength) { - list.add(temp); - temp = new ArrayList<>(); - i = 0; - } - temp.add(each); - i++; - } - if (!temp.isEmpty()) { - list.add(temp); - } - return list; - } - - public static Map> bucket(final Iterable bs, - final Function f) { - final Map> bucketed = new HashMap<>(); - for (final B each : bs) { - final A key = f.apply(each); - Collection existing = bucketed.get(key); - if (existing == null) { - existing = new ArrayList<>(); - bucketed.put(key, existing); - } - existing.add(each); - } - return bucketed; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * Functional programming style operations for plain old Java iterables. + */ +public abstract class FCollection { + + public static void forEach(final Iterable as, + final SideEffect1 e) { + for (final A a : as) { + e.apply(a); + } + } + + public static void mapTo(final Iterable as, + final Function f, final Collection bs) { + if (as != null) { + for (final A a : as) { + bs.add(f.apply(a)); + } + } + } + + public static List map(final Iterable as, + final Function f) { + final List bs = emptyList(); + mapTo(as, f, bs); + return bs; + } + + public static void flatMapTo(final Iterable as, + final Function> f, final Collection bs) { + if (as != null) { + for (final A a : as) { + for (final B each : f.apply(a)) { + bs.add(each); + } + } + } + } + + public static List flatMap( + final Iterable as, final Function> f) { + final List bs = emptyList(); + flatMapTo(as, f, bs); + return bs; + } + + private static List emptyList() { + return new ArrayList<>(); + } + + public static List filter(final Iterable xs, + final Predicate predicate) { + final List dest = emptyList(); + filter(xs, predicate, dest); + return dest; + } + + public static void filter(final Iterable xs, + final Predicate predicate, final Collection dest) { + for (final T x : xs) { + if (predicate.test(x)) { + dest.add(x); + } + } + } + + + public static java.util.Optional findFirst(final Iterable xs, + final Predicate predicate) { + for (final T x : xs) { + if (predicate.test(x)) { + return java.util.Optional.ofNullable(x); + } + } + return java.util.Optional.empty(); + } + + + public static boolean contains(final Iterable xs, + final Predicate predicate) { + for (final T x : xs) { + if (predicate.test(x)) { + return true; + } + } + return false; + + } + + public static A fold(final BiFunction f, final A z, + final Iterable xs) { + A p = z; + for (final B x : xs) { + p = f.apply(p, x); + } + return p; + } + + public static Collection flatten( + final Iterable> ts) { + final List list = new ArrayList<>(); + for (final Iterable it : ts) { + for (final T each : it) { + list.add(each); + } + } + return list; + } + + public static List> splitToLength( + final int targetLength, final Iterable ts) { + final List> list = new ArrayList<>(); + List temp = new ArrayList<>(); + int i = 0; + for (final T each : ts) { + if (i == targetLength) { + list.add(temp); + temp = new ArrayList<>(); + i = 0; + } + temp.add(each); + i++; + } + if (!temp.isEmpty()) { + list.add(temp); + } + return list; + } + + public static Map> bucket(final Iterable bs, + final Function f) { + final Map> bucketed = new HashMap<>(); + for (final B each : bs) { + final A key = f.apply(each); + Collection existing = bucketed.get(key); + if (existing == null) { + existing = new ArrayList<>(); + bucketed.put(key, existing); + } + existing.add(each); + } + return bucketed; + } + +} diff --git a/pitest/src/main/java/org/pitest/functional/SideEffect.java b/pitest/src/main/java/org/pitest/functional/SideEffect.java index 710b6beaf..9a52d528d 100644 --- a/pitest/src/main/java/org/pitest/functional/SideEffect.java +++ b/pitest/src/main/java/org/pitest/functional/SideEffect.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -/** - * @author henry - * - */ -public interface SideEffect { - - void apply(); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +/** + * @author henry + * + */ +public interface SideEffect { + + void apply(); + +} diff --git a/pitest/src/main/java/org/pitest/functional/SideEffect1.java b/pitest/src/main/java/org/pitest/functional/SideEffect1.java index 88f47efe5..cddce00af 100644 --- a/pitest/src/main/java/org/pitest/functional/SideEffect1.java +++ b/pitest/src/main/java/org/pitest/functional/SideEffect1.java @@ -1,21 +1,21 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -public interface SideEffect1 { - - void apply(A a); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +public interface SideEffect1 { + + void apply(A a); + +} diff --git a/pitest/src/main/java/org/pitest/functional/SideEffect2.java b/pitest/src/main/java/org/pitest/functional/SideEffect2.java index 8d6287b36..8458e2a60 100644 --- a/pitest/src/main/java/org/pitest/functional/SideEffect2.java +++ b/pitest/src/main/java/org/pitest/functional/SideEffect2.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional; - -/** - * @author henry - * - */ -public interface SideEffect2 { - - void apply(A a, B b); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional; + +/** + * @author henry + * + */ +public interface SideEffect2 { + + void apply(A a, B b); + +} diff --git a/pitest/src/main/java/org/pitest/functional/Streams.java b/pitest/src/main/java/org/pitest/functional/Streams.java index 42a21e3d0..66e6e3eec 100644 --- a/pitest/src/main/java/org/pitest/functional/Streams.java +++ b/pitest/src/main/java/org/pitest/functional/Streams.java @@ -1,13 +1,13 @@ -package org.pitest.functional; - -import java.util.stream.Stream; - -public class Streams { - public static Stream fromOptional(java.util.Optional opt) { - if (opt.isPresent()) { - return Stream.of(opt.get()); - } else { - return Stream.empty(); - } - } -} +package org.pitest.functional; + +import java.util.stream.Stream; + +public class Streams { + public static Stream fromOptional(java.util.Optional opt) { + if (opt.isPresent()) { + return Stream.of(opt.get()); + } else { + return Stream.empty(); + } + } +} diff --git a/pitest/src/main/java/org/pitest/functional/predicate/And.java b/pitest/src/main/java/org/pitest/functional/predicate/And.java index 6d2261f31..ac66af337 100644 --- a/pitest/src/main/java/org/pitest/functional/predicate/And.java +++ b/pitest/src/main/java/org/pitest/functional/predicate/And.java @@ -1,45 +1,45 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional.predicate; - -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.function.Predicate; - -/** - * @author henry - * - */ -public class And implements Predicate { - - private final Set> ps = new LinkedHashSet<>(); - - public And(final Iterable> ps) { - for (final Predicate each : ps) { - this.ps.add(each); - } - } - - @Override - public boolean test(final A a) { - for (final Predicate each : this.ps) { - if (!each.test(a)) { - return false; - } - } - return !this.ps.isEmpty(); - } - +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional.predicate; + +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.function.Predicate; + +/** + * @author henry + * + */ +public class And implements Predicate { + + private final Set> ps = new LinkedHashSet<>(); + + public And(final Iterable> ps) { + for (final Predicate each : ps) { + this.ps.add(each); + } + } + + @Override + public boolean test(final A a) { + for (final Predicate each : this.ps) { + if (!each.test(a)) { + return false; + } + } + return !this.ps.isEmpty(); + } + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/functional/predicate/False.java b/pitest/src/main/java/org/pitest/functional/predicate/False.java index 2be4750c8..32bcc003a 100644 --- a/pitest/src/main/java/org/pitest/functional/predicate/False.java +++ b/pitest/src/main/java/org/pitest/functional/predicate/False.java @@ -1,37 +1,37 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional.predicate; - -import java.util.function.Predicate; - -/** - * @author henry - * - */ -public class False implements Predicate { - - private static final False INSTANCE = new False<>(); - - @SuppressWarnings("unchecked") - public static False instance() { - return (False) INSTANCE; - } - - @Override - public boolean test(final A a) { - return false; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional.predicate; + +import java.util.function.Predicate; + +/** + * @author henry + * + */ +public class False implements Predicate { + + private static final False INSTANCE = new False<>(); + + @SuppressWarnings("unchecked") + public static False instance() { + return (False) INSTANCE; + } + + @Override + public boolean test(final A a) { + return false; + } + +} diff --git a/pitest/src/main/java/org/pitest/functional/predicate/Or.java b/pitest/src/main/java/org/pitest/functional/predicate/Or.java index 09f6f5298..5095fa0b1 100644 --- a/pitest/src/main/java/org/pitest/functional/predicate/Or.java +++ b/pitest/src/main/java/org/pitest/functional/predicate/Or.java @@ -1,45 +1,45 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional.predicate; - -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.function.Predicate; - -/** - * @author henry - * - */ -public class Or implements Predicate { - - private final Set> ps = new LinkedHashSet<>(); - - public Or(final Iterable> ps) { - for (final Predicate each : ps) { - this.ps.add(each); - } - } - - @Override - public boolean test(final A a) { - for (final Predicate each : this.ps) { - if (each.test(a)) { - return true; - } - } - return false; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional.predicate; + +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.function.Predicate; + +/** + * @author henry + * + */ +public class Or implements Predicate { + + private final Set> ps = new LinkedHashSet<>(); + + public Or(final Iterable> ps) { + for (final Predicate each : ps) { + this.ps.add(each); + } + } + + @Override + public boolean test(final A a) { + for (final Predicate each : this.ps) { + if (each.test(a)) { + return true; + } + } + return false; + } + +} diff --git a/pitest/src/main/java/org/pitest/functional/prelude/Prelude.java b/pitest/src/main/java/org/pitest/functional/prelude/Prelude.java index 85393e1a3..4cf7b307a 100644 --- a/pitest/src/main/java/org/pitest/functional/prelude/Prelude.java +++ b/pitest/src/main/java/org/pitest/functional/prelude/Prelude.java @@ -1,121 +1,121 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional.prelude; - -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.pitest.functional.SideEffect1; -import org.pitest.functional.predicate.And; -import org.pitest.functional.predicate.Or; - -/** - * @author henry - * - */ -public abstract class Prelude { - - @SafeVarargs - public static final And and(final Predicate... ps) { - return new And<>(Arrays.asList(ps)); - } - - public static final And and(final Iterable> ps) { - return new And<>(ps); - } - - public static final Predicate not(final Predicate p) { - return p.negate(); - } - - @SafeVarargs - public static final Or or(final Predicate... ps) { - return new Or<>(Arrays.asList(ps)); - } - - public static final Or or(final Iterable> ps) { - return new Or<>(ps); - } - - public static final SideEffect1 accumulateTo( - final Collection collection) { - return a -> collection.add(a); - - } - - public static SideEffect1 putToMap(final Map map, - final B value) { - return key -> map.put(key, value); - } - - public static final Function id() { - return a -> a; - } - - public static final Function id(final Class type) { - return id(); - } - - public static final SideEffect1 print() { - return printTo(System.out); - } - - public static final SideEffect1 print(final Class type) { - return print(); - } - - public static final SideEffect1 printTo(final Class type, - final PrintStream stream) { - return printTo(stream); - } - - public static final SideEffect1 printTo(final PrintStream stream) { - return a -> stream.print(a); - } - - public static SideEffect1 printWith(final T t) { - return a -> System.out.print(t + " : " + a); - } - - public static Predicate isGreaterThan(final T value) { - return o -> o.longValue() > value.longValue(); - } - - public static Predicate isEqualTo(final T value) { - return o -> o.equals(value); - } - - public static Predicate isNotNull() { - return o -> (o != null); - } - - public static Predicate isNull() { - return o -> (o == null); - } - - public static Function> asList(final Class type) { - return a -> Collections.singletonList(a); - } - - public static SideEffect1 noSideEffect(final Class clazz) { - return a -> { - }; - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional.prelude; + +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.pitest.functional.SideEffect1; +import org.pitest.functional.predicate.And; +import org.pitest.functional.predicate.Or; + +/** + * @author henry + * + */ +public abstract class Prelude { + + @SafeVarargs + public static final And and(final Predicate... ps) { + return new And<>(Arrays.asList(ps)); + } + + public static final And and(final Iterable> ps) { + return new And<>(ps); + } + + public static final Predicate not(final Predicate p) { + return p.negate(); + } + + @SafeVarargs + public static final Or or(final Predicate... ps) { + return new Or<>(Arrays.asList(ps)); + } + + public static final Or or(final Iterable> ps) { + return new Or<>(ps); + } + + public static final SideEffect1 accumulateTo( + final Collection collection) { + return a -> collection.add(a); + + } + + public static SideEffect1 putToMap(final Map map, + final B value) { + return key -> map.put(key, value); + } + + public static final Function id() { + return a -> a; + } + + public static final Function id(final Class type) { + return id(); + } + + public static final SideEffect1 print() { + return printTo(System.out); + } + + public static final SideEffect1 print(final Class type) { + return print(); + } + + public static final SideEffect1 printTo(final Class type, + final PrintStream stream) { + return printTo(stream); + } + + public static final SideEffect1 printTo(final PrintStream stream) { + return a -> stream.print(a); + } + + public static SideEffect1 printWith(final T t) { + return a -> System.out.print(t + " : " + a); + } + + public static Predicate isGreaterThan(final T value) { + return o -> o.longValue() > value.longValue(); + } + + public static Predicate isEqualTo(final T value) { + return o -> o.equals(value); + } + + public static Predicate isNotNull() { + return o -> (o != null); + } + + public static Predicate isNull() { + return o -> (o == null); + } + + public static Function> asList(final Class type) { + return a -> Collections.singletonList(a); + } + + public static SideEffect1 noSideEffect(final Class clazz) { + return a -> { + }; + } +} diff --git a/pitest/src/main/java/org/pitest/help/Help.java b/pitest/src/main/java/org/pitest/help/Help.java index 307193535..4b6339212 100644 --- a/pitest/src/main/java/org/pitest/help/Help.java +++ b/pitest/src/main/java/org/pitest/help/Help.java @@ -1,60 +1,60 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.help; - -public enum Help { - - NO_MUTATIONS_FOUND( - "No mutations found. This probably means there is an issue with either the supplied classpath or filters."), // - WRONG_JUNIT_VERSION( - "Unsupported JUnit version %s. PIT requires JUnit 4.6 or above."), // - FAILING_TESTS( - "All tests did not pass without mutation when calculating line coverage. Mutation testing requires a green suite."), // - NO_JUNIT( - "JUnit was not found on the classpath. PIT requires JUnit 4.6 or above."), // - NO_SOURCE_FILE( - "The class %s does not contain source debug information. All classes must have an associated source file"), // - NO_LINE_NUMBERS( - "No classes found with line number debug information. All classes should be compiled with source and line number debug information."), // - NO_TEST_LIBRARY( - "No test library found on classpath. PIT requires either JUnit 4 (but can run JUnit 3 tests) or TestNG"), // - BAD_FILTER( - "The supplied filter would cause PIT to try and mutate itself. This will lead to many wasted hours of confusion and debugging. You have better things to do with your life so please don't do this again."), // - UNKNOWN_MUTATOR( - "Mutator or group %s is unknown. Check PIT configuration and try again."), - NO_JUNIT_EXCLUDE_RUNNERS( - "Exclude Runners option requires JUnit 4.6 or above."); - - private static final String URL = "http://pitest.org"; - private final String text; - - Help(final String text) { - this.text = text; - } - - @Override - public String toString() { - return this.text + getLink(); - } - - private String getLink() { - return "\nSee " + URL + " for more details."; - } - - public String format(final Object... params) { - return String.format(this.toString(), params); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.help; + +public enum Help { + + NO_MUTATIONS_FOUND( + "No mutations found. This probably means there is an issue with either the supplied classpath or filters."), // + WRONG_JUNIT_VERSION( + "Unsupported JUnit version %s. PIT requires JUnit 4.6 or above."), // + FAILING_TESTS( + "All tests did not pass without mutation when calculating line coverage. Mutation testing requires a green suite."), // + NO_JUNIT( + "JUnit was not found on the classpath. PIT requires JUnit 4.6 or above."), // + NO_SOURCE_FILE( + "The class %s does not contain source debug information. All classes must have an associated source file"), // + NO_LINE_NUMBERS( + "No classes found with line number debug information. All classes should be compiled with source and line number debug information."), // + NO_TEST_LIBRARY( + "No test library found on classpath. PIT requires either JUnit 4 (but can run JUnit 3 tests) or TestNG"), // + BAD_FILTER( + "The supplied filter would cause PIT to try and mutate itself. This will lead to many wasted hours of confusion and debugging. You have better things to do with your life so please don't do this again."), // + UNKNOWN_MUTATOR( + "Mutator or group %s is unknown. Check PIT configuration and try again."), + NO_JUNIT_EXCLUDE_RUNNERS( + "Exclude Runners option requires JUnit 4.6 or above."); + + private static final String URL = "http://pitest.org"; + private final String text; + + Help(final String text) { + this.text = text; + } + + @Override + public String toString() { + return this.text + getLink(); + } + + private String getLink() { + return "\nSee " + URL + " for more details."; + } + + public String format(final Object... params) { + return String.format(this.toString(), params); + } + +} diff --git a/pitest/src/main/java/org/pitest/help/PitHelpError.java b/pitest/src/main/java/org/pitest/help/PitHelpError.java index 79d9a6f58..7cc912926 100644 --- a/pitest/src/main/java/org/pitest/help/PitHelpError.java +++ b/pitest/src/main/java/org/pitest/help/PitHelpError.java @@ -1,25 +1,25 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.help; - -public class PitHelpError extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public PitHelpError(final Help message, final Object... params) { - super(message.format(params)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.help; + +public class PitHelpError extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public PitHelpError(final Help message, final Object... params) { + super(message.format(params)); + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/CompoundTestUnitFinder.java b/pitest/src/main/java/org/pitest/junit/CompoundTestUnitFinder.java index 762ea0e91..3c918e618 100644 --- a/pitest/src/main/java/org/pitest/junit/CompoundTestUnitFinder.java +++ b/pitest/src/main/java/org/pitest/junit/CompoundTestUnitFinder.java @@ -1,28 +1,28 @@ -package org.pitest.junit; - -import java.util.Collections; -import java.util.List; - -import org.pitest.testapi.TestUnit; -import org.pitest.testapi.TestUnitFinder; - -public class CompoundTestUnitFinder implements TestUnitFinder { - - private final List tufs; - - public CompoundTestUnitFinder(final List tufs) { - this.tufs = tufs; - } - - @Override - public List findTestUnits(final Class clazz) { - for (final TestUnitFinder each : this.tufs) { - final List tus = each.findTestUnits(clazz); - if (!tus.isEmpty()) { - return tus; - } - } - return Collections.emptyList(); - } - -} +package org.pitest.junit; + +import java.util.Collections; +import java.util.List; + +import org.pitest.testapi.TestUnit; +import org.pitest.testapi.TestUnitFinder; + +public class CompoundTestUnitFinder implements TestUnitFinder { + + private final List tufs; + + public CompoundTestUnitFinder(final List tufs) { + this.tufs = tufs; + } + + @Override + public List findTestUnits(final Class clazz) { + for (final TestUnitFinder each : this.tufs) { + final List tus = each.findTestUnits(clazz); + if (!tus.isEmpty()) { + return tus; + } + } + return Collections.emptyList(); + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/DescriptionFilter.java b/pitest/src/main/java/org/pitest/junit/DescriptionFilter.java index 5f7459ef0..883a1856d 100644 --- a/pitest/src/main/java/org/pitest/junit/DescriptionFilter.java +++ b/pitest/src/main/java/org/pitest/junit/DescriptionFilter.java @@ -1,44 +1,44 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.junit; - -import org.junit.runner.Description; -import org.junit.runner.manipulation.Filter; - -public class DescriptionFilter extends Filter { - - private final String desc; - - public DescriptionFilter(final String description) { - this.desc = description; - } - - @Override - public boolean shouldRun(final Description description) { - return description.toString().equals(this.desc); - } - - @Override - public String describe() { - return this.desc; - } - - @Override - public String toString() { - return describe(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.junit; + +import org.junit.runner.Description; +import org.junit.runner.manipulation.Filter; + +public class DescriptionFilter extends Filter { + + private final String desc; + + public DescriptionFilter(final String description) { + this.desc = description; + } + + @Override + public boolean shouldRun(final Description description) { + return description.toString().equals(this.desc); + } + + @Override + public String describe() { + return this.desc; + } + + @Override + public String toString() { + return describe(); + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/JUnit4SuiteFinder.java b/pitest/src/main/java/org/pitest/junit/JUnit4SuiteFinder.java index 5aa6f6036..c8ac56005 100644 --- a/pitest/src/main/java/org/pitest/junit/JUnit4SuiteFinder.java +++ b/pitest/src/main/java/org/pitest/junit/JUnit4SuiteFinder.java @@ -1,48 +1,48 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.pitest.testapi.TestSuiteFinder; - -public class JUnit4SuiteFinder implements TestSuiteFinder { - - @Override - public List> apply(final Class a) { - final SuiteClasses annotation = a.getAnnotation(SuiteClasses.class); - - if ((annotation != null) && hasSuitableRunnner(a)) { - return Arrays.asList(annotation.value()); - } else { - return Collections.emptyList(); - } - } - - private boolean hasSuitableRunnner(final Class clazz) { - - final RunWith runWith = clazz.getAnnotation(RunWith.class); - if (runWith != null) { - return (runWith.value().equals(Suite.class)); - } - return false; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.pitest.testapi.TestSuiteFinder; + +public class JUnit4SuiteFinder implements TestSuiteFinder { + + @Override + public List> apply(final Class a) { + final SuiteClasses annotation = a.getAnnotation(SuiteClasses.class); + + if ((annotation != null) && hasSuitableRunnner(a)) { + return Arrays.asList(annotation.value()); + } else { + return Collections.emptyList(); + } + } + + private boolean hasSuitableRunnner(final Class clazz) { + + final RunWith runWith = clazz.getAnnotation(RunWith.class); + if (runWith != null) { + return (runWith.value().equals(Suite.class)); + } + return false; + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/JUnitCompatibleConfiguration.java b/pitest/src/main/java/org/pitest/junit/JUnitCompatibleConfiguration.java index f31feb645..f87a66d50 100644 --- a/pitest/src/main/java/org/pitest/junit/JUnitCompatibleConfiguration.java +++ b/pitest/src/main/java/org/pitest/junit/JUnitCompatibleConfiguration.java @@ -1,83 +1,83 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import java.util.Arrays; -import java.util.Collection; - -import org.pitest.extension.common.CompoundTestSuiteFinder; -import java.util.Optional; -import org.pitest.help.Help; -import org.pitest.help.PitHelpError; -import org.pitest.testapi.Configuration; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.testapi.TestSuiteFinder; -import org.pitest.testapi.TestUnitFinder; -import org.pitest.util.Preconditions; - -public class JUnitCompatibleConfiguration implements Configuration { - - private final TestGroupConfig config; - private final Collection excludedRunners; - private final Collection includedTestMethods; - - private static final JUnitVersion MIN_JUNIT_VERSION = JUnitVersion.parse("4.6"); - - public JUnitCompatibleConfiguration(TestGroupConfig config, Collection excludedRunners, - Collection includedTestMethods) { - Preconditions.checkNotNull(config); - this.config = config; - this.excludedRunners = excludedRunners; - this.includedTestMethods = includedTestMethods; - } - - @Override - public TestUnitFinder testUnitFinder() { - return new CompoundTestUnitFinder(Arrays.asList( - new JUnitCustomRunnerTestUnitFinder(this.config, this.excludedRunners, this.includedTestMethods), - new ParameterisedJUnitTestFinder())); - } - - @Override - public TestSuiteFinder testSuiteFinder() { - return new CompoundTestSuiteFinder(Arrays. asList( - new JUnit4SuiteFinder(), new RunnerSuiteFinder())); - } - - - @Override - public Optional verifyEnvironment() { - try { - final String version = junit.runner.Version.id(); - if (isInvalidVersion(version)) { - return Optional.ofNullable(new PitHelpError(Help.WRONG_JUNIT_VERSION, version)); - } - } catch (final NoClassDefFoundError er) { - return Optional.ofNullable(new PitHelpError(Help.NO_JUNIT)); - } - - return Optional.empty(); - } - - boolean isInvalidVersion(final String version) { - try { - final JUnitVersion jUnitVersion = JUnitVersion.parse(version); - return jUnitVersion.isLessThan(MIN_JUNIT_VERSION); - } catch (final IllegalArgumentException e) { - return true; - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import java.util.Arrays; +import java.util.Collection; + +import org.pitest.extension.common.CompoundTestSuiteFinder; +import java.util.Optional; +import org.pitest.help.Help; +import org.pitest.help.PitHelpError; +import org.pitest.testapi.Configuration; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.testapi.TestSuiteFinder; +import org.pitest.testapi.TestUnitFinder; +import org.pitest.util.Preconditions; + +public class JUnitCompatibleConfiguration implements Configuration { + + private final TestGroupConfig config; + private final Collection excludedRunners; + private final Collection includedTestMethods; + + private static final JUnitVersion MIN_JUNIT_VERSION = JUnitVersion.parse("4.6"); + + public JUnitCompatibleConfiguration(TestGroupConfig config, Collection excludedRunners, + Collection includedTestMethods) { + Preconditions.checkNotNull(config); + this.config = config; + this.excludedRunners = excludedRunners; + this.includedTestMethods = includedTestMethods; + } + + @Override + public TestUnitFinder testUnitFinder() { + return new CompoundTestUnitFinder(Arrays.asList( + new JUnitCustomRunnerTestUnitFinder(this.config, this.excludedRunners, this.includedTestMethods), + new ParameterisedJUnitTestFinder())); + } + + @Override + public TestSuiteFinder testSuiteFinder() { + return new CompoundTestSuiteFinder(Arrays. asList( + new JUnit4SuiteFinder(), new RunnerSuiteFinder())); + } + + + @Override + public Optional verifyEnvironment() { + try { + final String version = junit.runner.Version.id(); + if (isInvalidVersion(version)) { + return Optional.ofNullable(new PitHelpError(Help.WRONG_JUNIT_VERSION, version)); + } + } catch (final NoClassDefFoundError er) { + return Optional.ofNullable(new PitHelpError(Help.NO_JUNIT)); + } + + return Optional.empty(); + } + + boolean isInvalidVersion(final String version) { + try { + final JUnitVersion jUnitVersion = JUnitVersion.parse(version); + return jUnitVersion.isLessThan(MIN_JUNIT_VERSION); + } catch (final IllegalArgumentException e) { + return true; + } + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/JUnitCustomRunnerTestUnitFinder.java b/pitest/src/main/java/org/pitest/junit/JUnitCustomRunnerTestUnitFinder.java index 72f97a658..e7a11d238 100644 --- a/pitest/src/main/java/org/pitest/junit/JUnitCustomRunnerTestUnitFinder.java +++ b/pitest/src/main/java/org/pitest/junit/JUnitCustomRunnerTestUnitFinder.java @@ -1,242 +1,242 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.experimental.categories.Category; -import org.junit.internal.runners.ErrorReportingRunner; -import org.junit.runner.Description; -import org.junit.runner.Runner; -import org.junit.runner.manipulation.Filter; -import org.junit.runner.manipulation.Filterable; -import org.junit.runners.Parameterized; -import org.pitest.functional.FCollection; -import org.pitest.junit.adapter.AdaptedJUnitTestUnit; -import org.pitest.reflection.IsAnnotatedWith; -import org.pitest.reflection.Reflection; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.testapi.TestUnit; -import org.pitest.testapi.TestUnitFinder; -import org.pitest.util.IsolationUtils; -import org.pitest.util.Preconditions; - -public class JUnitCustomRunnerTestUnitFinder implements TestUnitFinder { - - @SuppressWarnings("rawtypes") - private static final Optional CLASS_RULE = findClassRuleClass(); - - - private final TestGroupConfig config; - private final Collection excludedRunners; - private final Collection includedTestMethods; - - JUnitCustomRunnerTestUnitFinder(TestGroupConfig config, final Collection excludedRunners, - final Collection includedTestMethods) { - Preconditions.checkNotNull(config); - this.config = config; - this.excludedRunners = excludedRunners; - this.includedTestMethods = includedTestMethods; - } - - @Override - public List findTestUnits(final Class clazz) { - - final Runner runner = AdaptedJUnitTestUnit.createRunner(clazz); - - if (isExcluded(runner) || isNotARunnableTest(runner, clazz.getName()) || !isIncluded(clazz)) { - return Collections.emptyList(); - } - - if (Filterable.class.isAssignableFrom(runner.getClass()) - && !shouldTreatAsOneUnit(clazz, runner)) { - final List filteredUnits = splitIntoFilteredUnits(runner.getDescription()); - return filterUnitsByMethod(filteredUnits); - } else { - return Collections. singletonList(new AdaptedJUnitTestUnit( - clazz, Optional. empty())); - } - } - - private List filterUnitsByMethod(List filteredUnits) { - if (this.includedTestMethods.isEmpty()) { - return filteredUnits; - } - - final List units = new ArrayList<>(); - for (final TestUnit unit: filteredUnits) { - if (this.includedTestMethods.contains(unit.getDescription().getName().split("\\(")[0])) { - units.add(unit); - } - } - return units; - } - - private boolean isExcluded(Runner runner) { - return this.excludedRunners.contains(runner.getClass().getName()); - } - - private boolean isIncluded(final Class a) { - return isIncludedCategory(a) && !isExcludedCategory(a); - } - - - private boolean isIncludedCategory(final Class a) { - final List included = this.config.getIncludedGroups(); - return included.isEmpty() || !Collections.disjoint(included, getCategories(a)); - } - - private boolean isExcludedCategory(final Class a) { - final List excluded = this.config.getExcludedGroups(); - return !excluded.isEmpty() && !Collections.disjoint(excluded, getCategories(a)); - } - - private List getCategories(final Class a) { - final Category c = a.getAnnotation(Category.class); - return FCollection.flatMap(Arrays.asList(c), toCategoryNames()); - } - - private Function> toCategoryNames() { - return a -> { - if (a == null) { - return Collections.emptyList(); - } - return FCollection.map(Arrays.asList(a.value()),toName()); - }; - } - - private Function,String> toName() { - return a -> a.getName(); - } - - private boolean isNotARunnableTest(final Runner runner, - final String className) { - try { - return (runner == null) - || runner.getClass().isAssignableFrom(ErrorReportingRunner.class) - || isParameterizedTest(runner) - || isAJUnitThreeErrorOrWarning(runner) - || isJUnitThreeSuiteMethodNotForOwnClass(runner, className); - } catch (final RuntimeException ex) { - // some runners (looking at you spock) can throw a runtime exception - // when the getDescription method is called - return true; - } - } - - private boolean isAJUnitThreeErrorOrWarning(final Runner runner) { - return !runner.getDescription().getChildren().isEmpty() - && runner.getDescription().getChildren().get(0).getClassName() - .startsWith("junit.framework.TestSuite"); - } - - private boolean shouldTreatAsOneUnit(final Class clazz, final Runner runner) { - final Set methods = Reflection.allMethods(clazz); - return runnerCannotBeSplit(runner) - || hasAnnotation(methods, BeforeClass.class) - || hasAnnotation(methods, AfterClass.class) - || hasClassRuleAnnotations(clazz, methods); - } - - private boolean hasClassRuleAnnotations(final Class clazz, - final Set methods) { - if (!CLASS_RULE.isPresent()) { - return false; - } - - return hasAnnotation(methods, CLASS_RULE.get()) - || hasAnnotation(Reflection.publicFields(clazz), CLASS_RULE.get()); - } - - private boolean hasAnnotation(final Set methods, - final Class annotation) { - return FCollection.contains(methods, IsAnnotatedWith.instance(annotation)); - } - - private boolean isParameterizedTest(final Runner runner) { - return Parameterized.class.isAssignableFrom(runner.getClass()); - } - - private boolean runnerCannotBeSplit(final Runner runner) { - final String runnerName = runner.getClass().getName(); - return runnerName.equals("junitparams.JUnitParamsRunner") - || runnerName.startsWith("org.spockframework.runtime.Sputnik") - || runnerName.startsWith("com.insightfullogic.lambdabehave") - || runnerName.startsWith("com.googlecode.yatspec") - || runnerName.startsWith("com.google.gwtmockito.GwtMockitoTestRunner"); - } - - private boolean isJUnitThreeSuiteMethodNotForOwnClass(final Runner runner, - final String className) { - // use strings in case this hack blows up due to internal junit change - return runner.getClass().getName() - .equals("org.junit.internal.runners.SuiteMethod") - && !runner.getDescription().getClassName().equals(className); - } - - private List splitIntoFilteredUnits(final Description description) { - return description.getChildren().stream() - .filter(isTest()) - .map(descriptionToTestUnit()) - .collect(Collectors.toList()); - } - - private Function descriptionToTestUnit() { - return a -> descriptionToTest(a); - } - - private Predicate isTest() { - return a -> a.isTest(); - } - - private TestUnit descriptionToTest(final Description description) { - - Class clazz = description.getTestClass(); - if (clazz == null) { - clazz = IsolationUtils.convertForClassLoader( - IsolationUtils.getContextClassLoader(), description.getClassName()); - } - return new AdaptedJUnitTestUnit(clazz, - Optional.ofNullable(createFilterFor(description))); - } - - private Filter createFilterFor(final Description description) { - return new DescriptionFilter(description.toString()); - } - - @SuppressWarnings("rawtypes") - private static Optional findClassRuleClass() { - try { - return Optional. ofNullable(Class.forName("org.junit.ClassRule")); - } catch (final ClassNotFoundException ex) { - return Optional.empty(); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.experimental.categories.Category; +import org.junit.internal.runners.ErrorReportingRunner; +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.junit.runner.manipulation.Filter; +import org.junit.runner.manipulation.Filterable; +import org.junit.runners.Parameterized; +import org.pitest.functional.FCollection; +import org.pitest.junit.adapter.AdaptedJUnitTestUnit; +import org.pitest.reflection.IsAnnotatedWith; +import org.pitest.reflection.Reflection; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.testapi.TestUnit; +import org.pitest.testapi.TestUnitFinder; +import org.pitest.util.IsolationUtils; +import org.pitest.util.Preconditions; + +public class JUnitCustomRunnerTestUnitFinder implements TestUnitFinder { + + @SuppressWarnings("rawtypes") + private static final Optional CLASS_RULE = findClassRuleClass(); + + + private final TestGroupConfig config; + private final Collection excludedRunners; + private final Collection includedTestMethods; + + JUnitCustomRunnerTestUnitFinder(TestGroupConfig config, final Collection excludedRunners, + final Collection includedTestMethods) { + Preconditions.checkNotNull(config); + this.config = config; + this.excludedRunners = excludedRunners; + this.includedTestMethods = includedTestMethods; + } + + @Override + public List findTestUnits(final Class clazz) { + + final Runner runner = AdaptedJUnitTestUnit.createRunner(clazz); + + if (isExcluded(runner) || isNotARunnableTest(runner, clazz.getName()) || !isIncluded(clazz)) { + return Collections.emptyList(); + } + + if (Filterable.class.isAssignableFrom(runner.getClass()) + && !shouldTreatAsOneUnit(clazz, runner)) { + final List filteredUnits = splitIntoFilteredUnits(runner.getDescription()); + return filterUnitsByMethod(filteredUnits); + } else { + return Collections. singletonList(new AdaptedJUnitTestUnit( + clazz, Optional. empty())); + } + } + + private List filterUnitsByMethod(List filteredUnits) { + if (this.includedTestMethods.isEmpty()) { + return filteredUnits; + } + + final List units = new ArrayList<>(); + for (final TestUnit unit: filteredUnits) { + if (this.includedTestMethods.contains(unit.getDescription().getName().split("\\(")[0])) { + units.add(unit); + } + } + return units; + } + + private boolean isExcluded(Runner runner) { + return this.excludedRunners.contains(runner.getClass().getName()); + } + + private boolean isIncluded(final Class a) { + return isIncludedCategory(a) && !isExcludedCategory(a); + } + + + private boolean isIncludedCategory(final Class a) { + final List included = this.config.getIncludedGroups(); + return included.isEmpty() || !Collections.disjoint(included, getCategories(a)); + } + + private boolean isExcludedCategory(final Class a) { + final List excluded = this.config.getExcludedGroups(); + return !excluded.isEmpty() && !Collections.disjoint(excluded, getCategories(a)); + } + + private List getCategories(final Class a) { + final Category c = a.getAnnotation(Category.class); + return FCollection.flatMap(Arrays.asList(c), toCategoryNames()); + } + + private Function> toCategoryNames() { + return a -> { + if (a == null) { + return Collections.emptyList(); + } + return FCollection.map(Arrays.asList(a.value()),toName()); + }; + } + + private Function,String> toName() { + return a -> a.getName(); + } + + private boolean isNotARunnableTest(final Runner runner, + final String className) { + try { + return (runner == null) + || runner.getClass().isAssignableFrom(ErrorReportingRunner.class) + || isParameterizedTest(runner) + || isAJUnitThreeErrorOrWarning(runner) + || isJUnitThreeSuiteMethodNotForOwnClass(runner, className); + } catch (final RuntimeException ex) { + // some runners (looking at you spock) can throw a runtime exception + // when the getDescription method is called + return true; + } + } + + private boolean isAJUnitThreeErrorOrWarning(final Runner runner) { + return !runner.getDescription().getChildren().isEmpty() + && runner.getDescription().getChildren().get(0).getClassName() + .startsWith("junit.framework.TestSuite"); + } + + private boolean shouldTreatAsOneUnit(final Class clazz, final Runner runner) { + final Set methods = Reflection.allMethods(clazz); + return runnerCannotBeSplit(runner) + || hasAnnotation(methods, BeforeClass.class) + || hasAnnotation(methods, AfterClass.class) + || hasClassRuleAnnotations(clazz, methods); + } + + private boolean hasClassRuleAnnotations(final Class clazz, + final Set methods) { + if (!CLASS_RULE.isPresent()) { + return false; + } + + return hasAnnotation(methods, CLASS_RULE.get()) + || hasAnnotation(Reflection.publicFields(clazz), CLASS_RULE.get()); + } + + private boolean hasAnnotation(final Set methods, + final Class annotation) { + return FCollection.contains(methods, IsAnnotatedWith.instance(annotation)); + } + + private boolean isParameterizedTest(final Runner runner) { + return Parameterized.class.isAssignableFrom(runner.getClass()); + } + + private boolean runnerCannotBeSplit(final Runner runner) { + final String runnerName = runner.getClass().getName(); + return runnerName.equals("junitparams.JUnitParamsRunner") + || runnerName.startsWith("org.spockframework.runtime.Sputnik") + || runnerName.startsWith("com.insightfullogic.lambdabehave") + || runnerName.startsWith("com.googlecode.yatspec") + || runnerName.startsWith("com.google.gwtmockito.GwtMockitoTestRunner"); + } + + private boolean isJUnitThreeSuiteMethodNotForOwnClass(final Runner runner, + final String className) { + // use strings in case this hack blows up due to internal junit change + return runner.getClass().getName() + .equals("org.junit.internal.runners.SuiteMethod") + && !runner.getDescription().getClassName().equals(className); + } + + private List splitIntoFilteredUnits(final Description description) { + return description.getChildren().stream() + .filter(isTest()) + .map(descriptionToTestUnit()) + .collect(Collectors.toList()); + } + + private Function descriptionToTestUnit() { + return a -> descriptionToTest(a); + } + + private Predicate isTest() { + return a -> a.isTest(); + } + + private TestUnit descriptionToTest(final Description description) { + + Class clazz = description.getTestClass(); + if (clazz == null) { + clazz = IsolationUtils.convertForClassLoader( + IsolationUtils.getContextClassLoader(), description.getClassName()); + } + return new AdaptedJUnitTestUnit(clazz, + Optional.ofNullable(createFilterFor(description))); + } + + private Filter createFilterFor(final Description description) { + return new DescriptionFilter(description.toString()); + } + + @SuppressWarnings("rawtypes") + private static Optional findClassRuleClass() { + try { + return Optional. ofNullable(Class.forName("org.junit.ClassRule")); + } catch (final ClassNotFoundException ex) { + return Optional.empty(); + } + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/JUnitTestPlugin.java b/pitest/src/main/java/org/pitest/junit/JUnitTestPlugin.java index 91f28e913..e750af3ff 100644 --- a/pitest/src/main/java/org/pitest/junit/JUnitTestPlugin.java +++ b/pitest/src/main/java/org/pitest/junit/JUnitTestPlugin.java @@ -1,46 +1,46 @@ -package org.pitest.junit; - -import java.util.Collection; - -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.testapi.Configuration; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.testapi.TestPluginFactory; -import org.pitest.util.Preconditions; - -/** - * Plugin that provides support for both JUnit 3, 4 - * - * This plugin has been battle tested against many different strange uses and - * abuses of JUnit found in real world code bases. - * - * It will probably work well on your legacy code base but some of the code is - * pretty hairy, so support for more modern test frameworks will likely be added - * via different plugins. - * - * Much of the complexity comes from splitting the tests down into smaller - * units. - * - */ -public class JUnitTestPlugin implements TestPluginFactory { - - public static final String NAME = "junit"; - - @Override - public String description() { - return "JUnit plugin"; - } - - @Override - public Configuration createTestFrameworkConfiguration(TestGroupConfig config, - ClassByteArraySource source, Collection excludedRunners, Collection includedTestMethods) { - Preconditions.checkNotNull(config); - return new JUnitCompatibleConfiguration(config, excludedRunners, includedTestMethods); - } - - @Override - public String name() { - return NAME; - } - -} +package org.pitest.junit; + +import java.util.Collection; + +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.testapi.Configuration; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.testapi.TestPluginFactory; +import org.pitest.util.Preconditions; + +/** + * Plugin that provides support for both JUnit 3, 4 + * + * This plugin has been battle tested against many different strange uses and + * abuses of JUnit found in real world code bases. + * + * It will probably work well on your legacy code base but some of the code is + * pretty hairy, so support for more modern test frameworks will likely be added + * via different plugins. + * + * Much of the complexity comes from splitting the tests down into smaller + * units. + * + */ +public class JUnitTestPlugin implements TestPluginFactory { + + public static final String NAME = "junit"; + + @Override + public String description() { + return "JUnit plugin"; + } + + @Override + public Configuration createTestFrameworkConfiguration(TestGroupConfig config, + ClassByteArraySource source, Collection excludedRunners, Collection includedTestMethods) { + Preconditions.checkNotNull(config); + return new JUnitCompatibleConfiguration(config, excludedRunners, includedTestMethods); + } + + @Override + public String name() { + return NAME; + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/JUnitVersion.java b/pitest/src/main/java/org/pitest/junit/JUnitVersion.java index 1f678b664..f66b04c1f 100644 --- a/pitest/src/main/java/org/pitest/junit/JUnitVersion.java +++ b/pitest/src/main/java/org/pitest/junit/JUnitVersion.java @@ -1,96 +1,96 @@ -package org.pitest.junit; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public final class JUnitVersion implements Comparable { - - private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+)\\.(\\d+).*"); - - public static JUnitVersion parse(final String version) { - final Matcher matcher = VERSION_PATTERN.matcher(version); - - if (!matcher.matches()) { - throw new IllegalArgumentException("Invalid version string! Could not parse " + version); - } - - final int major = Integer.parseInt(matcher.group(1)); - final int minor = Integer.parseInt(matcher.group(2)); - - return new JUnitVersion(major, minor); - } - - private final int major; - - private final int minor; - - private JUnitVersion(final int major, final int minor) { - this.major = major; - this.minor = minor; - } - - @Override - public int compareTo(final JUnitVersion that) { - - if (that == null) { - return 1; - } - - if (this.major != that.major) { - return this.major - that.major; - } - - if (this.minor != that.minor) { - return this.minor - that.minor; - } - - return 0; - } - - public boolean is(final JUnitVersion version) { - return equals(version); - } - - public boolean isGreaterThan(final JUnitVersion version) { - return compareTo(version) > 0; - } - - public boolean isGreaterThanOrEqualTo(final JUnitVersion version) { - return compareTo(version) >= 0; - } - - public boolean isLessThan(final JUnitVersion version) { - return compareTo(version) < 0; - } - - public boolean isLessThanOrEqualTo(final JUnitVersion version) { - return compareTo(version) <= 0; - } - - @Override - public int hashCode() { - int result = this.major; - result = (31 * result) + this.minor; - return result; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (!(o instanceof JUnitVersion)) { - return false; - } - - final JUnitVersion that = (JUnitVersion) o; - - return (this.major == that.major) && (this.minor == that.minor); - - } - - @Override - public String toString() { - return this.major + "." + this.minor; - } -} +package org.pitest.junit; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class JUnitVersion implements Comparable { + + private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+)\\.(\\d+).*"); + + public static JUnitVersion parse(final String version) { + final Matcher matcher = VERSION_PATTERN.matcher(version); + + if (!matcher.matches()) { + throw new IllegalArgumentException("Invalid version string! Could not parse " + version); + } + + final int major = Integer.parseInt(matcher.group(1)); + final int minor = Integer.parseInt(matcher.group(2)); + + return new JUnitVersion(major, minor); + } + + private final int major; + + private final int minor; + + private JUnitVersion(final int major, final int minor) { + this.major = major; + this.minor = minor; + } + + @Override + public int compareTo(final JUnitVersion that) { + + if (that == null) { + return 1; + } + + if (this.major != that.major) { + return this.major - that.major; + } + + if (this.minor != that.minor) { + return this.minor - that.minor; + } + + return 0; + } + + public boolean is(final JUnitVersion version) { + return equals(version); + } + + public boolean isGreaterThan(final JUnitVersion version) { + return compareTo(version) > 0; + } + + public boolean isGreaterThanOrEqualTo(final JUnitVersion version) { + return compareTo(version) >= 0; + } + + public boolean isLessThan(final JUnitVersion version) { + return compareTo(version) < 0; + } + + public boolean isLessThanOrEqualTo(final JUnitVersion version) { + return compareTo(version) <= 0; + } + + @Override + public int hashCode() { + int result = this.major; + result = (31 * result) + this.minor; + return result; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof JUnitVersion)) { + return false; + } + + final JUnitVersion that = (JUnitVersion) o; + + return (this.major == that.major) && (this.minor == that.minor); + + } + + @Override + public String toString() { + return this.major + "." + this.minor; + } +} diff --git a/pitest/src/main/java/org/pitest/junit/ParameterisedJUnitTestFinder.java b/pitest/src/main/java/org/pitest/junit/ParameterisedJUnitTestFinder.java index 141bb56df..0a76acd71 100644 --- a/pitest/src/main/java/org/pitest/junit/ParameterisedJUnitTestFinder.java +++ b/pitest/src/main/java/org/pitest/junit/ParameterisedJUnitTestFinder.java @@ -1,70 +1,70 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; - -import org.junit.internal.runners.ErrorReportingRunner; -import org.junit.runner.Description; -import org.junit.runner.Runner; -import org.junit.runner.manipulation.Filter; -import org.junit.runners.Parameterized; -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.junit.adapter.AdaptedJUnitTestUnit; -import org.pitest.testapi.TestUnit; -import org.pitest.testapi.TestUnitFinder; - -public class ParameterisedJUnitTestFinder implements TestUnitFinder { - @Override - public List findTestUnits(final Class clazz) { - - final Runner runner = AdaptedJUnitTestUnit.createRunner(clazz); - if ((runner == null) - || runner.getClass().isAssignableFrom(ErrorReportingRunner.class)) { - return Collections.emptyList(); - } - - if (isParameterizedTest(runner)) { - return handleParameterizedTest(clazz, runner.getDescription()); - } - - return Collections.emptyList(); - - } - - private List handleParameterizedTest(final Class clazz, - final Description description) { - final List result = new ArrayList<>(); - for (final Description each : description.getChildren()) { - FCollection.mapTo(each.getChildren(), parameterizedToTestUnit(clazz), - result); - } - return result; - } - - private Function parameterizedToTestUnit(final Class clazz) { - return a -> new AdaptedJUnitTestUnit(clazz, - Optional. ofNullable(new ParameterisedTestFilter(a.toString()))); - } - - private boolean isParameterizedTest(final Runner runner) { - return Parameterized.class.isAssignableFrom(runner.getClass()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; + +import org.junit.internal.runners.ErrorReportingRunner; +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.junit.runner.manipulation.Filter; +import org.junit.runners.Parameterized; +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.junit.adapter.AdaptedJUnitTestUnit; +import org.pitest.testapi.TestUnit; +import org.pitest.testapi.TestUnitFinder; + +public class ParameterisedJUnitTestFinder implements TestUnitFinder { + @Override + public List findTestUnits(final Class clazz) { + + final Runner runner = AdaptedJUnitTestUnit.createRunner(clazz); + if ((runner == null) + || runner.getClass().isAssignableFrom(ErrorReportingRunner.class)) { + return Collections.emptyList(); + } + + if (isParameterizedTest(runner)) { + return handleParameterizedTest(clazz, runner.getDescription()); + } + + return Collections.emptyList(); + + } + + private List handleParameterizedTest(final Class clazz, + final Description description) { + final List result = new ArrayList<>(); + for (final Description each : description.getChildren()) { + FCollection.mapTo(each.getChildren(), parameterizedToTestUnit(clazz), + result); + } + return result; + } + + private Function parameterizedToTestUnit(final Class clazz) { + return a -> new AdaptedJUnitTestUnit(clazz, + Optional. ofNullable(new ParameterisedTestFilter(a.toString()))); + } + + private boolean isParameterizedTest(final Runner runner) { + return Parameterized.class.isAssignableFrom(runner.getClass()); + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/ParameterisedTestFilter.java b/pitest/src/main/java/org/pitest/junit/ParameterisedTestFilter.java index f94d16818..2af25eefa 100644 --- a/pitest/src/main/java/org/pitest/junit/ParameterisedTestFilter.java +++ b/pitest/src/main/java/org/pitest/junit/ParameterisedTestFilter.java @@ -1,40 +1,40 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import org.junit.runner.Description; -import org.junit.runner.manipulation.Filter; - -public class ParameterisedTestFilter extends Filter { - private final String desc; - private final String parent; - - ParameterisedTestFilter(final String desc) { - this.desc = desc; - this.parent = desc.substring(desc.indexOf('['), desc.indexOf(']') + 1); - } - - @Override - public String describe() { - return this.desc; - } - - @Override - public boolean shouldRun(final Description description) { - return description.toString().equals(this.desc) - || description.toString().equals(this.parent); - } - +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import org.junit.runner.Description; +import org.junit.runner.manipulation.Filter; + +public class ParameterisedTestFilter extends Filter { + private final String desc; + private final String parent; + + ParameterisedTestFilter(final String desc) { + this.desc = desc; + this.parent = desc.substring(desc.indexOf('['), desc.indexOf(']') + 1); + } + + @Override + public String describe() { + return this.desc; + } + + @Override + public boolean shouldRun(final Description description) { + return description.toString().equals(this.desc) + || description.toString().equals(this.parent); + } + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/junit/RunnerSuiteFinder.java b/pitest/src/main/java/org/pitest/junit/RunnerSuiteFinder.java index 5fb60a1bd..c5c7c4030 100644 --- a/pitest/src/main/java/org/pitest/junit/RunnerSuiteFinder.java +++ b/pitest/src/main/java/org/pitest/junit/RunnerSuiteFinder.java @@ -1,86 +1,86 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.junit; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.junit.internal.runners.SuiteMethod; -import org.junit.runner.Description; -import org.junit.runner.Runner; -import org.pitest.functional.FCollection; -import org.pitest.functional.prelude.Prelude; -import org.pitest.junit.adapter.AdaptedJUnitTestUnit; -import org.pitest.testapi.TestSuiteFinder; - -public class RunnerSuiteFinder implements TestSuiteFinder { - - @Override - public List> apply(final Class a) { - try { - final Runner runner = AdaptedJUnitTestUnit.createRunner(a); - - final List allChildren = new ArrayList<>(); - flattenChildren(allChildren, runner.getDescription()); - - final List suites = FCollection.filter(allChildren, - Prelude.or(isSuiteMethodRunner(runner), isSuite())); - final Set> classes = suites.stream().flatMap(descriptionToTestClass()).collect(Collectors.toSet()); - - classes.remove(a); - return new ArrayList<>(classes); - } catch (final RuntimeException ex) { - // some runners (looking at you spock) can throw a runtime exception - // when the getDescription method is called. - return Collections.emptyList(); - } - - } - - private void flattenChildren(final List allChildren, - final Description description) { - for (final Description each : description.getChildren()) { - allChildren.add(each); - flattenChildren(allChildren, each); - } - } - - private static Predicate isSuiteMethodRunner(final Runner runner) { - return a -> SuiteMethod.class.isAssignableFrom(runner.getClass()); - } - - private static Function>> descriptionToTestClass() { - return a -> { - final Class clazz = a.getTestClass(); - if (clazz != null) { - return Stream.of(clazz); - } else { - return Stream.empty(); - } - }; - } - - private static Predicate isSuite() { - return a -> a.isSuite(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.junit; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.internal.runners.SuiteMethod; +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.pitest.functional.FCollection; +import org.pitest.functional.prelude.Prelude; +import org.pitest.junit.adapter.AdaptedJUnitTestUnit; +import org.pitest.testapi.TestSuiteFinder; + +public class RunnerSuiteFinder implements TestSuiteFinder { + + @Override + public List> apply(final Class a) { + try { + final Runner runner = AdaptedJUnitTestUnit.createRunner(a); + + final List allChildren = new ArrayList<>(); + flattenChildren(allChildren, runner.getDescription()); + + final List suites = FCollection.filter(allChildren, + Prelude.or(isSuiteMethodRunner(runner), isSuite())); + final Set> classes = suites.stream().flatMap(descriptionToTestClass()).collect(Collectors.toSet()); + + classes.remove(a); + return new ArrayList<>(classes); + } catch (final RuntimeException ex) { + // some runners (looking at you spock) can throw a runtime exception + // when the getDescription method is called. + return Collections.emptyList(); + } + + } + + private void flattenChildren(final List allChildren, + final Description description) { + for (final Description each : description.getChildren()) { + allChildren.add(each); + flattenChildren(allChildren, each); + } + } + + private static Predicate isSuiteMethodRunner(final Runner runner) { + return a -> SuiteMethod.class.isAssignableFrom(runner.getClass()); + } + + private static Function>> descriptionToTestClass() { + return a -> { + final Class clazz = a.getTestClass(); + if (clazz != null) { + return Stream.of(clazz); + } else { + return Stream.empty(); + } + }; + } + + private static Predicate isSuite() { + return a -> a.isSuite(); + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/TestInfo.java b/pitest/src/main/java/org/pitest/junit/TestInfo.java index 92982c3f2..2df4a199f 100644 --- a/pitest/src/main/java/org/pitest/junit/TestInfo.java +++ b/pitest/src/main/java/org/pitest/junit/TestInfo.java @@ -1,60 +1,60 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import java.util.function.Predicate; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.pitest.classinfo.ClassInfo; -import java.util.Optional; - -abstract class TestInfo { - - public static boolean isWithinATestClass(final ClassInfo clazz) { - - final Optional outerClass = clazz.getOuterClass(); - return isATest(clazz) - || (outerClass.isPresent() && isATest(outerClass.get())); - - } - - private static boolean isATest(final ClassInfo clazz) { - return isJUnit3Test(clazz) || isJUnit4Test(clazz) - || isATest(clazz.getSuperClass()); - } - - private static boolean isATest(final Optional clazz) { - if (clazz.isPresent()) { - return isATest(clazz.get()); - } - return false; - } - - public static Predicate isATest() { - return clazz -> isATest(clazz); - } - - private static boolean isJUnit3Test(final ClassInfo clazz) { - return clazz.descendsFrom(junit.framework.TestCase.class) - || clazz.descendsFrom(junit.framework.TestSuite.class); - } - - private static boolean isJUnit4Test(final ClassInfo clazz) { - return clazz.hasAnnotation(RunWith.class) - || clazz.hasAnnotation(Test.class); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import java.util.function.Predicate; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.pitest.classinfo.ClassInfo; +import java.util.Optional; + +abstract class TestInfo { + + public static boolean isWithinATestClass(final ClassInfo clazz) { + + final Optional outerClass = clazz.getOuterClass(); + return isATest(clazz) + || (outerClass.isPresent() && isATest(outerClass.get())); + + } + + private static boolean isATest(final ClassInfo clazz) { + return isJUnit3Test(clazz) || isJUnit4Test(clazz) + || isATest(clazz.getSuperClass()); + } + + private static boolean isATest(final Optional clazz) { + if (clazz.isPresent()) { + return isATest(clazz.get()); + } + return false; + } + + public static Predicate isATest() { + return clazz -> isATest(clazz); + } + + private static boolean isJUnit3Test(final ClassInfo clazz) { + return clazz.descendsFrom(junit.framework.TestCase.class) + || clazz.descendsFrom(junit.framework.TestSuite.class); + } + + private static boolean isJUnit4Test(final ClassInfo clazz) { + return clazz.hasAnnotation(RunWith.class) + || clazz.hasAnnotation(Test.class); + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/adapter/AdaptedJUnitTestUnit.java b/pitest/src/main/java/org/pitest/junit/adapter/AdaptedJUnitTestUnit.java index ddbe03307..afdb9f6ef 100644 --- a/pitest/src/main/java/org/pitest/junit/adapter/AdaptedJUnitTestUnit.java +++ b/pitest/src/main/java/org/pitest/junit/adapter/AdaptedJUnitTestUnit.java @@ -1,125 +1,125 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.junit.adapter; - -import static org.pitest.util.Unchecked.translateCheckedException; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; -import org.junit.internal.runners.ErrorReportingRunner; -import org.junit.runner.Runner; -import org.junit.runner.manipulation.Filter; -import org.junit.runner.manipulation.Filterable; -import org.junit.runner.manipulation.NoTestsRemainException; -import org.junit.runners.model.RunnerBuilder; -import java.util.Optional; -import org.pitest.testapi.AbstractTestUnit; -import org.pitest.testapi.ResultCollector; -import org.pitest.util.Log; - -public class AdaptedJUnitTestUnit extends AbstractTestUnit { - - private static final Logger LOG = Log.getLogger(); - - private final Class clazz; - private final Optional filter; - - - public AdaptedJUnitTestUnit( - final Class clazz, final Optional filter) { - super(new org.pitest.testapi.Description(createName(clazz, filter), clazz)); - this.clazz = clazz; - this.filter = filter; - } - - private static String createName(final Class clazz, - final Optional filter) { - if (filter.isPresent()) { - return filter.get().describe(); - } else { - return clazz.getName(); - } - } - - @Override - public void execute(final ResultCollector rc) { - - final Runner runner = createRunner(this.clazz); - checkForErrorRunner(runner); - filterIfRequired(rc, runner); - - try { - final CustomRunnerExecutor nativeCe = new CustomRunnerExecutor( - this.getDescription(), runner, rc); - nativeCe.run(); - - } catch (final Exception e) { - LOG.log(Level.SEVERE, "Error while running adapter JUnit fixture " - + this.clazz + " with filter " + this.filter, e); - throw translateCheckedException(e); - } - - } - - private void checkForErrorRunner(final Runner runner) { - if (runner instanceof ErrorReportingRunner) { - LOG.warning("JUnit error for class " + this.clazz + " : " - + runner.getDescription()); - } - - } - - private void filterIfRequired(final ResultCollector rc, final Runner runner) { - if (this.filter.isPresent()) { - if (!(runner instanceof Filterable)) { - LOG.warning("Not able to filter " + runner.getDescription() - + ". Mutation may have prevented JUnit from constructing test"); - return; - } - final Filterable f = (Filterable) runner; - try { - f.filter(this.filter.get()); - } catch (final NoTestsRemainException e1) { - rc.notifySkipped(this.getDescription()); - return; - } - } - } - - public static Runner createRunner(final Class clazz) { - final RunnerBuilder builder = createRunnerBuilder(); - try { - return builder.runnerForClass(clazz); - } catch (final Throwable ex) { - LOG.log(Level.SEVERE, "Error while creating runner for " + clazz, ex); - throw translateCheckedException(ex); - } - - } - - private static RunnerBuilder createRunnerBuilder() { - return new AllDefaultPossibilitiesBuilder(true); - } - - @Override - public String toString() { - return "AdaptedJUnitTestUnit [clazz=" + this.clazz + ", filter=" - + this.filter + "]"; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.junit.adapter; + +import static org.pitest.util.Unchecked.translateCheckedException; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; +import org.junit.internal.runners.ErrorReportingRunner; +import org.junit.runner.Runner; +import org.junit.runner.manipulation.Filter; +import org.junit.runner.manipulation.Filterable; +import org.junit.runner.manipulation.NoTestsRemainException; +import org.junit.runners.model.RunnerBuilder; +import java.util.Optional; +import org.pitest.testapi.AbstractTestUnit; +import org.pitest.testapi.ResultCollector; +import org.pitest.util.Log; + +public class AdaptedJUnitTestUnit extends AbstractTestUnit { + + private static final Logger LOG = Log.getLogger(); + + private final Class clazz; + private final Optional filter; + + + public AdaptedJUnitTestUnit( + final Class clazz, final Optional filter) { + super(new org.pitest.testapi.Description(createName(clazz, filter), clazz)); + this.clazz = clazz; + this.filter = filter; + } + + private static String createName(final Class clazz, + final Optional filter) { + if (filter.isPresent()) { + return filter.get().describe(); + } else { + return clazz.getName(); + } + } + + @Override + public void execute(final ResultCollector rc) { + + final Runner runner = createRunner(this.clazz); + checkForErrorRunner(runner); + filterIfRequired(rc, runner); + + try { + final CustomRunnerExecutor nativeCe = new CustomRunnerExecutor( + this.getDescription(), runner, rc); + nativeCe.run(); + + } catch (final Exception e) { + LOG.log(Level.SEVERE, "Error while running adapter JUnit fixture " + + this.clazz + " with filter " + this.filter, e); + throw translateCheckedException(e); + } + + } + + private void checkForErrorRunner(final Runner runner) { + if (runner instanceof ErrorReportingRunner) { + LOG.warning("JUnit error for class " + this.clazz + " : " + + runner.getDescription()); + } + + } + + private void filterIfRequired(final ResultCollector rc, final Runner runner) { + if (this.filter.isPresent()) { + if (!(runner instanceof Filterable)) { + LOG.warning("Not able to filter " + runner.getDescription() + + ". Mutation may have prevented JUnit from constructing test"); + return; + } + final Filterable f = (Filterable) runner; + try { + f.filter(this.filter.get()); + } catch (final NoTestsRemainException e1) { + rc.notifySkipped(this.getDescription()); + return; + } + } + } + + public static Runner createRunner(final Class clazz) { + final RunnerBuilder builder = createRunnerBuilder(); + try { + return builder.runnerForClass(clazz); + } catch (final Throwable ex) { + LOG.log(Level.SEVERE, "Error while creating runner for " + clazz, ex); + throw translateCheckedException(ex); + } + + } + + private static RunnerBuilder createRunnerBuilder() { + return new AllDefaultPossibilitiesBuilder(true); + } + + @Override + public String toString() { + return "AdaptedJUnitTestUnit [clazz=" + this.clazz + ", filter=" + + this.filter + "]"; + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/adapter/AdaptingRunListener.java b/pitest/src/main/java/org/pitest/junit/adapter/AdaptingRunListener.java index bf3c68506..abb81436a 100644 --- a/pitest/src/main/java/org/pitest/junit/adapter/AdaptingRunListener.java +++ b/pitest/src/main/java/org/pitest/junit/adapter/AdaptingRunListener.java @@ -1,59 +1,59 @@ -package org.pitest.junit.adapter; - -import org.junit.runner.Description; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; -import org.junit.runner.notification.StoppedByUserException; -import org.pitest.testapi.ResultCollector; - -class AdaptingRunListener extends RunListener { - - private final org.pitest.testapi.Description description; - private final ResultCollector rc; - private boolean failed = false; - - AdaptingRunListener(final org.pitest.testapi.Description description, - final ResultCollector rc) { - this.description = description; - this.rc = rc; - } - - @Override - public void testFailure(final Failure failure) throws Exception { - this.rc.notifyEnd(this.description, failure.getException()); - this.failed = true; - } - - @Override - public void testAssumptionFailure(final Failure failure) { - // do nothing so treated as success - // see http://junit.sourceforge.net/doc/ReleaseNotes4.4.html#assumptions - } - - @Override - public void testIgnored(final Description description) throws Exception { - this.rc.notifySkipped(this.description); - } - - @Override - public void testStarted(final Description description) throws Exception { - if (this.failed) { - // If the JUnit test has been annotated with @BeforeClass or @AfterClass - // need to force the exit after the first failure as tests will be run as - // a block - // rather than individually. - // This is apparently the junit way. - throw new StoppedByUserException(); - } - this.rc.notifyStart(this.description); - } - - @Override - public void testFinished(final Description description) throws Exception { - if (!this.failed) { - this.rc.notifyEnd(this.description); - } - - } - -} +package org.pitest.junit.adapter; + +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; +import org.junit.runner.notification.StoppedByUserException; +import org.pitest.testapi.ResultCollector; + +class AdaptingRunListener extends RunListener { + + private final org.pitest.testapi.Description description; + private final ResultCollector rc; + private boolean failed = false; + + AdaptingRunListener(final org.pitest.testapi.Description description, + final ResultCollector rc) { + this.description = description; + this.rc = rc; + } + + @Override + public void testFailure(final Failure failure) throws Exception { + this.rc.notifyEnd(this.description, failure.getException()); + this.failed = true; + } + + @Override + public void testAssumptionFailure(final Failure failure) { + // do nothing so treated as success + // see http://junit.sourceforge.net/doc/ReleaseNotes4.4.html#assumptions + } + + @Override + public void testIgnored(final Description description) throws Exception { + this.rc.notifySkipped(this.description); + } + + @Override + public void testStarted(final Description description) throws Exception { + if (this.failed) { + // If the JUnit test has been annotated with @BeforeClass or @AfterClass + // need to force the exit after the first failure as tests will be run as + // a block + // rather than individually. + // This is apparently the junit way. + throw new StoppedByUserException(); + } + this.rc.notifyStart(this.description); + } + + @Override + public void testFinished(final Description description) throws Exception { + if (!this.failed) { + this.rc.notifyEnd(this.description); + } + + } + +} diff --git a/pitest/src/main/java/org/pitest/junit/adapter/CustomRunnerExecutor.java b/pitest/src/main/java/org/pitest/junit/adapter/CustomRunnerExecutor.java index 7e92aef4a..db8e50635 100644 --- a/pitest/src/main/java/org/pitest/junit/adapter/CustomRunnerExecutor.java +++ b/pitest/src/main/java/org/pitest/junit/adapter/CustomRunnerExecutor.java @@ -1,46 +1,46 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit.adapter; - -import org.junit.runner.Runner; -import org.junit.runner.notification.RunListener; -import org.junit.runner.notification.RunNotifier; -import org.pitest.testapi.ResultCollector; - -public class CustomRunnerExecutor { - - private final org.pitest.testapi.Description description; - private final Runner runner; - private final ResultCollector rc; - - public CustomRunnerExecutor(final org.pitest.testapi.Description description, - final Runner runner, final ResultCollector rc) { - this.runner = runner; - this.rc = rc; - this.description = description; - } - - public void run() { - - final RunNotifier rn = new RunNotifier(); - final RunListener listener = new AdaptingRunListener(this.description, - this.rc); - - rn.addFirstListener(listener); - this.runner.run(rn); - - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit.adapter; + +import org.junit.runner.Runner; +import org.junit.runner.notification.RunListener; +import org.junit.runner.notification.RunNotifier; +import org.pitest.testapi.ResultCollector; + +public class CustomRunnerExecutor { + + private final org.pitest.testapi.Description description; + private final Runner runner; + private final ResultCollector rc; + + public CustomRunnerExecutor(final org.pitest.testapi.Description description, + final Runner runner, final ResultCollector rc) { + this.runner = runner; + this.rc = rc; + this.description = description; + } + + public void run() { + + final RunNotifier rn = new RunNotifier(); + final RunListener listener = new AdaptingRunListener(this.description, + this.rc); + + rn.addFirstListener(listener); + this.runner.run(rn); + + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/DetectionStatus.java b/pitest/src/main/java/org/pitest/mutationtest/DetectionStatus.java index 83f1ef8eb..b5d63263d 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/DetectionStatus.java +++ b/pitest/src/main/java/org/pitest/mutationtest/DetectionStatus.java @@ -1,104 +1,104 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import org.pitest.util.ExitCode; - -/** - * The detection status of a mutant - */ -public enum DetectionStatus { - /** - * Mutation was detected by a test - */ - KILLED(true), - - /** - * No test failed in the presence of the mutation - */ - SURVIVED(false), - - /** - * A test took a long time to run when mutation was present, might indicate an - * that the mutation caused an infinite loop but we don't know for sure. - */ - TIMED_OUT(true), - - /** - * Mutation could not be loaded into the jvm. Should never happen. - */ - NON_VIABLE(true), - - /** - * JVM ran out of memory while processing a mutation. Might indicate that the - * mutation increases memory usage but we don't know for sure. - */ - MEMORY_ERROR(true), - /** - * Mutation not yet assessed. For internal use only. - */ - NOT_STARTED(false), - - /** - * Processing of mutation has begun but not yet fully assessed. For internal - * use only. - */ - STARTED(false), - - /** - * Something went wrong. Don't know what but it was probably bad. - */ - RUN_ERROR(true), - - /** - * Mutation is not covered by any test. - */ - NO_COVERAGE(false); - - private final boolean detected; - - DetectionStatus(final boolean detected) { - this.detected = detected; - } - - /** - * Converts a process exit code to a mutation status - * - * @param exitCode - * Exit code to convert - * @return The status corresponding to the exit code - */ - public static DetectionStatus getForErrorExitCode(final ExitCode exitCode) { - if (exitCode.equals(ExitCode.OUT_OF_MEMORY)) { - return DetectionStatus.MEMORY_ERROR; - } else if (exitCode.equals(ExitCode.TIMEOUT)) { - return DetectionStatus.TIMED_OUT; - } else { - return DetectionStatus.RUN_ERROR; - } - } - - /** - * Returns true if this status indicates that the mutation was distinguished - * from the un-mutated code by the test suite, ignores the slight ambiguity of - * some of the statuses. - * - * @return True if detected, false if not. - */ - public boolean isDetected() { - return this.detected; - } - -}; +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import org.pitest.util.ExitCode; + +/** + * The detection status of a mutant + */ +public enum DetectionStatus { + /** + * Mutation was detected by a test + */ + KILLED(true), + + /** + * No test failed in the presence of the mutation + */ + SURVIVED(false), + + /** + * A test took a long time to run when mutation was present, might indicate an + * that the mutation caused an infinite loop but we don't know for sure. + */ + TIMED_OUT(true), + + /** + * Mutation could not be loaded into the jvm. Should never happen. + */ + NON_VIABLE(true), + + /** + * JVM ran out of memory while processing a mutation. Might indicate that the + * mutation increases memory usage but we don't know for sure. + */ + MEMORY_ERROR(true), + /** + * Mutation not yet assessed. For internal use only. + */ + NOT_STARTED(false), + + /** + * Processing of mutation has begun but not yet fully assessed. For internal + * use only. + */ + STARTED(false), + + /** + * Something went wrong. Don't know what but it was probably bad. + */ + RUN_ERROR(true), + + /** + * Mutation is not covered by any test. + */ + NO_COVERAGE(false); + + private final boolean detected; + + DetectionStatus(final boolean detected) { + this.detected = detected; + } + + /** + * Converts a process exit code to a mutation status + * + * @param exitCode + * Exit code to convert + * @return The status corresponding to the exit code + */ + public static DetectionStatus getForErrorExitCode(final ExitCode exitCode) { + if (exitCode.equals(ExitCode.OUT_OF_MEMORY)) { + return DetectionStatus.MEMORY_ERROR; + } else if (exitCode.equals(ExitCode.TIMEOUT)) { + return DetectionStatus.TIMED_OUT; + } else { + return DetectionStatus.RUN_ERROR; + } + } + + /** + * Returns true if this status indicates that the mutation was distinguished + * from the un-mutated code by the test suite, ignores the slight ambiguity of + * some of the statuses. + * + * @return True if detected, false if not. + */ + public boolean isDetected() { + return this.detected; + } + +}; diff --git a/pitest/src/main/java/org/pitest/mutationtest/EngineArguments.java b/pitest/src/main/java/org/pitest/mutationtest/EngineArguments.java index 5839a717b..eb460f88a 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/EngineArguments.java +++ b/pitest/src/main/java/org/pitest/mutationtest/EngineArguments.java @@ -1,40 +1,40 @@ -package org.pitest.mutationtest; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; - -public class EngineArguments implements Serializable { - - private static final long serialVersionUID = 1L; - - private final Collection mutators; - private final Collection excludedMethods; - - public EngineArguments(Collection mutators, Collection excludedMethods) { - this.mutators = mutators; - this.excludedMethods = excludedMethods; - } - - public static EngineArguments arguments() { - return new EngineArguments(Collections.emptyList(), Collections.emptyList()); - } - - public EngineArguments withMutators(Collection mutators) { - return new EngineArguments(mutators, this.excludedMethods); - } - - public EngineArguments withExcludedMethods(Collection excludedMethods) { - return new EngineArguments(this.mutators, excludedMethods); - } - - public Collection mutators() { - return this.mutators; - } - - public Collection excludedMethods() { - return this.excludedMethods; - } - -} - +package org.pitest.mutationtest; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Collections; + +public class EngineArguments implements Serializable { + + private static final long serialVersionUID = 1L; + + private final Collection mutators; + private final Collection excludedMethods; + + public EngineArguments(Collection mutators, Collection excludedMethods) { + this.mutators = mutators; + this.excludedMethods = excludedMethods; + } + + public static EngineArguments arguments() { + return new EngineArguments(Collections.emptyList(), Collections.emptyList()); + } + + public EngineArguments withMutators(Collection mutators) { + return new EngineArguments(mutators, this.excludedMethods); + } + + public EngineArguments withExcludedMethods(Collection excludedMethods) { + return new EngineArguments(this.mutators, excludedMethods); + } + + public Collection mutators() { + return this.mutators; + } + + public Collection excludedMethods() { + return this.excludedMethods; + } + +} + diff --git a/pitest/src/main/java/org/pitest/mutationtest/MutationEngineFactory.java b/pitest/src/main/java/org/pitest/mutationtest/MutationEngineFactory.java index 2d310df48..22561a3c9 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/MutationEngineFactory.java +++ b/pitest/src/main/java/org/pitest/mutationtest/MutationEngineFactory.java @@ -1,12 +1,12 @@ -package org.pitest.mutationtest; - -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.plugin.ClientClasspathPlugin; - -public interface MutationEngineFactory extends ClientClasspathPlugin { - - MutationEngine createEngine(EngineArguments arguments); - - String name(); - -} +package org.pitest.mutationtest; + +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.plugin.ClientClasspathPlugin; + +public interface MutationEngineFactory extends ClientClasspathPlugin { + + MutationEngine createEngine(EngineArguments arguments); + + String name(); + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/MutationStatusTestPair.java b/pitest/src/main/java/org/pitest/mutationtest/MutationStatusTestPair.java index 6d0215879..dbee96043 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/MutationStatusTestPair.java +++ b/pitest/src/main/java/org/pitest/mutationtest/MutationStatusTestPair.java @@ -1,103 +1,103 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import java.io.Serializable; - -import java.util.Optional; - -public final class MutationStatusTestPair implements Serializable { - - private static final long serialVersionUID = 1L; - - private final int numberOfTestsRun; - private final DetectionStatus status; - private final String killingTest; - - public MutationStatusTestPair(final int numberOfTestsRun, - final DetectionStatus status) { - this(numberOfTestsRun, status, null); - } - - public MutationStatusTestPair(final int numberOfTestsRun, - final DetectionStatus status, final String killingTest) { - this.status = status; - this.killingTest = killingTest; - this.numberOfTestsRun = numberOfTestsRun; - } - - public DetectionStatus getStatus() { - return this.status; - } - - public Optional getKillingTest() { - return Optional.ofNullable(this.killingTest); - } - - public int getNumberOfTestsRun() { - return this.numberOfTestsRun; - } - - @Override - public String toString() { - if (this.killingTest == null) { - return this.status.name(); - } else { - return this.status.name() + " by " + this.killingTest; - } - - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.killingTest == null) ? 0 : this.killingTest.hashCode()); - result = (prime * result) + this.numberOfTestsRun; - result = (prime * result) - + ((this.status == null) ? 0 : this.status.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MutationStatusTestPair other = (MutationStatusTestPair) obj; - if (this.killingTest == null) { - if (other.killingTest != null) { - return false; - } - } else if (!this.killingTest.equals(other.killingTest)) { - return false; - } - if (this.numberOfTestsRun != other.numberOfTestsRun) { - return false; - } - if (this.status != other.status) { - return false; - } - return true; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import java.io.Serializable; + +import java.util.Optional; + +public final class MutationStatusTestPair implements Serializable { + + private static final long serialVersionUID = 1L; + + private final int numberOfTestsRun; + private final DetectionStatus status; + private final String killingTest; + + public MutationStatusTestPair(final int numberOfTestsRun, + final DetectionStatus status) { + this(numberOfTestsRun, status, null); + } + + public MutationStatusTestPair(final int numberOfTestsRun, + final DetectionStatus status, final String killingTest) { + this.status = status; + this.killingTest = killingTest; + this.numberOfTestsRun = numberOfTestsRun; + } + + public DetectionStatus getStatus() { + return this.status; + } + + public Optional getKillingTest() { + return Optional.ofNullable(this.killingTest); + } + + public int getNumberOfTestsRun() { + return this.numberOfTestsRun; + } + + @Override + public String toString() { + if (this.killingTest == null) { + return this.status.name(); + } else { + return this.status.name() + " by " + this.killingTest; + } + + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.killingTest == null) ? 0 : this.killingTest.hashCode()); + result = (prime * result) + this.numberOfTestsRun; + result = (prime * result) + + ((this.status == null) ? 0 : this.status.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MutationStatusTestPair other = (MutationStatusTestPair) obj; + if (this.killingTest == null) { + if (other.killingTest != null) { + return false; + } + } else if (!this.killingTest.equals(other.killingTest)) { + return false; + } + if (this.numberOfTestsRun != other.numberOfTestsRun) { + return false; + } + if (this.status != other.status) { + return false; + } + return true; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/TimeoutLengthStrategy.java b/pitest/src/main/java/org/pitest/mutationtest/TimeoutLengthStrategy.java index b9f03147b..fbbc8dda4 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/TimeoutLengthStrategy.java +++ b/pitest/src/main/java/org/pitest/mutationtest/TimeoutLengthStrategy.java @@ -1,24 +1,24 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest; - -import java.io.Serializable; - -public interface TimeoutLengthStrategy extends Serializable { - - long getAllowedTime(long normalDuration); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest; + +import java.io.Serializable; + +public interface TimeoutLengthStrategy extends Serializable { + + long getAllowedTime(long normalDuration); + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/UnviableClassMutator.java b/pitest/src/main/java/org/pitest/mutationtest/UnviableClassMutator.java index 79250885c..dfcacb538 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/UnviableClassMutator.java +++ b/pitest/src/main/java/org/pitest/mutationtest/UnviableClassMutator.java @@ -1,70 +1,71 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import java.util.HashMap; -import java.util.Map; - -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.mutationtest.engine.gregor.AbstractInsnMutator; -import org.pitest.mutationtest.engine.gregor.InsnSubstitution; -import org.pitest.mutationtest.engine.gregor.MethodInfo; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.mutationtest.engine.gregor.MutationContext; -import org.pitest.mutationtest.engine.gregor.ZeroOperandMutation; - -public class UnviableClassMutator implements MethodMutatorFactory { - - @Override - public MethodVisitor create(final MutationContext context, - final MethodInfo methodInfo, final MethodVisitor methodVisitor) { - return new UnviableClassMethodVisitor(this, methodInfo, context, - methodVisitor); - } - - @Override - public String getGloballyUniqueId() { - return this.getClass().getName(); - } - - @Override - public String getName() { - return "UNVIABLE_CLASS_MUTATOR"; - } - -} - -class UnviableClassMethodVisitor extends AbstractInsnMutator { - - UnviableClassMethodVisitor(final MethodMutatorFactory factory, - final MethodInfo methodInfo, final MutationContext context, - final MethodVisitor writer) { - super(factory, methodInfo, context, writer); - } - - @Override - protected Map getMutations() { - final Map map = new HashMap<>(); - // map.put(Opcodes.ALOAD, new InsnSubstitution(Opcodes.TABLESWITCH, - // "Made unviable class")); - map.put(Opcodes.IRETURN, new InsnSubstitution(Opcodes.FCMPG, - "Made unviable class")); - map.put(Opcodes.RETURN, new InsnSubstitution(Opcodes.FCMPG, - "Made unviable class")); - return map; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import java.util.HashMap; +import java.util.Map; + +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.mutationtest.engine.gregor.AbstractInsnMutator; +import org.pitest.mutationtest.engine.gregor.InsnSubstitution; +import org.pitest.mutationtest.engine.gregor.MethodInfo; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.mutationtest.engine.gregor.MutationContext; +import org.pitest.mutationtest.engine.gregor.ZeroOperandMutation; + +public class UnviableClassMutator implements MethodMutatorFactory { + + @Override + public MethodVisitor create(final MutationContext context, + final MethodInfo methodInfo, final MethodVisitor methodVisitor, ClassByteArraySource byteSource) { + return new UnviableClassMethodVisitor(this, methodInfo, context, + methodVisitor, byteSource); + } + + @Override + public String getGloballyUniqueId() { + return this.getClass().getName(); + } + + @Override + public String getName() { + return "UNVIABLE_CLASS_MUTATOR"; + } + +} + +class UnviableClassMethodVisitor extends AbstractInsnMutator { + + UnviableClassMethodVisitor(final MethodMutatorFactory factory, + final MethodInfo methodInfo, final MutationContext context, + final MethodVisitor writer, ClassByteArraySource byteSource) { + super(factory, methodInfo, context, writer, byteSource); + } + + @Override + protected Map getMutations() { + final Map map = new HashMap<>(); + // map.put(Opcodes.ALOAD, new InsnSubstitution(Opcodes.TABLESWITCH, + // "Made unviable class")); + map.put(Opcodes.IRETURN, new InsnSubstitution(Opcodes.FCMPG, + "Made unviable class")); + map.put(Opcodes.RETURN, new InsnSubstitution(Opcodes.FCMPG, + "Made unviable class")); + return map; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/build/PercentAndConstantTimeoutStrategy.java b/pitest/src/main/java/org/pitest/mutationtest/build/PercentAndConstantTimeoutStrategy.java index c62791998..0d4879062 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/build/PercentAndConstantTimeoutStrategy.java +++ b/pitest/src/main/java/org/pitest/mutationtest/build/PercentAndConstantTimeoutStrategy.java @@ -1,41 +1,41 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.build; - -import org.pitest.mutationtest.TimeoutLengthStrategy; - -public class PercentAndConstantTimeoutStrategy implements TimeoutLengthStrategy { - - private static final long serialVersionUID = 1L; - - public static final float DEFAULT_FACTOR = 1.25f; - public static final long DEFAULT_CONSTANT = 4000; - - private final float percent; - private final long constant; - - public PercentAndConstantTimeoutStrategy(final float percent, - final long constant) { - this.percent = percent; - this.constant = constant; - } - - @Override - public long getAllowedTime(final long normalDuration) { - return Math.round(normalDuration * this.percent) + this.constant; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.build; + +import org.pitest.mutationtest.TimeoutLengthStrategy; + +public class PercentAndConstantTimeoutStrategy implements TimeoutLengthStrategy { + + private static final long serialVersionUID = 1L; + + public static final float DEFAULT_FACTOR = 1.25f; + public static final long DEFAULT_CONSTANT = 4000; + + private final float percent; + private final long constant; + + public PercentAndConstantTimeoutStrategy(final float percent, + final long constant) { + this.percent = percent; + this.constant = constant; + } + + @Override + public long getAllowedTime(final long normalDuration) { + return Math.round(normalDuration * this.percent) + this.constant; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/config/ClientPluginServices.java b/pitest/src/main/java/org/pitest/mutationtest/config/ClientPluginServices.java index 0e2652f38..e3ecf34f6 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/config/ClientPluginServices.java +++ b/pitest/src/main/java/org/pitest/mutationtest/config/ClientPluginServices.java @@ -1,30 +1,30 @@ -package org.pitest.mutationtest.config; - -import java.util.Collection; - -import org.pitest.mutationtest.MutationEngineFactory; -import org.pitest.testapi.TestPluginFactory; -import org.pitest.util.IsolationUtils; -import org.pitest.util.ServiceLoader; - -public class ClientPluginServices { - private final ClassLoader loader; - - public ClientPluginServices(ClassLoader loader) { - this.loader = loader; - } - - public static ClientPluginServices makeForContextLoader() { - return new ClientPluginServices(IsolationUtils.getContextClassLoader()); - } - - - Collection findTestFrameworkPlugins() { - return ServiceLoader.load(TestPluginFactory.class, this.loader); - } - - Collection findMutationEngines() { - return ServiceLoader.load(MutationEngineFactory.class, this.loader); - } - -} +package org.pitest.mutationtest.config; + +import java.util.Collection; + +import org.pitest.mutationtest.MutationEngineFactory; +import org.pitest.testapi.TestPluginFactory; +import org.pitest.util.IsolationUtils; +import org.pitest.util.ServiceLoader; + +public class ClientPluginServices { + private final ClassLoader loader; + + public ClientPluginServices(ClassLoader loader) { + this.loader = loader; + } + + public static ClientPluginServices makeForContextLoader() { + return new ClientPluginServices(IsolationUtils.getContextClassLoader()); + } + + + Collection findTestFrameworkPlugins() { + return ServiceLoader.load(TestPluginFactory.class, this.loader); + } + + Collection findMutationEngines() { + return ServiceLoader.load(MutationEngineFactory.class, this.loader); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/config/MinionSettings.java b/pitest/src/main/java/org/pitest/mutationtest/config/MinionSettings.java index 2d712991b..63944cbf6 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/config/MinionSettings.java +++ b/pitest/src/main/java/org/pitest/mutationtest/config/MinionSettings.java @@ -1,41 +1,41 @@ -package org.pitest.mutationtest.config; - -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.mutationtest.MutationEngineFactory; -import org.pitest.testapi.Configuration; -import org.pitest.testapi.TestPluginFactory; -import org.pitest.util.PitError; - -public class MinionSettings { - - private final ClientPluginServices plugins; - - public MinionSettings(final ClientPluginServices plugins) { - this.plugins = plugins; - } - - public MutationEngineFactory createEngine(String engine) { - for (final MutationEngineFactory each : this.plugins.findMutationEngines()) { - if (each.name().equals(engine)) { - return each; - } - } - throw new PitError("Could not load requested engine " - + engine); - } - - - public Configuration getTestFrameworkPlugin(TestPluginArguments options, ClassByteArraySource source) { - for (final TestPluginFactory each : this.plugins.findTestFrameworkPlugins()) { - if (each.name().equals(options.getTestPlugin())) { - return each.createTestFrameworkConfiguration(options.getGroupConfig(), - source, - options.getExcludedRunners(), - options.getIncludedTestMethods()); - } - } - throw new PitError("Could not load requested test plugin " - + options.getTestPlugin()); - } - -} +package org.pitest.mutationtest.config; + +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.mutationtest.MutationEngineFactory; +import org.pitest.testapi.Configuration; +import org.pitest.testapi.TestPluginFactory; +import org.pitest.util.PitError; + +public class MinionSettings { + + private final ClientPluginServices plugins; + + public MinionSettings(final ClientPluginServices plugins) { + this.plugins = plugins; + } + + public MutationEngineFactory createEngine(String engine) { + for (final MutationEngineFactory each : this.plugins.findMutationEngines()) { + if (each.name().equals(engine)) { + return each; + } + } + throw new PitError("Could not load requested engine " + + engine); + } + + + public Configuration getTestFrameworkPlugin(TestPluginArguments options, ClassByteArraySource source) { + for (final TestPluginFactory each : this.plugins.findTestFrameworkPlugins()) { + if (each.name().equals(options.getTestPlugin())) { + return each.createTestFrameworkConfiguration(options.getGroupConfig(), + source, + options.getExcludedRunners(), + options.getIncludedTestMethods()); + } + } + throw new PitError("Could not load requested test plugin " + + options.getTestPlugin()); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/config/TestPluginArguments.java b/pitest/src/main/java/org/pitest/mutationtest/config/TestPluginArguments.java index c78129719..fd94c9f8d 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/config/TestPluginArguments.java +++ b/pitest/src/main/java/org/pitest/mutationtest/config/TestPluginArguments.java @@ -1,58 +1,58 @@ -package org.pitest.mutationtest.config; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; - -import org.pitest.junit.JUnitTestPlugin; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.util.Preconditions; - -public class TestPluginArguments implements Serializable { - - private static final long serialVersionUID = 1L; - - private final String testPlugin; - private final TestGroupConfig groupConfig; - private final Collection includedTestMethods; - private final Collection excludedRunners; - - public TestPluginArguments(String testPlugin, - TestGroupConfig groupConfig, - Collection excludedRunners, - Collection includedTestMethods) { - Preconditions.checkNotNull(testPlugin); - Preconditions.checkNotNull(groupConfig); - Preconditions.checkNotNull(excludedRunners); - this.testPlugin = testPlugin; - this.groupConfig = groupConfig; - this.excludedRunners = excludedRunners; - this.includedTestMethods = includedTestMethods; - } - - public static TestPluginArguments defaults() { - return new TestPluginArguments(JUnitTestPlugin.NAME, new TestGroupConfig(), Collections.emptyList(), - Collections.emptyList()); - } - - public TestPluginArguments withTestPlugin(String plugin) { - return new TestPluginArguments(plugin, this.groupConfig, this.excludedRunners, this.includedTestMethods); - } - - public TestGroupConfig getGroupConfig() { - return this.groupConfig; - } - - public Collection getExcludedRunners() { - return this.excludedRunners; - } - - public Collection getIncludedTestMethods() { - return this.includedTestMethods; - } - - public String getTestPlugin() { - return this.testPlugin; - } - -} +package org.pitest.mutationtest.config; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Collections; + +import org.pitest.junit.JUnitTestPlugin; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.util.Preconditions; + +public class TestPluginArguments implements Serializable { + + private static final long serialVersionUID = 1L; + + private final String testPlugin; + private final TestGroupConfig groupConfig; + private final Collection includedTestMethods; + private final Collection excludedRunners; + + public TestPluginArguments(String testPlugin, + TestGroupConfig groupConfig, + Collection excludedRunners, + Collection includedTestMethods) { + Preconditions.checkNotNull(testPlugin); + Preconditions.checkNotNull(groupConfig); + Preconditions.checkNotNull(excludedRunners); + this.testPlugin = testPlugin; + this.groupConfig = groupConfig; + this.excludedRunners = excludedRunners; + this.includedTestMethods = includedTestMethods; + } + + public static TestPluginArguments defaults() { + return new TestPluginArguments(JUnitTestPlugin.NAME, new TestGroupConfig(), Collections.emptyList(), + Collections.emptyList()); + } + + public TestPluginArguments withTestPlugin(String plugin) { + return new TestPluginArguments(plugin, this.groupConfig, this.excludedRunners, this.includedTestMethods); + } + + public TestGroupConfig getGroupConfig() { + return this.groupConfig; + } + + public Collection getExcludedRunners() { + return this.excludedRunners; + } + + public Collection getIncludedTestMethods() { + return this.includedTestMethods; + } + + public String getTestPlugin() { + return this.testPlugin; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/Location.java b/pitest/src/main/java/org/pitest/mutationtest/engine/Location.java index 2d9bd1a74..d8eced4ad 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/Location.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/Location.java @@ -1,131 +1,131 @@ -/* - * Copyright 2013 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine; - -import java.io.Serializable; - -import org.pitest.classinfo.ClassName; - -/** - * The co-ordinates of a method within a class. - * - */ -public final class Location implements Comparable, Serializable { - - private static final long serialVersionUID = 1L; - - private final ClassName clazz; - private final MethodName method; - private final String methodDesc; - - public Location(final ClassName clazz, final MethodName method, - final String methodDesc) { - this.clazz = clazz; - this.method = method; - this.methodDesc = methodDesc; - } - - public static Location location(final ClassName clazz, - final MethodName method, final String methodDesc) { - return new Location(clazz, method, methodDesc); - } - - public ClassName getClassName() { - return this.clazz; - } - - public MethodName getMethodName() { - return this.method; - } - - public String getMethodDesc() { - return this.methodDesc; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.clazz == null) ? 0 : this.clazz.hashCode()); - result = (prime * result) - + ((this.method == null) ? 0 : this.method.hashCode()); - result = (prime * result) - + ((this.methodDesc == null) ? 0 : this.methodDesc.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Location other = (Location) obj; - if (this.clazz == null) { - if (other.clazz != null) { - return false; - } - } else if (!this.clazz.equals(other.clazz)) { - return false; - } - if (this.method == null) { - if (other.method != null) { - return false; - } - } else if (!this.method.equals(other.method)) { - return false; - } - if (this.methodDesc == null) { - if (other.methodDesc != null) { - return false; - } - } else if (!this.methodDesc.equals(other.methodDesc)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Location [clazz=" + this.clazz + ", method=" + this.method - + ", methodDesc=" + this.methodDesc + "]"; - } - - public String describe() { - return this.method.name(); - } - - @Override - public int compareTo(final Location o) { - int comp = this.clazz.compareTo(o.getClassName()); - if (comp != 0) { - return comp; - } - - comp = this.method.name().compareTo(o.getMethodName().name()); - if (comp != 0) { - return comp; - } - - return this.methodDesc.compareTo(o.getMethodDesc()); - } - -} +/* + * Copyright 2013 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine; + +import java.io.Serializable; + +import org.pitest.classinfo.ClassName; + +/** + * The co-ordinates of a method within a class. + * + */ +public final class Location implements Comparable, Serializable { + + private static final long serialVersionUID = 1L; + + private final ClassName clazz; + private final MethodName method; + private final String methodDesc; + + public Location(final ClassName clazz, final MethodName method, + final String methodDesc) { + this.clazz = clazz; + this.method = method; + this.methodDesc = methodDesc; + } + + public static Location location(final ClassName clazz, + final MethodName method, final String methodDesc) { + return new Location(clazz, method, methodDesc); + } + + public ClassName getClassName() { + return this.clazz; + } + + public MethodName getMethodName() { + return this.method; + } + + public String getMethodDesc() { + return this.methodDesc; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.clazz == null) ? 0 : this.clazz.hashCode()); + result = (prime * result) + + ((this.method == null) ? 0 : this.method.hashCode()); + result = (prime * result) + + ((this.methodDesc == null) ? 0 : this.methodDesc.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Location other = (Location) obj; + if (this.clazz == null) { + if (other.clazz != null) { + return false; + } + } else if (!this.clazz.equals(other.clazz)) { + return false; + } + if (this.method == null) { + if (other.method != null) { + return false; + } + } else if (!this.method.equals(other.method)) { + return false; + } + if (this.methodDesc == null) { + if (other.methodDesc != null) { + return false; + } + } else if (!this.methodDesc.equals(other.methodDesc)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "Location [clazz=" + this.clazz + ", method=" + this.method + + ", methodDesc=" + this.methodDesc + "]"; + } + + public String describe() { + return this.method.name(); + } + + @Override + public int compareTo(final Location o) { + int comp = this.clazz.compareTo(o.getClassName()); + if (comp != 0) { + return comp; + } + + comp = this.method.name().compareTo(o.getMethodName().name()); + if (comp != 0) { + return comp; + } + + return this.methodDesc.compareTo(o.getMethodDesc()); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/MethodName.java b/pitest/src/main/java/org/pitest/mutationtest/engine/MethodName.java index 4b7b4b3b9..b7c3c3b51 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/MethodName.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/MethodName.java @@ -1,59 +1,59 @@ -package org.pitest.mutationtest.engine; - -import java.io.Serializable; - -public class MethodName implements Serializable { - - private static final long serialVersionUID = 1L; - - private final String name; - - MethodName(final String name) { - this.name = name; - } - - public static MethodName fromString(final String name) { - return new MethodName(name); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.name == null) ? 0 : this.name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MethodName other = (MethodName) obj; - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - return this.name; - } - - public final String name() { - return this.name; - } - -} +package org.pitest.mutationtest.engine; + +import java.io.Serializable; + +public class MethodName implements Serializable { + + private static final long serialVersionUID = 1L; + + private final String name; + + MethodName(final String name) { + this.name = name; + } + + public static MethodName fromString(final String name) { + return new MethodName(name); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.name == null) ? 0 : this.name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MethodName other = (MethodName) obj; + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + return this.name; + } + + public final String name() { + return this.name; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/Mutant.java b/pitest/src/main/java/org/pitest/mutationtest/engine/Mutant.java index f7866facd..15221755c 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/Mutant.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/Mutant.java @@ -1,48 +1,48 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine; - -/** - * A fully generated mutant - */ -public final class Mutant { - - private final MutationDetails details; - private final byte[] bytes; - - public Mutant(final MutationDetails details, final byte[] bytes) { - this.details = details; - this.bytes = bytes; - } - - /** - * Returns a data relating to the mutant - * - * @return A MutationDetails object - */ - public MutationDetails getDetails() { - return this.details; - } - - /** - * Returns a byte array containing the mutant class - * - * @return A byte array - */ - public byte[] getBytes() { - return this.bytes; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine; + +/** + * A fully generated mutant + */ +public final class Mutant { + + private final MutationDetails details; + private final byte[] bytes; + + public Mutant(final MutationDetails details, final byte[] bytes) { + this.details = details; + this.bytes = bytes; + } + + /** + * Returns a data relating to the mutant + * + * @return A MutationDetails object + */ + public MutationDetails getDetails() { + return this.details; + } + + /** + * Returns a byte array containing the mutant class + * + * @return A byte array + */ + public byte[] getBytes() { + return this.bytes; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/Mutater.java b/pitest/src/main/java/org/pitest/mutationtest/engine/Mutater.java index 9327ac227..9296ad609 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/Mutater.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/Mutater.java @@ -1,44 +1,44 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine; - -import java.util.List; - -import org.pitest.classinfo.ClassName; - -/** - * Generates mutants - */ -public interface Mutater { - - /** - * Creates a mutant matching the given MutationIdentifier - * - * @param id - * the mutant to create - * @return a Mutant - */ - Mutant getMutation(MutationIdentifier id); - - /** - * Scans for possible mutants in the given class - * - * @param classToMutate - * the class to scan for mutants - * @return a list of possible mutants - */ - List findMutations(ClassName classToMutate); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine; + +import java.util.List; + +import org.pitest.classinfo.ClassName; + +/** + * Generates mutants + */ +public interface Mutater { + + /** + * Creates a mutant matching the given MutationIdentifier + * + * @param id + * the mutant to create + * @return a Mutant + */ + Mutant getMutation(MutationIdentifier id); + + /** + * Scans for possible mutants in the given class + * + * @param classToMutate + * the class to scan for mutants + * @return a list of possible mutants + */ + List findMutations(ClassName classToMutate); + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/MutationDetails.java b/pitest/src/main/java/org/pitest/mutationtest/engine/MutationDetails.java index f1486a0fe..2c8729324 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/MutationDetails.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/MutationDetails.java @@ -1,295 +1,294 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.ClassLine; -import org.pitest.coverage.TestInfo; -import org.pitest.util.Preconditions; -import org.pitest.util.StringUtil; - -/** - * Captures all data relating to a mutant. - */ -public final class MutationDetails implements Serializable { - - private static final long serialVersionUID = 1L; - - private final MutationIdentifier id; - private final String filename; - private final int block; - private final int lineNumber; - private final String description; - private final ArrayList testsInOrder = new ArrayList<>(); - private final boolean isInFinallyBlock; - private final PoisonStatus poison; - - public MutationDetails(final MutationIdentifier id, final String filename, - final String description, final int lineNumber, final int block) { - this(id, filename, description, lineNumber, block, false, PoisonStatus.NORMAL); - } - - public MutationDetails(final MutationIdentifier id, final String filename, - final String description, final int lineNumber, final int block, - final boolean isInFinallyBlock, final PoisonStatus poison) { - this.id = id; - this.description = Preconditions.checkNotNull(description); - this.filename = Preconditions.checkNotNull(filename); - this.lineNumber = lineNumber; - this.block = block; - this.isInFinallyBlock = isInFinallyBlock; - this.poison = poison; - } - - - - @Override - public String toString() { - return "MutationDetails [id=" + this.id + ", filename=" + this.filename + ", block=" - + this.block + ", lineNumber=" + this.lineNumber + ", description=" + this.description - + ", testsInOrder=" + this.testsInOrder + ", isInFinallyBlock=" - + this.isInFinallyBlock + ", poison=" + this.poison + "]"; - } - - public MutationDetails withDescription(String desc) { - return new MutationDetails(this.id, this.filename, desc, this.lineNumber, this.block, this.isInFinallyBlock, this.poison); - } - - public MutationDetails withPoisonStatus(PoisonStatus poisonStatus) { - return new MutationDetails(this.id, this.filename, this.description, this.lineNumber, this.block, this.isInFinallyBlock, poisonStatus); - } - - /** - * Returns the human readable description of the mutation. This may be a - * constant string or may provide more contextual information depending on the - * mutation operator. - * - * @return Human readable description of the mutation - */ - public String getDescription() { - return this.description; - } - - /** - * Returns the mutation description with special characters escaped - * - * @return Escaped description string - */ - @Deprecated - public String getHtmlSafeDescription() { - // fixme this should not be here used in string template - return StringUtil.escapeBasicHtmlChars(this.description); - } - - /** - * Returns the method name in which this mutation is located as a string - * - * @return method name as string - */ - @Deprecated - public String getLocation() { - // fixme this should not be here used in string template - return this.id.getLocation().describe(); - } - - /** - * Returns the class in which this mutation is located - * - * @return class in which mutation is located - */ - public ClassName getClassName() { - return this.id.getClassName(); - } - - /** - * Returns the class in which this mutation is located - * - * @return class in which mutation is located - */ - public MethodName getMethod() { - return this.id.getLocation().getMethodName(); - } - - /** - * Returns the file in which this mutation is located - * - * @return file in which mutation is located - */ - public String getFilename() { - return this.filename; - } - - /** - * Returns the line number on which the mutation occurs as reported within the - * jvm bytecode - * - * @return The line number on which the mutation occurs. - */ - public int getLineNumber() { - return this.lineNumber; - } - - /** - * Returns the ClassLine in which this mutation is located - * - * @return the ClassLine in which this mutation is located - */ - public ClassLine getClassLine() { - return new ClassLine(this.id.getClassName(), this.lineNumber); - } - - /** - * Returns the identified for this mutation - * - * @return a MutationIdentifier - */ - public MutationIdentifier getId() { - return this.id; - } - - /** - * Returns the tests that cover this mutation in optimised order - * - * @return a list of TestInfo objects - */ - public List getTestsInOrder() { - return this.testsInOrder; - } - - /** - * Adds tests to the list of covering tests - * - * @param testNames - * The tests to add - */ - public void addTestsInOrder(final Collection testNames) { - this.testsInOrder.addAll(testNames); - this.testsInOrder.trimToSize(); - } - - /** - * Indicates if this mutation might poison state within the jvm (e.g affect - * the values of static variable) - * - * @return true if the mutation might poison the jvm otherwise false - */ - public boolean mayPoisonJVM() { - return this.poison.mayPoison(); - } - - /** - * Indicates if this mutation is in a static initializer block - * - * @return true if in a static initializer otherwise false - */ - public boolean isInStaticInitializer() { - return this.poison == PoisonStatus.IS_STATIC_INITIALIZER_CODE; - } - - /** - * Returns the basic block in which this mutation occurs. See - * https://github.com/hcoles/pitest/issues/131 for discussion on block - * coverage - * - * @return the block within the method that this mutation is located in - */ - public int getBlock() { - return this.block; - } - - /** - * Returns true if this mutation has a matching identifier - * - * @param id - * the MutationIdentifier to match - * @return true if the MutationIdentifier matches otherwise false - */ - public Boolean matchesId(final MutationIdentifier id) { - return this.id.matches(id); - } - - /** - * Returns the name of the mutator that created this mutation - * - * @return the mutator name - */ - public String getMutator() { - return this.id.getMutator(); - } - - /** - * Returns the index to the first instruction on which this mutation occurs. - * This index is specific to how ASM represents the bytecode. - * - * @return the zero based index to the instruction - */ - public int getFirstIndex() { - return this.id.getFirstIndex(); - } - - /** - * Zero based index to first affected ASM instruction - * @return - */ - public int getInstructionIndex() { - return getFirstIndex() - 1; - } - - /** - * Indicates if the mutation is within a finally block - * - * @return true if in finally block otherwise false - */ - public boolean isInFinallyBlock() { - return this.isInFinallyBlock; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + ((this.id == null) ? 0 : this.id.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MutationDetails other = (MutationDetails) obj; - if (this.id == null) { - if (other.id != null) { - return false; - } - } else if (!this.id.equals(other.id)) { - return false; - } - return true; - } - - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.ClassLine; +import org.pitest.coverage.TestInfo; +import org.pitest.util.Preconditions; +import org.pitest.util.StringUtil; + +/** + * Captures all data relating to a mutant. + */ +public final class MutationDetails implements Serializable { + + private static final long serialVersionUID = 1L; + + private final MutationIdentifier id; + private final String filename; + private final int block; + private final int lineNumber; + private final String description; + private final ArrayList testsInOrder = new ArrayList<>(); + private final boolean isInFinallyBlock; + private final PoisonStatus poison; + + public MutationDetails(final MutationIdentifier id, final String filename, + final String description, final int lineNumber, final int block) { + this(id, filename, description, lineNumber, block, false, PoisonStatus.NORMAL); + } + + public MutationDetails(final MutationIdentifier id, final String filename, + final String description, final int lineNumber, final int block, + final boolean isInFinallyBlock, final PoisonStatus poison) { + this.id = id; + this.description = Preconditions.checkNotNull(description); + this.filename = Preconditions.checkNotNull(filename); + this.lineNumber = lineNumber; + this.block = block; + this.isInFinallyBlock = isInFinallyBlock; + this.poison = poison; + } + + + + @Override + public String toString() { + return "MutationDetails [id=" + this.id + ", filename=" + this.filename + ", block=" + + this.block + ", lineNumber=" + this.lineNumber + ", description=" + this.description + + ", testsInOrder=" + this.testsInOrder + ", isInFinallyBlock=" + + this.isInFinallyBlock + ", poison=" + this.poison + "]"; + } + + public MutationDetails withDescription(String desc) { + return new MutationDetails(this.id, this.filename, desc, this.lineNumber, this.block, this.isInFinallyBlock, this.poison); + } + + public MutationDetails withPoisonStatus(PoisonStatus poisonStatus) { + return new MutationDetails(this.id, this.filename, this.description, this.lineNumber, this.block, this.isInFinallyBlock, poisonStatus); + } + + /** + * Returns the human readable description of the mutation. This may be a + * constant string or may provide more contextual information depending on the + * mutation operator. + * + * @return Human readable description of the mutation + */ + public String getDescription() { + return this.description; + } + + /** + * Returns the mutation description with special characters escaped + * + * @return Escaped description string + */ + @Deprecated + public String getHtmlSafeDescription() { + // fixme this should not be here used in string template + return StringUtil.escapeBasicHtmlChars(this.description); + } + + /** + * Returns the method name in which this mutation is located as a string + * + * @return method name as string + */ + @Deprecated + public String getLocation() { + // fixme this should not be here used in string template + return this.id.getLocation().describe(); + } + + /** + * Returns the class in which this mutation is located + * + * @return class in which mutation is located + */ + public ClassName getClassName() { + return this.id.getClassName(); + } + + /** + * Returns the class in which this mutation is located + * + * @return class in which mutation is located + */ + public MethodName getMethod() { + return this.id.getLocation().getMethodName(); + } + + /** + * Returns the file in which this mutation is located + * + * @return file in which mutation is located + */ + public String getFilename() { + return this.filename; + } + + /** + * Returns the line number on which the mutation occurs as reported within the + * jvm bytecode + * + * @return The line number on which the mutation occurs. + */ + public int getLineNumber() { + return this.lineNumber; + } + + /** + * Returns the ClassLine in which this mutation is located + * + * @return the ClassLine in which this mutation is located + */ + public ClassLine getClassLine() { + return new ClassLine(this.id.getClassName(), this.lineNumber); + } + + /** + * Returns the identified for this mutation + * + * @return a MutationIdentifier + */ + public MutationIdentifier getId() { + return this.id; + } + + /** + * Returns the tests that cover this mutation in optimised order + * + * @return a list of TestInfo objects + */ + public List getTestsInOrder() { + return this.testsInOrder; + } + + /** + * Adds tests to the list of covering tests + * + * @param testNames + * The tests to add + */ + public void addTestsInOrder(final Collection testNames) { + this.testsInOrder.addAll(testNames); + this.testsInOrder.trimToSize(); + } + + /** + * Indicates if this mutation might poison state within the jvm (e.g affect + * the values of static variable) + * + * @return true if the mutation might poison the jvm otherwise false + */ + public boolean mayPoisonJVM() { + return this.poison.mayPoison(); + } + + /** + * Indicates if this mutation is in a static initializer block + * + * @return true if in a static initializer otherwise false + */ + public boolean isInStaticInitializer() { + return this.poison == PoisonStatus.IS_STATIC_INITIALIZER_CODE; + } + + /** + * Returns the basic block in which this mutation occurs. See + * https://github.com/hcoles/pitest/issues/131 for discussion on block + * coverage + * + * @return the block within the method that this mutation is located in + */ + public int getBlock() { + return this.block; + } + + /** + * Returns true if this mutation has a matching identifier + * + * @param id + * the MutationIdentifier to match + * @return true if the MutationIdentifier matches otherwise false + */ + public Boolean matchesId(final MutationIdentifier id) { + return this.id.matches(id); + } + + /** + * Returns the name of the mutator that created this mutation + * + * @return the mutator name + */ + public String getMutator() { + return this.id.getMutator(); + } + + /** + * Returns the index to the first instruction on which this mutation occurs. + * This index is specific to how ASM represents the bytecode. + * + * @return the zero based index to the instruction + */ + public int getFirstIndex() { + return this.id.getFirstIndex(); + } + + /** + * Zero based index to first affected ASM instruction + */ + public int getInstructionIndex() { + return getFirstIndex() - 1; + } + + /** + * Indicates if the mutation is within a finally block + * + * @return true if in finally block otherwise false + */ + public boolean isInFinallyBlock() { + return this.isInFinallyBlock; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((this.id == null) ? 0 : this.id.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MutationDetails other = (MutationDetails) obj; + if (this.id == null) { + if (other.id != null) { + return false; + } + } else if (!this.id.equals(other.id)) { + return false; + } + return true; + } + + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/MutationEngine.java b/pitest/src/main/java/org/pitest/mutationtest/engine/MutationEngine.java index 65760478b..f66f08ffd 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/MutationEngine.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/MutationEngine.java @@ -1,50 +1,50 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine; - -import java.util.Collection; - -import org.pitest.classinfo.ClassByteArraySource; - -/** - * A mutation engine acts as a factory for mutaters capable of creating mutant - * classes. - */ -public interface MutationEngine { - - /** - * Create a mutator using the given ClassByteArraySource as the source of - * unmated classes - * - * @param source - * the source to use to retrieve unmated classes - * @return a Mutater - */ - Mutater createMutator(ClassByteArraySource source); - - /** - * Returns a list of mutation operations this engine can perform - * - * @return a list of mutator names - */ - Collection getMutatorNames(); - - /** - * Returns the name of this engine - * @return The engine name - */ - String getName(); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine; + +import java.util.Collection; + +import org.pitest.classinfo.ClassByteArraySource; + +/** + * A mutation engine acts as a factory for mutaters capable of creating mutant + * classes. + */ +public interface MutationEngine { + + /** + * Create a mutator using the given ClassByteArraySource as the source of + * unmated classes + * + * @param source + * the source to use to retrieve unmated classes + * @return a Mutater + */ + Mutater createMutator(ClassByteArraySource source); + + /** + * Returns a list of mutation operations this engine can perform + * + * @return a list of mutator names + */ + Collection getMutatorNames(); + + /** + * Returns the name of this engine + * @return The engine name + */ + String getName(); + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/MutationIdentifier.java b/pitest/src/main/java/org/pitest/mutationtest/engine/MutationIdentifier.java index d583e0784..504376c97 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/MutationIdentifier.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/MutationIdentifier.java @@ -1,180 +1,180 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.pitest.classinfo.ClassName; - -/** - * Uniquely identifies a mutation - */ -public final class MutationIdentifier implements Comparable, Serializable { - - private static final long serialVersionUID = 1L; - - /** - * The location at which the mutation occurs - */ - private final Location location; - - /** - * The indexes to the instructions within the method at which the mutation - * occurs. - * - * Usually this will be a single instruction, but may be multiple if the - * mutation has been inlined by the compiler to implement a finally block - */ - private final List indexes; - - /** - * Name of the mutation operator that created this mutation - */ - private final String mutator; - - public MutationIdentifier(final Location location, final int index, - final String mutatorUniqueId) { - this(location, Collections.singleton(index), mutatorUniqueId); - } - - public MutationIdentifier(final Location location, - final Collection indexes, final String mutatorUniqueId) { - this.location = location; - this.indexes = new ArrayList<>(indexes); - this.mutator = mutatorUniqueId; - } - - /** - * Returns the location of the mutations - * - * @return the location of the mutation - */ - public Location getLocation() { - return this.location; - } - - /** - * Returns the name of the mutator that created this mutation - * - * @return the mutator name - */ - public String getMutator() { - return this.mutator; - } - - /** - * Returns the index to the first instruction on which this mutation occurs. - * This index is specific to how ASM represents the bytecode. - * - * @return the zero based index to the instruction - */ - public int getFirstIndex() { - return this.indexes.iterator().next(); - } - - @Override - public String toString() { - return "MutationIdentifier [location=" + this.location + ", indexes=" - + this.indexes + ", mutator=" + this.mutator + "]"; - } - - /** - * Returns true if this mutation has a matching identifier - * - * @param id - * the MutationIdentifier to match - * @return true if the MutationIdentifier matches otherwise false - */ - public boolean matches(final MutationIdentifier id) { - return this.location.equals(id.location) && this.mutator.equals(id.mutator) - && this.indexes.contains(id.getFirstIndex()); - } - - /** - * Returns the class in which this mutation is located - * - * @return class in which mutation is located - */ - public ClassName getClassName() { - return this.location.getClassName(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.indexes == null) ? 0 : this.indexes.hashCode()); - result = (prime * result) - + ((this.location == null) ? 0 : this.location.hashCode()); - result = (prime * result) - + ((this.mutator == null) ? 0 : this.mutator.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MutationIdentifier other = (MutationIdentifier) obj; - if (this.indexes == null) { - if (other.indexes != null) { - return false; - } - } else if (!this.indexes.equals(other.indexes)) { - return false; - } - if (this.location == null) { - if (other.location != null) { - return false; - } - } else if (!this.location.equals(other.location)) { - return false; - } - if (this.mutator == null) { - if (other.mutator != null) { - return false; - } - } else if (!this.mutator.equals(other.mutator)) { - return false; - } - return true; - } - - @Override - public int compareTo(final MutationIdentifier other) { - int comp = this.location.compareTo(other.getLocation()); - if (comp != 0) { - return comp; - } - comp = this.mutator.compareTo(other.getMutator()); - if (comp != 0) { - return comp; - } - return this.indexes.get(0).compareTo(other.indexes.get(0)); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.pitest.classinfo.ClassName; + +/** + * Uniquely identifies a mutation + */ +public final class MutationIdentifier implements Comparable, Serializable { + + private static final long serialVersionUID = 1L; + + /** + * The location at which the mutation occurs + */ + private final Location location; + + /** + * The indexes to the instructions within the method at which the mutation + * occurs. + * + * Usually this will be a single instruction, but may be multiple if the + * mutation has been inlined by the compiler to implement a finally block + */ + private final List indexes; + + /** + * Name of the mutation operator that created this mutation + */ + private final String mutator; + + public MutationIdentifier(final Location location, final int index, + final String mutatorUniqueId) { + this(location, Collections.singleton(index), mutatorUniqueId); + } + + public MutationIdentifier(final Location location, + final Collection indexes, final String mutatorUniqueId) { + this.location = location; + this.indexes = new ArrayList<>(indexes); + this.mutator = mutatorUniqueId; + } + + /** + * Returns the location of the mutations + * + * @return the location of the mutation + */ + public Location getLocation() { + return this.location; + } + + /** + * Returns the name of the mutator that created this mutation + * + * @return the mutator name + */ + public String getMutator() { + return this.mutator; + } + + /** + * Returns the index to the first instruction on which this mutation occurs. + * This index is specific to how ASM represents the bytecode. + * + * @return the zero based index to the instruction + */ + public int getFirstIndex() { + return this.indexes.iterator().next(); + } + + @Override + public String toString() { + return "MutationIdentifier [location=" + this.location + ", indexes=" + + this.indexes + ", mutator=" + this.mutator + "]"; + } + + /** + * Returns true if this mutation has a matching identifier + * + * @param id + * the MutationIdentifier to match + * @return true if the MutationIdentifier matches otherwise false + */ + public boolean matches(final MutationIdentifier id) { + return this.location.equals(id.location) && this.mutator.equals(id.mutator) + && this.indexes.contains(id.getFirstIndex()); + } + + /** + * Returns the class in which this mutation is located + * + * @return class in which mutation is located + */ + public ClassName getClassName() { + return this.location.getClassName(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.indexes == null) ? 0 : this.indexes.hashCode()); + result = (prime * result) + + ((this.location == null) ? 0 : this.location.hashCode()); + result = (prime * result) + + ((this.mutator == null) ? 0 : this.mutator.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MutationIdentifier other = (MutationIdentifier) obj; + if (this.indexes == null) { + if (other.indexes != null) { + return false; + } + } else if (!this.indexes.equals(other.indexes)) { + return false; + } + if (this.location == null) { + if (other.location != null) { + return false; + } + } else if (!this.location.equals(other.location)) { + return false; + } + if (this.mutator == null) { + if (other.mutator != null) { + return false; + } + } else if (!this.mutator.equals(other.mutator)) { + return false; + } + return true; + } + + @Override + public int compareTo(final MutationIdentifier other) { + int comp = this.location.compareTo(other.getLocation()); + if (comp != 0) { + return comp; + } + comp = this.mutator.compareTo(other.getMutator()); + if (comp != 0) { + return comp; + } + return this.indexes.get(0).compareTo(other.indexes.get(0)); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/PoisonStatus.java b/pitest/src/main/java/org/pitest/mutationtest/engine/PoisonStatus.java index 7ad9bfac7..3d9057f2b 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/PoisonStatus.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/PoisonStatus.java @@ -1,15 +1,15 @@ -package org.pitest.mutationtest.engine; - -public enum PoisonStatus { - NORMAL(false), MAY_POISON_JVM(true), IS_STATIC_INITIALIZER_CODE(true); - - private final boolean mayPoison; - - PoisonStatus(boolean mayPoison) { - this.mayPoison = mayPoison; - } - - boolean mayPoison() { - return this.mayPoison; - } -} +package org.pitest.mutationtest.engine; + +public enum PoisonStatus { + NORMAL(false), MAY_POISON_JVM(true), IS_STATIC_INITIALIZER_CODE(true); + + private final boolean mayPoison; + + PoisonStatus(boolean mayPoison) { + this.mayPoison = mayPoison; + } + + boolean mayPoison() { + return this.mayPoison; + } +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AbstractInsnMutator.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AbstractInsnMutator.java index 334002343..63567dd6a 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AbstractInsnMutator.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AbstractInsnMutator.java @@ -1,74 +1,79 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import java.util.Map; - -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public abstract class AbstractInsnMutator extends MethodVisitor { - - private final MethodMutatorFactory factory; - private final MutationContext context; - private final MethodInfo methodInfo; - - public AbstractInsnMutator(final MethodMutatorFactory factory, - final MethodInfo methodInfo, final MutationContext context, - final MethodVisitor delegateMethodVisitor) { - super(Opcodes.ASM6, delegateMethodVisitor); - this.factory = factory; - this.methodInfo = methodInfo; - this.context = context; - } - - protected abstract Map getMutations(); - - @Override - public void visitInsn(final int opcode) { - if (canMutate(opcode)) { - createMutationForInsnOpcode(opcode); - } else { - this.mv.visitInsn(opcode); - } - } - - protected boolean canMutate(final int opcode) { - return getMutations().containsKey(opcode); - } - - private void createMutationForInsnOpcode(final int opcode) { - final ZeroOperandMutation mutation = getMutations().get(opcode); - - final MutationIdentifier newId = this.context.registerMutation( - this.factory, mutation.decribe(opcode, this.methodInfo)); - - if (this.context.shouldMutate(newId)) { - mutation.apply(opcode, this.mv); - } else { - applyUnmutatedInstruction(opcode); - } - } - - private void applyUnmutatedInstruction(final int opcode) { - this.mv.visitInsn(opcode); - } - - protected MethodInfo methodInfo() { - return this.methodInfo; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import java.util.Map; + +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.mutationtest.engine.MutationIdentifier; + +/** + * Further implements visitInsn function in ASM, similar to AbstractJumpMutator + * + */ +public abstract class AbstractInsnMutator extends MethodVisitor { + + private final MethodMutatorFactory factory; + private final MutationContext context; + private final MethodInfo methodInfo; + + public AbstractInsnMutator(final MethodMutatorFactory factory, + final MethodInfo methodInfo, final MutationContext context, + final MethodVisitor delegateMethodVisitor, ClassByteArraySource byteSource) { + super(Opcodes.ASM6, delegateMethodVisitor); + this.factory = factory; + this.methodInfo = methodInfo; + this.context = context; + } + + protected abstract Map getMutations(); + + @Override + public void visitInsn(final int opcode) { + if (canMutate(opcode)) { + createMutationForInsnOpcode(opcode); + } else { + this.mv.visitInsn(opcode); + } + } + + protected boolean canMutate(final int opcode) { + return getMutations().containsKey(opcode); + } + + private void createMutationForInsnOpcode(final int opcode) { + final ZeroOperandMutation mutation = getMutations().get(opcode); + + final MutationIdentifier newId = this.context.registerMutation( + this.factory, mutation.decribe(opcode, this.methodInfo)); + + if (this.context.shouldMutate(newId)) { + mutation.apply(opcode, this.mv); + } else { + applyUnmutatedInstruction(opcode); + } + } + + private void applyUnmutatedInstruction(final int opcode) { + this.mv.visitInsn(opcode); + } + + protected MethodInfo methodInfo() { + return this.methodInfo; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AbstractJumpMutator.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AbstractJumpMutator.java index a1e0a2e49..0e2f9d112 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AbstractJumpMutator.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AbstractJumpMutator.java @@ -1,74 +1,77 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import java.util.Map; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public abstract class AbstractJumpMutator extends MethodVisitor { - - private final MethodMutatorFactory factory; - private final MutationContext context; - - public static class Substitution { - public Substitution(final int newCode, final String description) { - this.newCode = newCode; - this.description = description; - } - - private final int newCode; - private final String description; - } - - public AbstractJumpMutator(final MethodMutatorFactory factory, - final MutationContext context, final MethodVisitor writer) { - super(Opcodes.ASM6, writer); - this.factory = factory; - this.context = context; - } - - protected abstract Map getMutations(); - - @Override - public void visitJumpInsn(final int opcode, final Label label) { - if (canMutate(opcode)) { - createMutationForJumpInsn(opcode, label); - } else { - this.mv.visitJumpInsn(opcode, label); - } - } - - private boolean canMutate(final int opcode) { - return this.getMutations().containsKey(opcode); - } - - private void createMutationForJumpInsn(final int opcode, final Label label) { - final Substitution substitution = this.getMutations().get(opcode); - - final MutationIdentifier newId = this.context.registerMutation( - this.factory, substitution.description); - - if (this.context.shouldMutate(newId)) { - this.mv.visitJumpInsn(substitution.newCode, label); - } else { - this.mv.visitJumpInsn(opcode, label); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import java.util.Map; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.mutationtest.engine.MutationIdentifier; + +/** + * Further implements vistJumpInsn in ASM. Similar to AbstractInsnMutator + */ +public abstract class AbstractJumpMutator extends MethodVisitor { + + private final MethodMutatorFactory factory; + private final MutationContext context; + + public static class Substitution { + public Substitution(final int newCode, final String description) { + this.newCode = newCode; + this.description = description; + } + + private final int newCode; + private final String description; + } + + public AbstractJumpMutator(final MethodMutatorFactory factory, + final MutationContext context, final MethodVisitor writer) { + super(Opcodes.ASM6, writer); + this.factory = factory; + this.context = context; + } + + protected abstract Map getMutations(); + + @Override + public void visitJumpInsn(final int opcode, final Label label) { + if (canMutate(opcode)) { + createMutationForJumpInsn(opcode, label); + } else { + this.mv.visitJumpInsn(opcode, label); + } + } + + private boolean canMutate(final int opcode) { + return this.getMutations().containsKey(opcode); + } + + private void createMutationForJumpInsn(final int opcode, final Label label) { + final Substitution substitution = this.getMutations().get(opcode); + + final MutationIdentifier newId = this.context.registerMutation( + this.factory, substitution.description); + + if (this.context.shouldMutate(newId)) { + this.mv.visitJumpInsn(substitution.newCode, label); + } else { + this.mv.visitJumpInsn(opcode, label); + } + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AvoidAssertsMethodAdapter.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AvoidAssertsMethodAdapter.java index e76a5c4b6..86cba54d3 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AvoidAssertsMethodAdapter.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AvoidAssertsMethodAdapter.java @@ -1,86 +1,86 @@ -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -/** - * Disables mutations within java assertions - * - */ -public class AvoidAssertsMethodAdapter extends MethodVisitor { - - private static final String DISABLE_REASON = "ASSERTS"; - - private final MutationContext context; - private boolean assertBlockStarted; - private Label destination; - - public AvoidAssertsMethodAdapter(final MutationContext context, - final MethodVisitor delegateMethodVisitor) { - super(Opcodes.ASM6, delegateMethodVisitor); - this.context = context; - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, - final String name, final String desc, boolean itf) { - - if ((opcode == Opcodes.INVOKEVIRTUAL) && "java/lang/Class".equals(owner) - && "desiredAssertionStatus".equals(name)) { - this.context.disableMutations(DISABLE_REASON); - } - super.visitMethodInsn(opcode, owner, name, desc, itf); - } - - @Override - public void visitFieldInsn(final int opcode, final String owner, - final String name, final String desc) { - - if ("$assertionsDisabled".equals(name)) { - if (opcode == Opcodes.GETSTATIC) { - this.context.disableMutations(DISABLE_REASON); - this.assertBlockStarted = true; - } else if (opcode == Opcodes.PUTSTATIC) { - this.context.enableMutatations(DISABLE_REASON); - } - } - super.visitFieldInsn(opcode, owner, name, desc); - - } - - @Override - public void visitJumpInsn(final int opcode, final Label destination) { - if ((opcode == Opcodes.IFNE) && this.assertBlockStarted) { - this.destination = destination; - this.assertBlockStarted = false; - } - super.visitJumpInsn(opcode, destination); - - } - - @Override - public void visitLabel(final Label label) { - // delegate to child first to ensure visitLabel not in scope for mutation - super.visitLabel(label); - if (this.destination == label) { - this.context.enableMutatations(DISABLE_REASON); - this.destination = null; - } - } - -} +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Disables mutations within java assertions + * + */ +public class AvoidAssertsMethodAdapter extends MethodVisitor { + + private static final String DISABLE_REASON = "ASSERTS"; + + private final MutationContext context; + private boolean assertBlockStarted; + private Label destination; + + public AvoidAssertsMethodAdapter(final MutationContext context, + final MethodVisitor delegateMethodVisitor) { + super(Opcodes.ASM6, delegateMethodVisitor); + this.context = context; + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, + final String name, final String desc, boolean itf) { + + if ((opcode == Opcodes.INVOKEVIRTUAL) && "java/lang/Class".equals(owner) + && "desiredAssertionStatus".equals(name)) { + this.context.disableMutations(DISABLE_REASON); + } + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + + @Override + public void visitFieldInsn(final int opcode, final String owner, + final String name, final String desc) { + + if ("$assertionsDisabled".equals(name)) { + if (opcode == Opcodes.GETSTATIC) { + this.context.disableMutations(DISABLE_REASON); + this.assertBlockStarted = true; + } else if (opcode == Opcodes.PUTSTATIC) { + this.context.enableMutatations(DISABLE_REASON); + } + } + super.visitFieldInsn(opcode, owner, name, desc); + + } + + @Override + public void visitJumpInsn(final int opcode, final Label destination) { + if ((opcode == Opcodes.IFNE) && this.assertBlockStarted) { + this.destination = destination; + this.assertBlockStarted = false; + } + super.visitJumpInsn(opcode, destination); + + } + + @Override + public void visitLabel(final Label label) { + // delegate to child first to ensure visitLabel not in scope for mutation + super.visitLabel(label); + if (this.destination == label) { + this.context.enableMutatations(DISABLE_REASON); + this.destination = null; + } + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AvoidStringSwitchedMethodAdapter.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AvoidStringSwitchedMethodAdapter.java index 14aedd1bf..2cf25ae3a 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AvoidStringSwitchedMethodAdapter.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/AvoidStringSwitchedMethodAdapter.java @@ -1,120 +1,120 @@ -package org.pitest.mutationtest.engine.gregor; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -/** - * Disables mutations in the conditional statements generated - * by java compilers when switching on a string value. - * - * Disable logic looks for a call to hashcode followed immediately by - * a tableswitch or lookupswitch. - * - * Mutation is renabled when the switch block is complete or a new line of code - * is encountered. - * - */ -public class AvoidStringSwitchedMethodAdapter extends MethodVisitor { - - private static final String DISABLE_REASON = "STRING_SWITCH"; - - private final MutationContext context; - - // Set to indicate a call to hashcode has been encountered. - // Unset when other instructions hit so that we can detect if - // calls directly follow each other - private boolean hashCodeWasLastCall; - - private Label end; - - public AvoidStringSwitchedMethodAdapter(final MutationContext context, - final MethodVisitor delegateMethodVisitor) { - super(Opcodes.ASM6, delegateMethodVisitor); - this.context = context; - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, - final String name, final String desc, boolean itf) { - if ((opcode == Opcodes.INVOKEVIRTUAL) && "java/lang/String".equals(owner) - && "hashCode".equals(name)) { - this.hashCodeWasLastCall = true; - } else { - this.hashCodeWasLastCall = false; - } - super.visitMethodInsn(opcode, owner, name, desc, itf); - } - - @Override - public void visitLineNumber(int line, Label start) { - super.visitLineNumber(line, start); - // if compiler emits a line number switch statement (probably) contains user - // generated code - enableMutation(); - } - - @Override - public void visitTableSwitchInsn(int min, int max, Label dflt, - Label... labels) { - - // delegate first so switch statements will be mutated - super.visitTableSwitchInsn(min, max, dflt, labels); - - if (this.hashCodeWasLastCall) { - this.context.disableMutations(DISABLE_REASON); - this.end = dflt; - } - } - - @Override - public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { - // delegate first so switch statements will be mutated - super.visitLookupSwitchInsn(dflt, keys, labels); - - if (this.hashCodeWasLastCall) { - this.context.disableMutations(DISABLE_REASON); - this.end = dflt; - } - } - - @Override - public void visitLabel(final Label label) { - // delegate to child first to ensure visitLabel not in scope for mutation - super.visitLabel(label); - if (this.end == label) { - enableMutation(); - } - } - - @Override - public void visitJumpInsn(int opcode, Label label) { - this.hashCodeWasLastCall = false; - super.visitJumpInsn(opcode, label); - } - - @Override - public void visitIntInsn(int opcode, int operand) { - this.hashCodeWasLastCall = false; - super.visitIntInsn(opcode, operand); - } - - @Override - public void visitInsn(int opcode) { - this.hashCodeWasLastCall = false; - super.visitInsn(opcode); - } - - @Override - public void visitEnd() { - super.visitEnd(); - enableMutation(); - } - - private void enableMutation() { - this.context.enableMutatations(DISABLE_REASON); - this.end = null; - this.hashCodeWasLastCall = false; - } - -} +package org.pitest.mutationtest.engine.gregor; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Disables mutations in the conditional statements generated + * by java compilers when switching on a string value. + * + * Disable logic looks for a call to hashcode followed immediately by + * a tableswitch or lookupswitch. + * + * Mutation is renabled when the switch block is complete or a new line of code + * is encountered. + * + */ +public class AvoidStringSwitchedMethodAdapter extends MethodVisitor { + + private static final String DISABLE_REASON = "STRING_SWITCH"; + + private final MutationContext context; + + // Set to indicate a call to hashcode has been encountered. + // Unset when other instructions hit so that we can detect if + // calls directly follow each other + private boolean hashCodeWasLastCall; + + private Label end; + + public AvoidStringSwitchedMethodAdapter(final MutationContext context, + final MethodVisitor delegateMethodVisitor) { + super(Opcodes.ASM6, delegateMethodVisitor); + this.context = context; + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, + final String name, final String desc, boolean itf) { + if ((opcode == Opcodes.INVOKEVIRTUAL) && "java/lang/String".equals(owner) + && "hashCode".equals(name)) { + this.hashCodeWasLastCall = true; + } else { + this.hashCodeWasLastCall = false; + } + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + + @Override + public void visitLineNumber(int line, Label start) { + super.visitLineNumber(line, start); + // if compiler emits a line number switch statement (probably) contains user + // generated code + enableMutation(); + } + + @Override + public void visitTableSwitchInsn(int min, int max, Label dflt, + Label... labels) { + + // delegate first so switch statements will be mutated + super.visitTableSwitchInsn(min, max, dflt, labels); + + if (this.hashCodeWasLastCall) { + this.context.disableMutations(DISABLE_REASON); + this.end = dflt; + } + } + + @Override + public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { + // delegate first so switch statements will be mutated + super.visitLookupSwitchInsn(dflt, keys, labels); + + if (this.hashCodeWasLastCall) { + this.context.disableMutations(DISABLE_REASON); + this.end = dflt; + } + } + + @Override + public void visitLabel(final Label label) { + // delegate to child first to ensure visitLabel not in scope for mutation + super.visitLabel(label); + if (this.end == label) { + enableMutation(); + } + } + + @Override + public void visitJumpInsn(int opcode, Label label) { + this.hashCodeWasLastCall = false; + super.visitJumpInsn(opcode, label); + } + + @Override + public void visitIntInsn(int opcode, int operand) { + this.hashCodeWasLastCall = false; + super.visitIntInsn(opcode, operand); + } + + @Override + public void visitInsn(int opcode) { + this.hashCodeWasLastCall = false; + super.visitInsn(opcode); + } + + @Override + public void visitEnd() { + super.visitEnd(); + enableMutation(); + } + + private void enableMutation() { + this.context.enableMutatations(DISABLE_REASON); + this.end = null; + this.hashCodeWasLastCall = false; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ClassContext.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ClassContext.java index 951b40b76..11c4b59c4 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ClassContext.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ClassContext.java @@ -1,117 +1,126 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.function.Predicate; - -import org.pitest.functional.FCollection; -import java.util.Optional; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.mutationtest.engine.gregor.blocks.BlockCounter; -import org.pitest.mutationtest.engine.gregor.blocks.ConcreteBlockCounter; - -class ClassContext implements BlockCounter { - - private ClassInfo classInfo; - private String sourceFile; - - private Optional target = Optional.empty(); - private final List mutations = new ArrayList<>(); - - private final ConcreteBlockCounter blockCounter = new ConcreteBlockCounter(); - - public Optional getTargetMutation() { - return this.target; - } - - public ClassInfo getClassInfo() { - return this.classInfo; - } - - public String getJavaClassName() { - return this.classInfo.getName().replace("/", "."); - } - - public String getFileName() { - return this.sourceFile; - } - - public void setTargetMutation(final Optional target) { - this.target = target; - } - - public List getMutationDetails(final MutationIdentifier id) { - return FCollection.filter(this.mutations, hasId(id)); - } - - private static Predicate hasId(final MutationIdentifier id) { - return a -> a.matchesId(id); - } - - public void registerClass(final ClassInfo classInfo) { - this.classInfo = classInfo; - } - - public void registerSourceFile(final String source) { - this.sourceFile = source; - } - - public boolean shouldMutate(final MutationIdentifier newId) { - return getTargetMutation().filter(idMatches(newId)).isPresent(); - } - - private static Predicate idMatches( - final MutationIdentifier newId) { - return a -> a.matches(newId); - } - - public Collection getCollectedMutations() { - return this.mutations; - } - - public void addMutation(final MutationDetails details) { - this.mutations.add(details); - - } - - @Override - public void registerNewBlock() { - this.blockCounter.registerNewBlock(); - - } - - @Override - public void registerFinallyBlockStart() { - this.blockCounter.registerFinallyBlockStart(); - } - - @Override - public void registerFinallyBlockEnd() { - this.blockCounter.registerFinallyBlockEnd(); - } - - public int getCurrentBlock() { - return this.blockCounter.getCurrentBlock(); - } - - public boolean isWithinFinallyBlock() { - return this.blockCounter.isWithinFinallyBlock(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Predicate; + +import org.pitest.functional.FCollection; +import java.util.Optional; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.mutationtest.engine.gregor.blocks.BlockCounter; +import org.pitest.mutationtest.engine.gregor.blocks.ConcreteBlockCounter; + +class ClassContext implements BlockCounter { + + private ClassInfo classInfo; + private String sourceFile; + + private Optional target = Optional.empty(); + private final List mutations = new ArrayList<>(); + + private final ConcreteBlockCounter blockCounter = new ConcreteBlockCounter(); + + public Optional getTargetMutation() { + return this.target; + } + + public ClassInfo getClassInfo() { + return this.classInfo; + } + + /** + * Get the fully qualified name of a class, then replace "/" with "." so it can + * be written to the bytecode. It's very helpful for constructing the owner and + * class name for GETFIELD, PUTFIELD, INVOKE... + * + * @return fully qualified class name with "/" instead of "." + */ + public String getJavaClassName() { + return this.classInfo.getName().replace("/", "."); + } + + public String getFileName() { + return this.sourceFile; + } + + public void setTargetMutation(final Optional target) { + this.target = target; + } + + public List getMutationDetails(final MutationIdentifier id) { + return FCollection.filter(this.mutations, hasId(id)); + } + + private static Predicate hasId(final MutationIdentifier id) { + return a -> a.matchesId(id); + } + + public void registerClass(final ClassInfo classInfo) { + this.classInfo = classInfo; + } + + public void registerSourceFile(final String source) { + this.sourceFile = source; + } + + public boolean shouldMutate(final MutationIdentifier newId) { + return getTargetMutation().filter(idMatches(newId)).isPresent(); + } + + private static Predicate idMatches(final MutationIdentifier newId) { + return a -> a.matches(newId); + } + + /** + * Return a collection of mutations. + */ + public Collection getCollectedMutations() { + return this.mutations; + } + + public void addMutation(final MutationDetails details) { + this.mutations.add(details); + + } + + @Override + public void registerNewBlock() { + this.blockCounter.registerNewBlock(); + + } + + @Override + public void registerFinallyBlockStart() { + this.blockCounter.registerFinallyBlockStart(); + } + + @Override + public void registerFinallyBlockEnd() { + this.blockCounter.registerFinallyBlockEnd(); + } + + public int getCurrentBlock() { + return this.blockCounter.getCurrentBlock(); + } + + public boolean isWithinFinallyBlock() { + return this.blockCounter.isWithinFinallyBlock(); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ClassInfo.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ClassInfo.java index 92cc45267..a481ce0d6 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ClassInfo.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ClassInfo.java @@ -1,63 +1,76 @@ -package org.pitest.mutationtest.engine.gregor; - -import java.util.function.Predicate; - -import org.pitest.functional.FArray; - -public class ClassInfo { - - private final int version; - private final int access; - private final String name; - private final String signature; - private final String superName; - private final String[] interfaces; - - public ClassInfo(final int version, final int access, final String name, - final String signature, final String superName, final String[] interfaces) { - this.version = version; - this.access = access; - this.name = name; - this.signature = signature; - this.superName = superName; - this.interfaces = interfaces; - } - - public boolean isEnum() { - return this.superName.equals("java/lang/Enum"); - } - - public boolean isGroovyClass() { - return FArray.contains(this.interfaces, isAGroovyClass()); - } - - private static Predicate isAGroovyClass() { - return a -> a.startsWith("groovy/lang/") - || a.startsWith("org/codehaus/groovy/runtime"); - } - - public int getVersion() { - return this.version; - } - - public int getAccess() { - return this.access; - } - - public String getName() { - return this.name; - } - - public String getSignature() { - return this.signature; - } - - public String getSuperName() { - return this.superName; - } - - public String[] getInterfaces() { - return this.interfaces; - } - -} +package org.pitest.mutationtest.engine.gregor; + +import java.util.function.Predicate; + +import org.pitest.functional.FArray; + +/** + * Contains all information about a class. Also contain a method to convert a + * Java class to Groovy class and methods to extract different parts of a class. + * Notice the constructor is private. + */ +public class ClassInfo { + + private final int version; + private final int access; + private final String name; + private final String signature; + private final String superName; + private final String[] interfaces; + + /** + * Construct a ClassInfo object with all information about the class. + * @param version + * @param access + * @param name + * @param signature + * @param superName + * @param interfaces + */ + public ClassInfo(final int version, final int access, final String name, final String signature, + final String superName, final String[] interfaces) { + this.version = version; + this.access = access; + this.name = name; + this.signature = signature; + this.superName = superName; + this.interfaces = interfaces; + } + + public boolean isEnum() { + return this.superName.equals("java/lang/Enum"); + } + + public boolean isGroovyClass() { + return FArray.contains(this.interfaces, isAGroovyClass()); + } + + private static Predicate isAGroovyClass() { + return a -> a.startsWith("groovy/lang/") || a.startsWith("org/codehaus/groovy/runtime"); + } + + public int getVersion() { + return this.version; + } + + public int getAccess() { + return this.access; + } + + public String getName() { + return this.name; + } + + public String getSignature() { + return this.signature; + } + + public String getSuperName() { + return this.superName; + } + + public String[] getInterfaces() { + return this.interfaces; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/GregorMutater.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/GregorMutater.java index 0debd7657..3b9568c45 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/GregorMutater.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/GregorMutater.java @@ -1,137 +1,171 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import static org.pitest.functional.prelude.Prelude.and; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.pitest.bytecode.FrameOptions; -import org.pitest.bytecode.NullVisitor; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.ComputeClassWriter; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; - -public class GregorMutater implements Mutater { - - private final Map computeCache = new HashMap<>(); - private final Predicate filter; - private final ClassByteArraySource byteSource; - private final Set mutators = new HashSet<>(); - - public GregorMutater(final ClassByteArraySource byteSource, - final Predicate filter, - final Collection mutators) { - this.filter = filter; - this.mutators.addAll(mutators); - this.byteSource = byteSource; - } - - @Override - public List findMutations( - final ClassName classToMutate) { - - final ClassContext context = new ClassContext(); - context.setTargetMutation(Optional. empty()); - Optional bytes = GregorMutater.this.byteSource.getBytes( - classToMutate.asInternalName()); - - return bytes.map(findMutations(context)) - .orElse(Collections.emptyList()); - - } - - private Function> findMutations( - final ClassContext context) { - return bytes -> findMutationsForBytes(context, bytes); - } - - private List findMutationsForBytes( - final ClassContext context, final byte[] classToMutate) { - - final ClassReader first = new ClassReader(classToMutate); - final NullVisitor nv = new NullVisitor(); - final MutatingClassVisitor mca = new MutatingClassVisitor(nv, context, - filterMethods(), this.mutators); - - first.accept(mca, ClassReader.EXPAND_FRAMES); - - return new ArrayList<>(context.getCollectedMutations()); - } - - @Override - public Mutant getMutation(final MutationIdentifier id) { - - final ClassContext context = new ClassContext(); - context.setTargetMutation(Optional.ofNullable(id)); - - final Optional bytes = this.byteSource.getBytes(id.getClassName() - .asJavaName()); - - final ClassReader reader = new ClassReader(bytes.get()); - final ClassWriter w = new ComputeClassWriter(this.byteSource, - this.computeCache, FrameOptions.pickFlags(bytes.get())); - final MutatingClassVisitor mca = new MutatingClassVisitor(w, context, - filterMethods(), FCollection.filter(this.mutators, - isMutatorFor(id))); - reader.accept(mca, ClassReader.EXPAND_FRAMES); - - final List details = context.getMutationDetails(context - .getTargetMutation().get()); - - return new Mutant(details.get(0), w.toByteArray()); - - } - - private static Predicate isMutatorFor( - final MutationIdentifier id) { - return a -> id.getMutator().equals(a.getGloballyUniqueId()); - } - - private Predicate filterMethods() { - return and(this.filter, filterSyntheticMethods(), - isGeneratedEnumMethod().negate(), isGroovyClass().negate()); - } - - private static Predicate isGroovyClass() { - return a -> a.isInGroovyClass(); - } - - private static Predicate filterSyntheticMethods() { - return a -> !a.isSynthetic() || a.getName().startsWith("lambda$"); - } - - private static Predicate isGeneratedEnumMethod() { - return a -> a.isGeneratedEnumMethod(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import static org.pitest.functional.prelude.Prelude.and; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.pitest.bytecode.FrameOptions; +import org.pitest.bytecode.NullVisitor; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.ComputeClassWriter; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; + +/** + * Use ClassByteArraySource byteSource interface to replace methods name and + * method descriptor in code. ByteSource is an interface and therefore can + * accept CatchingByteArraySource, ClassloaderByteArraySource, + * ClassPathByteArraySource, ResourceFolderByteArraySource + */ +public class GregorMutater implements Mutater { + + private final Map computeCache = new HashMap<>(); + private final Predicate filter; + private final ClassByteArraySource byteSource; + + private final Set mutators = new HashSet<>(); + + public GregorMutater(final ClassByteArraySource byteSource, final Predicate filter, + final Collection mutators) { + System.out.println(byteSource.toString()); + this.filter = filter; + this.mutators.addAll(mutators); + this.byteSource = byteSource; + } + + /** + * Implements the interface and use Optional object to find the mutation. + * + * @see org.pitest.mutationtest.engine.Mutater#findMutations(org.pitest.classinfo. + * ClassName) + */ + @Override + public List findMutations(final ClassName classToMutate) { + + final ClassContext context = new ClassContext(); + context.setTargetMutation(Optional.empty()); + Optional bytes = GregorMutater.this.byteSource.getBytes(classToMutate.asInternalName()); + + return bytes.map(findMutations(context)).orElse(Collections.emptyList()); + + } + + /** + * Function interface, return a list of input and a list of output + * + * @param context + * A ClassContext input to be used in the function + * findMutationForBytes + * @return Function> A function interface with + * input as an array of byte[], output to List ??? not + * sure about this + */ + private Function> findMutations(final ClassContext context) { + return bytes -> findMutationsForBytes(context, bytes); + } + + /** + * Used as a lambda function for findMutations. Read the stream of byte[] from a + * class then save the mutations in an ArrayList in ClassContext object. Then + * return the ArrayList. + * + * @param context + * ClassContext to save the mutations. + * @param classToMutat + * An array of byte to scan for possible mutations. + * @return List A list of mutations saved in the "context" + * parameter + */ + private List findMutationsForBytes(final ClassContext context, final byte[] classToMutate) { + + final ClassReader first = new ClassReader(classToMutate); + final NullVisitor nv = new NullVisitor(); + final MutatingClassVisitor mca = new MutatingClassVisitor(nv, context, filterMethods(), this.mutators, + this.byteSource); + + first.accept(mca, ClassReader.EXPAND_FRAMES); + + return new ArrayList<>(context.getCollectedMutations()); + } + + /** + * Use the optimization pattern similar to page 21 of ASM user guide. + */ + @Override + public Mutant getMutation(final MutationIdentifier id) { + final ClassContext context = new ClassContext(); + context.setTargetMutation(Optional.ofNullable(id)); + + final Optional bytes = this.byteSource.getBytes(id.getClassName().asJavaName()); + + final ClassReader reader = new ClassReader(bytes.get()); + final ClassWriter w = new ComputeClassWriter(this.byteSource, this.computeCache, + FrameOptions.pickFlags(bytes.get())); + final MutatingClassVisitor mca = new MutatingClassVisitor(w, context, filterMethods(), + FCollection.filter(this.mutators, isMutatorFor(id)), this.byteSource); + reader.accept(mca, ClassReader.EXPAND_FRAMES); + final List details = context.getMutationDetails(context.getTargetMutation().get()); + return new Mutant(details.get(0), w.toByteArray()); + + } + + /** + * @return Return the byteSource object. Useful for extracting data about the + * current class and potentially manipulate it (methods, overloading + * methods/constructors) + */ + public ClassByteArraySource getByteSource() { + return this.byteSource; + } + + private static Predicate isMutatorFor(final MutationIdentifier id) { + return a -> id.getMutator().equals(a.getGloballyUniqueId()); + } + + private Predicate filterMethods() { + return and(this.filter, filterSyntheticMethods(), isGeneratedEnumMethod().negate(), isGroovyClass().negate()); + } + + private static Predicate isGroovyClass() { + return a -> a.isInGroovyClass(); + } + + private static Predicate filterSyntheticMethods() { + return a -> !a.isSynthetic() || a.getName().startsWith("lambda$"); + } + + private static Predicate isGeneratedEnumMethod() { + return a -> a.isGeneratedEnumMethod(); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/GregorMutationEngine.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/GregorMutationEngine.java index 214af64b9..8f0e50690 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/GregorMutationEngine.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/GregorMutationEngine.java @@ -1,70 +1,70 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationEngine; - -/** - * The default (and currently only) mutation engine for PIT. - * - * In case anyone was wondering I'm named after either Gregor Mendel or Gregor - * Samsa, or maybe both. - */ -public class GregorMutationEngine implements MutationEngine { - - private final Set mutationOperators = new LinkedHashSet<>(); - private final Predicate methodFilter; - - public GregorMutationEngine(final MutationEngineConfiguration config) { - this.methodFilter = config.methodFilter(); - this.mutationOperators.addAll(config.mutators()); - } - - @Override - public Mutater createMutator(final ClassByteArraySource byteSource) { - return new GregorMutater(byteSource, this.methodFilter, - this.mutationOperators); - } - - @Override - public String toString() { - return "GregorMutationEngine [filter=" + this.methodFilter - + ", mutationOperators=" + this.mutationOperators + "]"; - } - - @Override - public Collection getMutatorNames() { - return FCollection.map(this.mutationOperators, toName()); - } - - private static Function toName() { - return a -> a.getName(); - } - - @Override - public String getName() { - return "gregor"; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationEngine; + +/** + * The default (and currently only) mutation engine for PIT. + * + * In case anyone was wondering I'm named after either Gregor Mendel or Gregor + * Samsa, or maybe both. + */ +public class GregorMutationEngine implements MutationEngine { + + private final Set mutationOperators = new LinkedHashSet<>(); + private final Predicate methodFilter; + + public GregorMutationEngine(final MutationEngineConfiguration config) { + this.methodFilter = config.methodFilter(); + this.mutationOperators.addAll(config.mutators()); + } + + @Override + public Mutater createMutator(final ClassByteArraySource byteSource) { + return new GregorMutater(byteSource, this.methodFilter, + this.mutationOperators); + } + + @Override + public String toString() { + return "GregorMutationEngine [filter=" + this.methodFilter + + ", mutationOperators=" + this.mutationOperators + "]"; + } + + @Override + public Collection getMutatorNames() { + return FCollection.map(this.mutationOperators, toName()); + } + + private static Function toName() { + return a -> a.getName(); + } + + @Override + public String getName() { + return "gregor"; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/InsnSubstitution.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/InsnSubstitution.java index f7a10cc15..f0d8b60c1 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/InsnSubstitution.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/InsnSubstitution.java @@ -1,3 +1,4 @@ + /* * Copyright 2010 Henry Coles * @@ -16,6 +17,9 @@ import org.objectweb.asm.MethodVisitor; +/* + * Substitute an opcode with another opcode. This can delete an operation. + */ public class InsnSubstitution implements ZeroOperandMutation { private final int replacementOpcode; @@ -37,3 +41,4 @@ public String decribe(final int opCode, final MethodInfo methodInfo) { } } + diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/LineTrackingMethodVisitor.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/LineTrackingMethodVisitor.java index 02a21eb6a..5a4cabe8d 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/LineTrackingMethodVisitor.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/LineTrackingMethodVisitor.java @@ -1,37 +1,37 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -public class LineTrackingMethodVisitor extends MethodVisitor { - - private final MutationContext context; - - public LineTrackingMethodVisitor(final MutationContext context, - final MethodVisitor delegateMethodVisitor) { - super(Opcodes.ASM6, delegateMethodVisitor); - this.context = context; - } - - @Override - public void visitLineNumber(final int line, final Label start) { - this.context.registerCurrentLine(line); - this.mv.visitLineNumber(line, start); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +public class LineTrackingMethodVisitor extends MethodVisitor { + + private final MutationContext context; + + public LineTrackingMethodVisitor(final MutationContext context, + final MethodVisitor delegateMethodVisitor) { + super(Opcodes.ASM6, delegateMethodVisitor); + this.context = context; + } + + @Override + public void visitLineNumber(final int line, final Label start) { + this.context.registerCurrentLine(line); + this.mv.visitLineNumber(line, start); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodInfo.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodInfo.java index e67bb698a..4e8fcee2a 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodInfo.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodInfo.java @@ -1,132 +1,161 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - -public class MethodInfo { - - private final ClassInfo owningClass; - private final int access; - private final String methodName; - private final String methodDescriptor; - - public MethodInfo() { - this(new ClassInfo(0, 0, "", "", "", new String[0]), 0, "", "()V"); - } - - private MethodInfo(final ClassInfo owningClass, final int access, - final String name, final String methodDescriptor) { - this.owningClass = owningClass; - this.access = access; - this.methodName = name; - this.methodDescriptor = methodDescriptor; - } - - public String getDescription() { - return this.owningClass.getName() + "::" + getName(); - } - - public String getName() { - return this.methodName; - } - - public String getMethodDescriptor() { - return this.methodDescriptor; - } - - @Override - public String toString() { - return "MethodInfo [access=" + this.access + ", desc=" - + this.methodDescriptor + ", name=" + this.methodName + "]"; - } - - public boolean isStatic() { - return ((this.access & Opcodes.ACC_STATIC) != 0); - } - - public boolean isSynthetic() { - return ((this.access & Opcodes.ACC_SYNTHETIC) != 0); - } - - public boolean isConstructor() { - return isConstructor(this.methodName); - } - - public static boolean isConstructor(final String methodName) { - return "".equals(methodName); - } - - public Type getReturnType() { - return Type.getReturnType(this.methodDescriptor); - } - - public static boolean isVoid(final String desc) { - return Type.getReturnType(desc).equals(Type.VOID_TYPE); - } - - public boolean isStaticInitializer() { - return "".equals(this.methodName); - } - - public boolean isVoid() { - return isVoid(this.methodDescriptor); - } - - public boolean takesNoParameters() { - return this.methodDescriptor.startsWith("()"); - } - - public boolean isInGroovyClass() { - return this.owningClass.isGroovyClass(); - } - - public boolean isGeneratedEnumMethod() { - return this.owningClass.isEnum() - && (isValuesMethod() || isValueOfMethod() || isStaticInitializer()); - } - - private boolean isValuesMethod() { - return this.getName().equals("values") && takesNoParameters() && isStatic(); - } - - private boolean isValueOfMethod() { - return this.getName().equals("valueOf") - && this.methodDescriptor.startsWith("(Ljava/lang/String;)") - && isStatic(); - } - - public MethodInfo withMethodDescriptor(final String newDescriptor) { - return new MethodInfo(this.owningClass, this.access, this.methodName, - newDescriptor); - } - - public MethodInfo withAccess(final int accessModifier) { - return new MethodInfo(this.owningClass, accessModifier, this.methodName, - this.methodDescriptor); - } - - public MethodInfo withMethodName(final String newMethodName) { - return new MethodInfo(this.owningClass, this.access, newMethodName, - this.methodDescriptor); - } - - public MethodInfo withOwner(final ClassInfo newOwnerClass) { - return new MethodInfo(newOwnerClass, this.access, this.methodName, - this.methodDescriptor); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; + +/** + * Extract different parts of a method. + * + */ +public class MethodInfo { + + private final ClassInfo owningClass; + private final int access; + private final String methodName; + private final String methodDescriptor; + + public MethodInfo() { + this(new ClassInfo(0, 0, "", "", "", new String[0]), 0, "", "()V"); + } + + private MethodInfo(final ClassInfo owningClass, final int access, + final String name, final String methodDescriptor) { + this.owningClass = owningClass; + this.access = access; + this.methodName = name; + this.methodDescriptor = methodDescriptor; + } + + public String getDescription() { + return this.owningClass.getName() + "::" + getName(); + } + + public String getName() { + return this.methodName; + } + + public String getMethodDescriptor() { + return this.methodDescriptor; + } + + @Override + public String toString() { + return "MethodInfo [access=" + this.access + ", desc=" + + this.methodDescriptor + ", name=" + this.methodName + "]"; + } + + /** + * Check if this method is static + * @return is this method static? + */ + public boolean isStatic() { + return ((this.access & Opcodes.ACC_STATIC) != 0); + } + + /** + * Check this method is synthetic + * @return is it synthetic? + */ + public boolean isSynthetic() { + return ((this.access & Opcodes.ACC_SYNTHETIC) != 0); + } + + /** + * Check if this method is a constructor. + * @return is this a constructor? + */ + public boolean isConstructor() { + return isConstructor(this.methodName); + } + /** + * Check if this method contains init in the class file (constructor) + * @param methodName method name + * @return is this a constructor? + */ + public static boolean isConstructor(final String methodName) { + return "".equals(methodName); + } + + /** + * Use ASM getReturnType function to get the return type. + * @return return type + */ + public Type getReturnType() { + return Type.getReturnType(this.methodDescriptor); + } + + /** + * Check if a method returns void using ASM Type.VOID_TYPE + * @param desc method name? + * @return a method is void or not. + */ + public static boolean isVoid(final String desc) { + return Type.getReturnType(desc).equals(Type.VOID_TYPE); + } + + public boolean isStaticInitializer() { + return "".equals(this.methodName); + } + + public boolean isVoid() { + return isVoid(this.methodDescriptor); + } + + public boolean takesNoParameters() { + return this.methodDescriptor.startsWith("()"); + } + + public boolean isInGroovyClass() { + return this.owningClass.isGroovyClass(); + } + + public boolean isGeneratedEnumMethod() { + return this.owningClass.isEnum() + && (isValuesMethod() || isValueOfMethod() || isStaticInitializer()); + } + + private boolean isValuesMethod() { + return this.getName().equals("values") && takesNoParameters() && isStatic(); + } + + private boolean isValueOfMethod() { + return this.getName().equals("valueOf") + && this.methodDescriptor.startsWith("(Ljava/lang/String;)") + && isStatic(); + } + + public MethodInfo withMethodDescriptor(final String newDescriptor) { + return new MethodInfo(this.owningClass, this.access, this.methodName, + newDescriptor); + } + + public MethodInfo withAccess(final int accessModifier) { + return new MethodInfo(this.owningClass, accessModifier, this.methodName, + this.methodDescriptor); + } + + public MethodInfo withMethodName(final String newMethodName) { + return new MethodInfo(this.owningClass, this.access, newMethodName, + this.methodDescriptor); + } + + public MethodInfo withOwner(final ClassInfo newOwnerClass) { + return new MethodInfo(newOwnerClass, this.access, this.methodName, + this.methodDescriptor); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodMutationContext.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodMutationContext.java index 4c7058f34..2393214c9 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodMutationContext.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodMutationContext.java @@ -1,108 +1,108 @@ -package org.pitest.mutationtest.engine.gregor; - -import java.util.HashSet; -import java.util.Set; - -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.mutationtest.engine.PoisonStatus; -import org.pitest.mutationtest.engine.gregor.analysis.InstructionCounter; - -class MethodMutationContext implements MutationContext, InstructionCounter { - - private final ClassContext classContext; - private final Location location; - - private int instructionIndex; - - private int lastLineNumber; - private final Set mutationFindingDisabledReasons = new HashSet<>(); - - MethodMutationContext(final ClassContext classContext, final Location location) { - this.classContext = classContext; - this.location = location; - } - - @Override - public MutationIdentifier registerMutation( - final MethodMutatorFactory factory, final String description) { - final MutationIdentifier newId = getNextMutationIdentifer(factory, - this.classContext.getJavaClassName()); - final MutationDetails details = new MutationDetails(newId, - this.classContext.getFileName(), description, this.lastLineNumber, - this.classContext.getCurrentBlock(), - this.classContext.isWithinFinallyBlock(), PoisonStatus.NORMAL); - registerMutation(details); - return newId; - } - - private MutationIdentifier getNextMutationIdentifer( - final MethodMutatorFactory factory, final String className) { - return new MutationIdentifier(this.location, this.instructionIndex, - factory.getGloballyUniqueId()); - } - - private void registerMutation(final MutationDetails details) { - if (!isMutationFindingDisabled()) { - this.classContext.addMutation(details); - } - } - - private boolean isMutationFindingDisabled() { - return !this.mutationFindingDisabledReasons.isEmpty(); - } - - @Override - public void registerCurrentLine(final int line) { - this.lastLineNumber = line; - } - - @Override - public void registerNewBlock() { - this.classContext.registerNewBlock(); - - } - - @Override - public void registerFinallyBlockStart() { - this.classContext.registerFinallyBlockStart(); - } - - @Override - public void registerFinallyBlockEnd() { - this.classContext.registerFinallyBlockEnd(); - } - - @Override - public ClassInfo getClassInfo() { - return this.classContext.getClassInfo(); - } - - @Override - public boolean shouldMutate(final MutationIdentifier newId) { - return this.classContext.shouldMutate(newId); - } - - @Override - public void disableMutations(final String reason) { - this.mutationFindingDisabledReasons.add(reason); - } - - @Override - public void enableMutatations(final String reason) { - this.mutationFindingDisabledReasons.remove(reason); - } - - @Override - public void increment() { - this.instructionIndex = this.instructionIndex + 1; - - } - - @Override - public int currentInstructionCount() { - return this.instructionIndex; - } - -} +package org.pitest.mutationtest.engine.gregor; + +import java.util.HashSet; +import java.util.Set; + +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.mutationtest.engine.PoisonStatus; +import org.pitest.mutationtest.engine.gregor.analysis.InstructionCounter; + +class MethodMutationContext implements MutationContext, InstructionCounter { + + private final ClassContext classContext; + private final Location location; + + private int instructionIndex; + + private int lastLineNumber; + private final Set mutationFindingDisabledReasons = new HashSet<>(); + + MethodMutationContext(final ClassContext classContext, final Location location) { + this.classContext = classContext; + this.location = location; + } + + @Override + public MutationIdentifier registerMutation( + final MethodMutatorFactory factory, final String description) { + final MutationIdentifier newId = getNextMutationIdentifer(factory, + this.classContext.getJavaClassName()); + final MutationDetails details = new MutationDetails(newId, + this.classContext.getFileName(), description, this.lastLineNumber, + this.classContext.getCurrentBlock(), + this.classContext.isWithinFinallyBlock(), PoisonStatus.NORMAL); + registerMutation(details); + return newId; + } + + private MutationIdentifier getNextMutationIdentifer( + final MethodMutatorFactory factory, final String className) { + return new MutationIdentifier(this.location, this.instructionIndex, + factory.getGloballyUniqueId()); + } + + private void registerMutation(final MutationDetails details) { + if (!isMutationFindingDisabled()) { + this.classContext.addMutation(details); + } + } + + private boolean isMutationFindingDisabled() { + return !this.mutationFindingDisabledReasons.isEmpty(); + } + + @Override + public void registerCurrentLine(final int line) { + this.lastLineNumber = line; + } + + @Override + public void registerNewBlock() { + this.classContext.registerNewBlock(); + + } + + @Override + public void registerFinallyBlockStart() { + this.classContext.registerFinallyBlockStart(); + } + + @Override + public void registerFinallyBlockEnd() { + this.classContext.registerFinallyBlockEnd(); + } + + @Override + public ClassInfo getClassInfo() { + return this.classContext.getClassInfo(); + } + + @Override + public boolean shouldMutate(final MutationIdentifier newId) { + return this.classContext.shouldMutate(newId); + } + + @Override + public void disableMutations(final String reason) { + this.mutationFindingDisabledReasons.add(reason); + } + + @Override + public void enableMutatations(final String reason) { + this.mutationFindingDisabledReasons.remove(reason); + } + + @Override + public void increment() { + this.instructionIndex = this.instructionIndex + 1; + + } + + @Override + public int currentInstructionCount() { + return this.instructionIndex; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodMutatorFactory.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodMutatorFactory.java index e0f934d96..9ae548497 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodMutatorFactory.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MethodMutatorFactory.java @@ -1,3 +1,4 @@ + /* * Copyright 2010 Henry Coles * @@ -15,6 +16,7 @@ package org.pitest.mutationtest.engine.gregor; import org.objectweb.asm.MethodVisitor; +import org.pitest.classinfo.ClassByteArraySource; /** * A MethodMutatorFactory is a factory creating method mutating @@ -29,27 +31,41 @@ * name will be used in the reports created to document and describe the * mutation(s) applied. *

+ * + * Also implement this interface and InsnSubstitution to replace bytecode on the + * spot. * * @author Henry Coles */ public interface MethodMutatorFactory { - MethodVisitor create(MutationContext context, - MethodInfo methodInfo, MethodVisitor methodVisitor); + /** + * To be implemented in various mutators in their own package. Visit a method and create mutations. + */ + MethodVisitor create(MutationContext context, MethodInfo methodInfo, MethodVisitor methodVisitor, ClassByteArraySource byteSource); - String getGloballyUniqueId(); + /** + * To be implemented in various mutators in their own packages, usually in the + * form Object.getClass().getName(). It seems that this method is used to get + * the fully qualified classname of an object. + * + * This is already implemented in Object class. I wonder why this is in the + * interface. + * + * @return a fully qualified class name of the mutator (I hope I got this right) + */ + String getGloballyUniqueId(); - /** - * Returns a human readable String representation of this - * MethodMutatorFactory. The return value of this method will be - * used in reports to document and describe the mutation(s) applied by the - * MethodVisitor created by this - * MethodMutatorFactory. - * - * - * @return a human readable string representation for end-user report - * generation. - */ - String getName(); + /** + * Returns a human readable String representation of this + * MethodMutatorFactory. The return value of this method will be + * used in reports to document and describe the mutation(s) applied by the + * MethodVisitor created by this MethodMutatorFactory. + * + * + * @return a human readable string representation for end-user report + * generation. + */ + String getName(); } diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutatingClassVisitor.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutatingClassVisitor.java index 766a6e22a..907c126d3 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutatingClassVisitor.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutatingClassVisitor.java @@ -1,133 +1,136 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Predicate; - -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.mutationtest.engine.gregor.analysis.InstructionTrackingMethodVisitor; -import org.pitest.mutationtest.engine.gregor.blocks.BlockTrackingMethodDecorator; - -class MutatingClassVisitor extends ClassVisitor { - - private final Predicate filter; - private final ClassContext context; - private final Set methodMutators = new HashSet<>(); - - MutatingClassVisitor(final ClassVisitor delegateClassVisitor, - final ClassContext context, final Predicate filter, - final Collection mutators) { - super(Opcodes.ASM6, delegateClassVisitor); - this.context = context; - this.filter = filter; - this.methodMutators.addAll(mutators); - } - - @Override - public void visit(final int version, final int access, final String name, - final String signature, final String superName, final String[] interfaces) { - super.visit(version, access, name, signature, superName, interfaces); - this.context.registerClass(new ClassInfo(version, access, name, signature, - superName, interfaces)); - } - - @Override - public void visitSource(final String source, final String debug) { - super.visitSource(source, debug); - this.context.registerSourceFile(source); - } - - @Override - public MethodVisitor visitMethod(final int access, final String methodName, - final String methodDescriptor, final String signature, - final String[] exceptions) { - - final MethodMutationContext methodContext = new MethodMutationContext( - this.context, Location.location( - ClassName.fromString(this.context.getClassInfo().getName()), - MethodName.fromString(methodName), methodDescriptor)); - - final MethodVisitor methodVisitor = this.cv.visitMethod(access, methodName, - methodDescriptor, signature, exceptions); - - final MethodInfo info = new MethodInfo() - .withOwner(this.context.getClassInfo()).withAccess(access) - .withMethodName(methodName).withMethodDescriptor(methodDescriptor); - - if (this.filter.test(info)) { - return this.visitMethodForMutation(methodContext, info, methodVisitor); - } else { - return methodVisitor; - } - - } - - private MethodVisitor visitMethodForMutation( - MethodMutationContext methodContext, final MethodInfo methodInfo, - final MethodVisitor methodVisitor) { - - MethodVisitor next = methodVisitor; - for (final MethodMutatorFactory each : this.methodMutators) { - next = each.create(methodContext, methodInfo, next); - } - - return new InstructionTrackingMethodVisitor(wrapWithDecorators( - methodContext, wrapWithFilters(methodContext, next)), methodContext); - } - - private static MethodVisitor wrapWithDecorators(MethodMutationContext methodContext, - final MethodVisitor mv) { - return wrapWithBlockTracker(methodContext, - wrapWithLineTracker(methodContext, mv)); - } - - private static MethodVisitor wrapWithBlockTracker( - MethodMutationContext methodContext, final MethodVisitor mv) { - return new BlockTrackingMethodDecorator(methodContext, mv); - } - - private static MethodVisitor wrapWithLineTracker( - MethodMutationContext methodContext, final MethodVisitor mv) { - return new LineTrackingMethodVisitor(methodContext, mv); - } - - private MethodVisitor wrapWithFilters(MethodMutationContext methodContext, - final MethodVisitor wrappedMethodVisitor) { - return - wrapWithStringSwitchFilter(methodContext, wrapWithAssertFilter(methodContext, wrappedMethodVisitor)); - } - - private static MethodVisitor wrapWithStringSwitchFilter( - MethodMutationContext methodContext, - final MethodVisitor wrappedMethodVisitor) { - return new AvoidStringSwitchedMethodAdapter(methodContext, wrappedMethodVisitor); - - } - - private static MethodVisitor wrapWithAssertFilter( - MethodMutationContext methodContext, - final MethodVisitor wrappedMethodVisitor) { - return new AvoidAssertsMethodAdapter(methodContext, wrappedMethodVisitor); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Predicate; + +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.mutationtest.engine.gregor.analysis.InstructionTrackingMethodVisitor; +import org.pitest.mutationtest.engine.gregor.blocks.BlockTrackingMethodDecorator; + +/** + * This is an adapter/filter according to ASM user manual. Visit a class and + * create mutations. + * + */ +public class MutatingClassVisitor extends ClassVisitor { + + private final Predicate filter; + private final ClassContext context; + private final Set methodMutators = new HashSet<>(); + private ClassByteArraySource byteSource; + + MutatingClassVisitor(final ClassVisitor delegateClassVisitor, final ClassContext context, + final Predicate filter, final Collection mutators, + ClassByteArraySource byteSource) { + super(Opcodes.ASM6, delegateClassVisitor); + this.context = context; + this.filter = filter; + this.methodMutators.addAll(mutators); + this.byteSource = byteSource; + } + + @Override + public void visit(final int version, final int access, final String name, final String signature, + final String superName, final String[] interfaces) { + super.visit(version, access, name, signature, superName, interfaces); + this.context.registerClass(new ClassInfo(version, access, name, signature, superName, interfaces)); + } + + @Override + public void visitSource(final String source, final String debug) { + super.visitSource(source, debug); + this.context.registerSourceFile(source); + } + + @Override + public MethodVisitor visitMethod(final int access, final String methodName, final String methodDescriptor, + final String signature, final String[] exceptions) { + + final MethodMutationContext methodContext = new MethodMutationContext(this.context, + Location.location(ClassName.fromString(this.context.getClassInfo().getName()), + MethodName.fromString(methodName), methodDescriptor)); + + final MethodVisitor methodVisitor = this.cv.visitMethod(access, methodName, methodDescriptor, signature, + exceptions); + + final MethodInfo info = new MethodInfo().withOwner(this.context.getClassInfo()).withAccess(access) + .withMethodName(methodName).withMethodDescriptor(methodDescriptor); + + if (this.filter.test(info)) { + return this.visitMethodForMutation(methodContext, info, methodVisitor); + } else { + return methodVisitor; + } + + } + + /** + * Added ClassByteArraySource to the MethodMutatorFactory. + * + * @param methodContext + * @param methodInfo + * @param methodVisitor + * @return An object that extends MethodVisitor + */ + private MethodVisitor visitMethodForMutation(MethodMutationContext methodContext, final MethodInfo methodInfo, + final MethodVisitor methodVisitor) { + + MethodVisitor next = methodVisitor; + for (final MethodMutatorFactory each : this.methodMutators) { + next = each.create(methodContext, methodInfo, next, this.byteSource); + } + + return new InstructionTrackingMethodVisitor( + wrapWithDecorators(methodContext, wrapWithFilters(methodContext, next)), methodContext); + } + + private static MethodVisitor wrapWithDecorators(MethodMutationContext methodContext, final MethodVisitor mv) { + return wrapWithBlockTracker(methodContext, wrapWithLineTracker(methodContext, mv)); + } + + private static MethodVisitor wrapWithBlockTracker(MethodMutationContext methodContext, final MethodVisitor mv) { + return new BlockTrackingMethodDecorator(methodContext, mv); + } + + private static MethodVisitor wrapWithLineTracker(MethodMutationContext methodContext, final MethodVisitor mv) { + return new LineTrackingMethodVisitor(methodContext, mv); + } + + private MethodVisitor wrapWithFilters(MethodMutationContext methodContext, + final MethodVisitor wrappedMethodVisitor) { + return wrapWithStringSwitchFilter(methodContext, wrapWithAssertFilter(methodContext, wrappedMethodVisitor)); + } + + private static MethodVisitor wrapWithStringSwitchFilter(MethodMutationContext methodContext, + final MethodVisitor wrappedMethodVisitor) { + return new AvoidStringSwitchedMethodAdapter(methodContext, wrappedMethodVisitor); + } + + private static MethodVisitor wrapWithAssertFilter(MethodMutationContext methodContext, + final MethodVisitor wrappedMethodVisitor) { + return new AvoidAssertsMethodAdapter(methodContext, wrappedMethodVisitor); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutationContext.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutationContext.java index 4f7f2f153..64b021f30 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutationContext.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutationContext.java @@ -1,21 +1,21 @@ -package org.pitest.mutationtest.engine.gregor; - -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.mutationtest.engine.gregor.blocks.BlockCounter; - -public interface MutationContext extends BlockCounter { - - void registerCurrentLine(int line); - - ClassInfo getClassInfo(); - - MutationIdentifier registerMutation(MethodMutatorFactory factory, - String description); - - boolean shouldMutate(MutationIdentifier newId); - - void disableMutations(String reason); - - void enableMutatations(String reason); - +package org.pitest.mutationtest.engine.gregor; + +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.mutationtest.engine.gregor.blocks.BlockCounter; + +public interface MutationContext extends BlockCounter { + + void registerCurrentLine(int line); + + ClassInfo getClassInfo(); + + MutationIdentifier registerMutation(MethodMutatorFactory factory, + String description); + + boolean shouldMutate(MutationIdentifier newId); + + void disableMutations(String reason); + + void enableMutatations(String reason); + } \ No newline at end of file diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutationEngineConfiguration.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutationEngineConfiguration.java index de34e2261..657135b33 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutationEngineConfiguration.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/MutationEngineConfiguration.java @@ -1,26 +1,26 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import java.util.Collection; -import java.util.function.Predicate; - -public interface MutationEngineConfiguration { - - Collection mutators(); - - Predicate methodFilter(); - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import java.util.Collection; +import java.util.function.Predicate; + +public interface MutationEngineConfiguration { + + Collection mutators(); + + Predicate methodFilter(); + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ZeroOperandMutation.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ZeroOperandMutation.java index 36c1ca91d..0dae7a79d 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ZeroOperandMutation.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/ZeroOperandMutation.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import org.objectweb.asm.MethodVisitor; - -public interface ZeroOperandMutation { - - void apply(int opCode, MethodVisitor mv); - - String decribe(int opCode, MethodInfo methodInfo); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import org.objectweb.asm.MethodVisitor; + +public interface ZeroOperandMutation { + + void apply(int opCode, MethodVisitor mv); + + String decribe(int opCode, MethodInfo methodInfo); + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/DefaultInstructionCounter.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/DefaultInstructionCounter.java index 2e6f5da3d..a612ff4a9 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/DefaultInstructionCounter.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/DefaultInstructionCounter.java @@ -1,17 +1,17 @@ -package org.pitest.mutationtest.engine.gregor.analysis; - -public class DefaultInstructionCounter implements InstructionCounter { - - private int count; - - @Override - public void increment() { - this.count++; - } - - @Override - public int currentInstructionCount() { - return this.count; - } - -} +package org.pitest.mutationtest.engine.gregor.analysis; + +public class DefaultInstructionCounter implements InstructionCounter { + + private int count; + + @Override + public void increment() { + this.count++; + } + + @Override + public int currentInstructionCount() { + return this.count; + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionCounter.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionCounter.java index b0393c2a0..2ec9e9121 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionCounter.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionCounter.java @@ -1,9 +1,14 @@ -package org.pitest.mutationtest.engine.gregor.analysis; - -public interface InstructionCounter { - - void increment(); - - int currentInstructionCount(); - -} +package org.pitest.mutationtest.engine.gregor.analysis; + +/** + * Count the instruction for each visit method. + * + * + */ +public interface InstructionCounter { + + void increment(); + + int currentInstructionCount(); + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionTrackingMethodVisitor.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionTrackingMethodVisitor.java index 302837e38..4244e5027 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionTrackingMethodVisitor.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionTrackingMethodVisitor.java @@ -1,120 +1,120 @@ -package org.pitest.mutationtest.engine.gregor.analysis; - -import org.objectweb.asm.Handle; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -public class InstructionTrackingMethodVisitor extends MethodVisitor { - - private final InstructionCounter count; - - public InstructionTrackingMethodVisitor(final MethodVisitor mv, - final InstructionCounter count) { - super(Opcodes.ASM6, mv); - this.count = count; - } - - @Override - public void visitFrame(final int type, final int nLocal, - final Object[] local, final int nStack, final Object[] stack) { - this.count.increment(); - super.visitFrame(type, nLocal, local, nStack, stack); - } - - @Override - public void visitInsn(final int opcode) { - this.count.increment(); - super.visitInsn(opcode); - } - - @Override - public void visitIntInsn(final int opcode, final int operand) { - this.count.increment(); - super.visitIntInsn(opcode, operand); - } - - @Override - public void visitVarInsn(final int opcode, final int var) { - this.count.increment(); - super.visitVarInsn(opcode, var); - } - - @Override - public void visitTypeInsn(final int opcode, final String type) { - this.count.increment(); - super.visitTypeInsn(opcode, type); - } - - @Override - public void visitFieldInsn(final int opcode, final String owner, - final String name, final String desc) { - this.count.increment(); - super.visitFieldInsn(opcode, owner, name, desc); - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, - final String name, final String desc, boolean itf) { - this.count.increment(); - super.visitMethodInsn(opcode, owner, name, desc, itf); - } - - @Override - public void visitInvokeDynamicInsn(final String name, final String desc, - final Handle bsm, final Object... bsmArgs) { - this.count.increment(); - super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); - } - - @Override - public void visitJumpInsn(final int opcode, final Label label) { - this.count.increment(); - super.visitJumpInsn(opcode, label); - } - - @Override - public void visitLabel(final Label label) { - this.count.increment(); - super.visitLabel(label); - } - - @Override - public void visitLdcInsn(final Object cst) { - this.count.increment(); - super.visitLdcInsn(cst); - } - - @Override - public void visitIincInsn(final int var, final int increment) { - this.count.increment(); - super.visitIincInsn(var, increment); - } - - @Override - public void visitTableSwitchInsn(final int min, final int max, - final Label dflt, final Label... labels) { - this.count.increment(); - super.visitTableSwitchInsn(min, max, dflt, labels); - } - - @Override - public void visitLookupSwitchInsn(final Label dflt, final int[] keys, - final Label[] labels) { - this.count.increment(); - super.visitLookupSwitchInsn(dflt, keys, labels); - } - - @Override - public void visitMultiANewArrayInsn(final String desc, final int dims) { - this.count.increment(); - super.visitMultiANewArrayInsn(desc, dims); - } - - @Override - public void visitLineNumber(final int line, final Label start) { - this.count.increment(); - super.visitLineNumber(line, start); - } - -} +package org.pitest.mutationtest.engine.gregor.analysis; + +import org.objectweb.asm.Handle; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Extends MethodVisitor. The main improvement is adding an InstructionCounter. + * For each visit instruction, the counter goes up by 1 (for now) + */ +public class InstructionTrackingMethodVisitor extends MethodVisitor { + + private final InstructionCounter count; + + public InstructionTrackingMethodVisitor(final MethodVisitor mv, final InstructionCounter count) { + super(Opcodes.ASM6, mv); + this.count = count; + } + + @Override + public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, + final Object[] stack) { + this.count.increment(); + super.visitFrame(type, nLocal, local, nStack, stack); + } + + @Override + public void visitInsn(final int opcode) { + this.count.increment(); + super.visitInsn(opcode); + } + + @Override + public void visitIntInsn(final int opcode, final int operand) { + this.count.increment(); + super.visitIntInsn(opcode, operand); + } + + @Override + public void visitVarInsn(final int opcode, final int var) { + this.count.increment(); + super.visitVarInsn(opcode, var); + } + + @Override + public void visitTypeInsn(final int opcode, final String type) { + this.count.increment(); + super.visitTypeInsn(opcode, type); + } + + @Override + public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { + this.count.increment(); + super.visitFieldInsn(opcode, owner, name, desc); + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, + boolean itf) { + this.count.increment(); + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + + @Override + public void visitInvokeDynamicInsn(final String name, final String desc, final Handle bsm, + final Object... bsmArgs) { + this.count.increment(); + super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); + } + + @Override + public void visitJumpInsn(final int opcode, final Label label) { + this.count.increment(); + super.visitJumpInsn(opcode, label); + } + + @Override + public void visitLabel(final Label label) { + this.count.increment(); + super.visitLabel(label); + } + + @Override + public void visitLdcInsn(final Object cst) { + this.count.increment(); + super.visitLdcInsn(cst); + } + + @Override + public void visitIincInsn(final int var, final int increment) { + this.count.increment(); + super.visitIincInsn(var, increment); + } + + @Override + public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels) { + this.count.increment(); + super.visitTableSwitchInsn(min, max, dflt, labels); + } + + @Override + public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { + this.count.increment(); + super.visitLookupSwitchInsn(dflt, keys, labels); + } + + @Override + public void visitMultiANewArrayInsn(final String desc, final int dims) { + this.count.increment(); + super.visitMultiANewArrayInsn(desc, dims); + } + + @Override + public void visitLineNumber(final int line, final Label start) { + this.count.increment(); + super.visitLineNumber(line, start); + } + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/blocks/BlockCounter.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/blocks/BlockCounter.java index dfd753a1d..d75cdd30a 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/blocks/BlockCounter.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/blocks/BlockCounter.java @@ -1,11 +1,11 @@ -package org.pitest.mutationtest.engine.gregor.blocks; - -public interface BlockCounter { - - void registerNewBlock(); - - void registerFinallyBlockStart(); - - void registerFinallyBlockEnd(); - -} +package org.pitest.mutationtest.engine.gregor.blocks; + +public interface BlockCounter { + + void registerNewBlock(); + + void registerFinallyBlockStart(); + + void registerFinallyBlockEnd(); + +} diff --git a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/blocks/BlockTrackingMethodDecorator.java b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/blocks/BlockTrackingMethodDecorator.java index 637f62bf4..c1c08073f 100644 --- a/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/blocks/BlockTrackingMethodDecorator.java +++ b/pitest/src/main/java/org/pitest/mutationtest/engine/gregor/blocks/BlockTrackingMethodDecorator.java @@ -1,90 +1,90 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.blocks; - -import static org.objectweb.asm.Opcodes.ARETURN; -import static org.objectweb.asm.Opcodes.ATHROW; -import static org.objectweb.asm.Opcodes.DRETURN; -import static org.objectweb.asm.Opcodes.FRETURN; -import static org.objectweb.asm.Opcodes.IRETURN; -import static org.objectweb.asm.Opcodes.LRETURN; -import static org.objectweb.asm.Opcodes.RETURN; - -import java.util.HashSet; -import java.util.Set; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -public class BlockTrackingMethodDecorator extends MethodVisitor { - - private final BlockCounter blockCounter; - private final Set
PIT ${project.version} - - + + + + + + + +

Pit Test Coverage Report

+ +

Project Summary

+ + + + + + + + + + + + + + + +
Number of ClassesLine CoverageMutation Coverage
$totals.numberOfFiles$$totals.lineCoverage$%
$totals.numberOfLinesCovered$/$totals.numberOfLines$
$totals.mutationCoverage$%
$totals.numberOfMutationsDetected$/$totals.numberOfMutations$
+ + +

Breakdown by Package

+ + + + + + + + + + +$packageSummaries:{ summary | + + + + + + +}$ + +
NameNumber of ClassesLine CoverageMutation Coverage
$summary.packageName$$summary.totals.numberOfFiles$
$summary.totals.lineCoverage$%
$summary.totals.numberOfLinesCovered$/$summary.totals.numberOfLines$
$summary.totals.mutationCoverage$%
$summary.totals.numberOfMutationsDetected$/$summary.totals.numberOfMutations$
+
+ + +$errors : { error | +
+ $error$ +
+
+}$ + +
+ +Report generated by PIT ${project.version} + + \ No newline at end of file diff --git a/pitest/src/main/resources/templates/mutation/mutation_report.st b/pitest/src/main/resources/templates/mutation/mutation_report.st index 5a7f9c74a..568577faf 100644 --- a/pitest/src/main/resources/templates/mutation/mutation_report.st +++ b/pitest/src/main/resources/templates/mutation/mutation_report.st @@ -1,67 +1,67 @@ - - - - - - - - -

$sourceFile.fileName$

- - - -$sourceFile.lines:{ line | - - - - - -}$ - - - - -$sourceFile.groups:{ group | - - - - - -}$ -
- -$line.number$ - - -$line.numberOfMutationsForDisplay$ - -$line.mutations:{ mutation | -$i$. $mutation.details.location$ : $mutation.details.htmlSafeDescription$ → $mutation.statusDescription$
-}$ -
-
$line.text$

Mutations

$group.id$ - - - -$group.mutations: { mutation |

$i$.$i$
Location : $mutation.details.location$
Killed by : $mutation.killingTestDescription$
$mutation.details.htmlSafeDescription$ → $mutation.statusDescription$

}$ -
- - -

Active mutators

-
    -$mutators : { mutator | -
  • $mutator$
  • -}$ -
- -

Tests examined

-
    -$tests:{ test |
  • $test.name$ ($test.time$ ms)
  • }$ -
- -
- -Report generated by PIT ${project.version} - - - + + + + + + + + +

$sourceFile.fileName$

+ + + +$sourceFile.lines:{ line | + + + + + +}$ + + + + +$sourceFile.groups:{ group | + + + + + +}$ +
+ +$line.number$ + + +$line.numberOfMutationsForDisplay$ + +$line.mutations:{ mutation | +$i$. $mutation.details.location$ : $mutation.details.htmlSafeDescription$ → $mutation.statusDescription$
+}$ +
+
$line.text$

Mutations

$group.id$ + + + +$group.mutations: { mutation |

$i$.$i$
Location : $mutation.details.location$
Killed by : $mutation.killingTestDescription$
$mutation.details.htmlSafeDescription$ → $mutation.statusDescription$

}$ +
+ + +

Active mutators

+
    +$mutators : { mutator | +
  • $mutator$
  • +}$ +
+ +

Tests examined

+
    +$tests:{ test |
  • $test.name$ ($test.time$ ms)
  • }$ +
+ +
+ +Report generated by PIT ${project.version} + + + diff --git a/pitest/src/main/resources/templates/mutation/package_index.st b/pitest/src/main/resources/templates/mutation/package_index.st index c3e78be9a..2af41d983 100644 --- a/pitest/src/main/resources/templates/mutation/package_index.st +++ b/pitest/src/main/resources/templates/mutation/package_index.st @@ -1,63 +1,63 @@ - - - - - - - -

Pit Test Coverage Report

-

Package Summary

-

$packageData.packageName$

- - - - - - - - - - - - - - - -
Number of ClassesLine CoverageMutation Coverage
$packageData.totals.numberOfFiles$$packageData.totals.lineCoverage$%
$packageData.totals.numberOfLinesCovered$/$packageData.totals.numberOfLines$
$packageData.totals.mutationCoverage$%
$packageData.totals.numberOfMutationsDetected$/$packageData.totals.numberOfMutations$
- - -

Breakdown by Class

- - - - - - - - - -$packageData.summaryData:{ summary | - - - - - -}$ - -
NameLine CoverageMutation Coverage
$summary.fileName$
$summary.totals.lineCoverage$%
$summary.totals.numberOfLinesCovered$/$summary.totals.numberOfLines$
$summary.totals.mutationCoverage$%
$summary.totals.numberOfMutationsDetected$/$summary.totals.numberOfMutations$
-
- - -$errors : { error | -
- $error$ -
-
-}$ - -
- -Report generated by PIT ${project.version} - - + + + + + + + +

Pit Test Coverage Report

+

Package Summary

+

$packageData.packageName$

+ + + + + + + + + + + + + + + +
Number of ClassesLine CoverageMutation Coverage
$packageData.totals.numberOfFiles$$packageData.totals.lineCoverage$%
$packageData.totals.numberOfLinesCovered$/$packageData.totals.numberOfLines$
$packageData.totals.mutationCoverage$%
$packageData.totals.numberOfMutationsDetected$/$packageData.totals.numberOfMutations$
+ + +

Breakdown by Class

+ + + + + + + + + +$packageData.summaryData:{ summary | + + + + + +}$ + +
NameLine CoverageMutation Coverage
$summary.fileName$
$summary.totals.lineCoverage$%
$summary.totals.numberOfLinesCovered$/$summary.totals.numberOfLines$
$summary.totals.mutationCoverage$%
$summary.totals.numberOfMutationsDetected$/$summary.totals.numberOfMutations$
+
+ + +$errors : { error | +
+ $error$ +
+
+}$ + +
+ +Report generated by PIT ${project.version} + + \ No newline at end of file diff --git a/pitest/src/main/resources/templates/mutation/style.css b/pitest/src/main/resources/templates/mutation/style.css index cd65bd3ab..c6ec6dbd4 100644 --- a/pitest/src/main/resources/templates/mutation/style.css +++ b/pitest/src/main/resources/templates/mutation/style.css @@ -1,563 +1,563 @@ -html, body, div, span, p, blockquote, pre { - margin: 0; - padding: 0; - border: 0; - outline: 0; - font-weight: inherit; - font-style: inherit; - font-size: 100%; - font-family: inherit; - vertical-align: baseline; -} - -body{ - line-height: 1; - color: black; - background: white; - margin-left: 20px; -} - -.src { - border: 1px solid #dddddd; - padding-top: 10px; - padding-right: 5px; - padding-left: 5px; - font-family: Consolas, Courier, monospace; -} - -.covered { - background-color: #ddffdd; -} - -.uncovered { - background-color: #ffdddd; -} - -.killed, .KILLED { - background-color: #aaffaa; -} - -.survived, .SURVIVED { - background-color: #ffaaaa; -} - -.uncertain { - background-color: #dde7ef; -} - -.run_error { - background-color: #dde7ef; -} - -.na { - background-color: #eeeeee; -} - -.timed_out { - background-color: #dde7ef; -} - -.non_viable { - background-color: #aaffaa; -} - -.memory_error { - background-color: #dde7ef; -} - -.not_started { - background-color: #dde7ef; color : red -} - -.no_coverage { - background-color: #ffaaaa; -} - -.tests { - width: 50%; - float: left; -} - -.mutees { - float: right; - width: 50%; -} - -.unit { - padding-top: 20px; - clear: both; -} - -.coverage_bar { - display: inline-block; - height: 1.1em; - width: 130px; - background: #FAA; - margin: 0 5px; - vertical-align: middle; - border: 1px solid #AAA; - position: relative; -} - -.coverage_complete { - display: inline-block; - height: 100%; - background: #DFD; - float: left; -} - -.coverage_legend { - position: absolute; - height: 100%; - width: 100%; - left: 0; - top: 0; - text-align: center; -} - -.line, .mut { - vertical-align: middle; -} - -.coverage_percentage { - display: inline-block; - width: 3em; - text-align: right; -} - -.pop { - outline:none; -} - -.pop strong { - line-height: 30px; -} - -.pop { - text-decoration: none; -} - -.pop span { - z-index: 10; - display: none; - padding: 14px 20px; - margin-top: -30px; - margin-left: 28px; - width: 800px; - line-height: 16px; - word-wrap: break-word; - border-radius: 4px; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - -moz-box-shadow: 5px 5px 8px #CCC; - -webkit-box-shadow: 5px 5px 8px #CCC; - box-shadow: 5px 5px 8px #CCC; -} - -.pop:hover span { - display: inline; - position: absolute; - color: #111; - border: 1px solid #DCA; - background: #fffAF0; -} - -.width-1 { - width: 1%; -} - -.width-2 { - width: 2%; -} - -.width-3 { - width: 3%; -} - -.width-4 { - width: 4%; -} - -.width-5 { - width: 5%; -} - -.width-6 { - width: 6%; -} - -.width-7 { - width: 7%; -} - -.width-8 { - width: 8%; -} - -.width-9 { - width: 9%; -} - -.width-10 { - width: 10%; -} - -.width-11 { - width: 11%; -} - -.width-12 { - width: 12%; -} - -.width-13 { - width: 13%; -} - -.width-14 { - width: 14%; -} - -.width-15 { - width: 15%; -} - -.width-16 { - width: 16%; -} - -.width-17 { - width: 17%; -} - -.width-18 { - width: 18%; -} - -.width-19 { - width: 19%; -} - -.width-20 { - width: 20%; -} - -.width-21 { - width: 21%; -} - -.width-22 { - width: 22%; -} - -.width-23 { - width: 23%; -} - -.width-24 { - width: 24%; -} - -.width-25 { - width: 25%; -} - -.width-26 { - width: 26%; -} - -.width-27 { - width: 27%; -} - -.width-28 { - width: 28%; -} - -.width-29 { - width: 29%; -} - -.width-30 { - width: 30%; -} - -.width-31 { - width: 31%; -} - -.width-32 { - width: 32%; -} - -.width-33 { - width: 33%; -} - -.width-34 { - width: 34%; -} - -.width-35 { - width: 35%; -} - -.width-36 { - width: 36%; -} - -.width-37 { - width: 37%; -} - -.width-38 { - width: 38%; -} - -.width-39 { - width: 39%; -} - -.width-40 { - width: 40%; -} - -.width-41 { - width: 41%; -} - -.width-42 { - width: 42%; -} - -.width-43 { - width: 43%; -} - -.width-44 { - width: 44%; -} - -.width-45 { - width: 45%; -} - -.width-46 { - width: 46%; -} - -.width-47 { - width: 47%; -} - -.width-48 { - width: 48%; -} - -.width-49 { - width: 49%; -} - -.width-50 { - width: 50%; -} - -.width-51 { - width: 51%; -} - -.width-52 { - width: 52%; -} - -.width-53 { - width: 53%; -} - -.width-54 { - width: 54%; -} - -.width-55 { - width: 55%; -} - -.width-56 { - width: 56%; -} - -.width-57 { - width: 57%; -} - -.width-58 { - width: 58%; -} - -.width-59 { - width: 59%; -} - -.width-60 { - width: 60%; -} - -.width-61 { - width: 61%; -} - -.width-62 { - width: 62%; -} - -.width-63 { - width: 63%; -} - -.width-64 { - width: 64%; -} - -.width-65 { - width: 65%; -} - -.width-66 { - width: 66%; -} - -.width-67 { - width: 67%; -} - -.width-68 { - width: 68%; -} - -.width-69 { - width: 69%; -} - -.width-70 { - width: 70%; -} - -.width-71 { - width: 71%; -} - -.width-72 { - width: 72%; -} - -.width-73 { - width: 73%; -} - -.width-74 { - width: 74%; -} - -.width-75 { - width: 75%; -} - -.width-76 { - width: 76%; -} - -.width-77 { - width: 77%; -} - -.width-78 { - width: 78%; -} - -.width-79 { - width: 79%; -} - -.width-80 { - width: 80%; -} - -.width-81 { - width: 81%; -} - -.width-82 { - width: 82%; -} - -.width-83 { - width: 83%; -} - -.width-84 { - width: 84%; -} - -.width-85 { - width: 85%; -} - -.width-86 { - width: 86%; -} - -.width-87 { - width: 87%; -} - -.width-88 { - width: 88%; -} - -.width-89 { - width: 89%; -} - -.width-90 { - width: 90%; -} - -.width-91 { - width: 91%; -} - -.width-92 { - width: 92%; -} - -.width-93 { - width: 93%; -} - -.width-94 { - width: 94%; -} - -.width-95 { - width: 95%; -} - -.width-96 { - width: 96%; -} - -.width-97 { - width: 97%; -} - -.width-98 { - width: 98%; -} - -.width-99 { - width: 99%; -} - -.width-100 { - width: 100%; +html, body, div, span, p, blockquote, pre { + margin: 0; + padding: 0; + border: 0; + outline: 0; + font-weight: inherit; + font-style: inherit; + font-size: 100%; + font-family: inherit; + vertical-align: baseline; +} + +body{ + line-height: 1; + color: black; + background: white; + margin-left: 20px; +} + +.src { + border: 1px solid #dddddd; + padding-top: 10px; + padding-right: 5px; + padding-left: 5px; + font-family: Consolas, Courier, monospace; +} + +.covered { + background-color: #ddffdd; +} + +.uncovered { + background-color: #ffdddd; +} + +.killed, .KILLED { + background-color: #aaffaa; +} + +.survived, .SURVIVED { + background-color: #ffaaaa; +} + +.uncertain { + background-color: #dde7ef; +} + +.run_error { + background-color: #dde7ef; +} + +.na { + background-color: #eeeeee; +} + +.timed_out { + background-color: #dde7ef; +} + +.non_viable { + background-color: #aaffaa; +} + +.memory_error { + background-color: #dde7ef; +} + +.not_started { + background-color: #dde7ef; color : red +} + +.no_coverage { + background-color: #ffaaaa; +} + +.tests { + width: 50%; + float: left; +} + +.mutees { + float: right; + width: 50%; +} + +.unit { + padding-top: 20px; + clear: both; +} + +.coverage_bar { + display: inline-block; + height: 1.1em; + width: 130px; + background: #FAA; + margin: 0 5px; + vertical-align: middle; + border: 1px solid #AAA; + position: relative; +} + +.coverage_complete { + display: inline-block; + height: 100%; + background: #DFD; + float: left; +} + +.coverage_legend { + position: absolute; + height: 100%; + width: 100%; + left: 0; + top: 0; + text-align: center; +} + +.line, .mut { + vertical-align: middle; +} + +.coverage_percentage { + display: inline-block; + width: 3em; + text-align: right; +} + +.pop { + outline:none; +} + +.pop strong { + line-height: 30px; +} + +.pop { + text-decoration: none; +} + +.pop span { + z-index: 10; + display: none; + padding: 14px 20px; + margin-top: -30px; + margin-left: 28px; + width: 800px; + line-height: 16px; + word-wrap: break-word; + border-radius: 4px; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + -moz-box-shadow: 5px 5px 8px #CCC; + -webkit-box-shadow: 5px 5px 8px #CCC; + box-shadow: 5px 5px 8px #CCC; +} + +.pop:hover span { + display: inline; + position: absolute; + color: #111; + border: 1px solid #DCA; + background: #fffAF0; +} + +.width-1 { + width: 1%; +} + +.width-2 { + width: 2%; +} + +.width-3 { + width: 3%; +} + +.width-4 { + width: 4%; +} + +.width-5 { + width: 5%; +} + +.width-6 { + width: 6%; +} + +.width-7 { + width: 7%; +} + +.width-8 { + width: 8%; +} + +.width-9 { + width: 9%; +} + +.width-10 { + width: 10%; +} + +.width-11 { + width: 11%; +} + +.width-12 { + width: 12%; +} + +.width-13 { + width: 13%; +} + +.width-14 { + width: 14%; +} + +.width-15 { + width: 15%; +} + +.width-16 { + width: 16%; +} + +.width-17 { + width: 17%; +} + +.width-18 { + width: 18%; +} + +.width-19 { + width: 19%; +} + +.width-20 { + width: 20%; +} + +.width-21 { + width: 21%; +} + +.width-22 { + width: 22%; +} + +.width-23 { + width: 23%; +} + +.width-24 { + width: 24%; +} + +.width-25 { + width: 25%; +} + +.width-26 { + width: 26%; +} + +.width-27 { + width: 27%; +} + +.width-28 { + width: 28%; +} + +.width-29 { + width: 29%; +} + +.width-30 { + width: 30%; +} + +.width-31 { + width: 31%; +} + +.width-32 { + width: 32%; +} + +.width-33 { + width: 33%; +} + +.width-34 { + width: 34%; +} + +.width-35 { + width: 35%; +} + +.width-36 { + width: 36%; +} + +.width-37 { + width: 37%; +} + +.width-38 { + width: 38%; +} + +.width-39 { + width: 39%; +} + +.width-40 { + width: 40%; +} + +.width-41 { + width: 41%; +} + +.width-42 { + width: 42%; +} + +.width-43 { + width: 43%; +} + +.width-44 { + width: 44%; +} + +.width-45 { + width: 45%; +} + +.width-46 { + width: 46%; +} + +.width-47 { + width: 47%; +} + +.width-48 { + width: 48%; +} + +.width-49 { + width: 49%; +} + +.width-50 { + width: 50%; +} + +.width-51 { + width: 51%; +} + +.width-52 { + width: 52%; +} + +.width-53 { + width: 53%; +} + +.width-54 { + width: 54%; +} + +.width-55 { + width: 55%; +} + +.width-56 { + width: 56%; +} + +.width-57 { + width: 57%; +} + +.width-58 { + width: 58%; +} + +.width-59 { + width: 59%; +} + +.width-60 { + width: 60%; +} + +.width-61 { + width: 61%; +} + +.width-62 { + width: 62%; +} + +.width-63 { + width: 63%; +} + +.width-64 { + width: 64%; +} + +.width-65 { + width: 65%; +} + +.width-66 { + width: 66%; +} + +.width-67 { + width: 67%; +} + +.width-68 { + width: 68%; +} + +.width-69 { + width: 69%; +} + +.width-70 { + width: 70%; +} + +.width-71 { + width: 71%; +} + +.width-72 { + width: 72%; +} + +.width-73 { + width: 73%; +} + +.width-74 { + width: 74%; +} + +.width-75 { + width: 75%; +} + +.width-76 { + width: 76%; +} + +.width-77 { + width: 77%; +} + +.width-78 { + width: 78%; +} + +.width-79 { + width: 79%; +} + +.width-80 { + width: 80%; +} + +.width-81 { + width: 81%; +} + +.width-82 { + width: 82%; +} + +.width-83 { + width: 83%; +} + +.width-84 { + width: 84%; +} + +.width-85 { + width: 85%; +} + +.width-86 { + width: 86%; +} + +.width-87 { + width: 87%; +} + +.width-88 { + width: 88%; +} + +.width-89 { + width: 89%; +} + +.width-90 { + width: 90%; +} + +.width-91 { + width: 91%; +} + +.width-92 { + width: 92%; +} + +.width-93 { + width: 93%; +} + +.width-94 { + width: 94%; +} + +.width-95 { + width: 95%; +} + +.width-96 { + width: 96%; +} + +.width-97 { + width: 97%; +} + +.width-98 { + width: 98%; +} + +.width-99 { + width: 99%; +} + +.width-100 { + width: 100%; } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/BeforeAfterClassTest.java b/pitest/src/test/java/com/example/BeforeAfterClassTest.java index b1f733bde..f66f9f0bd 100644 --- a/pitest/src/test/java/com/example/BeforeAfterClassTest.java +++ b/pitest/src/test/java/com/example/BeforeAfterClassTest.java @@ -1,24 +1,24 @@ -package com.example; - -import static org.junit.Assert.assertEquals; - -import org.junit.BeforeClass; -import org.junit.Test; - -public class BeforeAfterClassTest { - - @BeforeClass - public static void doSomething() { - // well actually do nothing except be here - } - - @Test - public void shouldKillMutant1() { - assertEquals(1, CoveredByABeforeAfterClass.returnOne()); - } - - @Test - public void shouldKillMutantAgainButShouldNotBeRun() { - assertEquals(1, CoveredByABeforeAfterClass.returnOne()); - } -} +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class BeforeAfterClassTest { + + @BeforeClass + public static void doSomething() { + // well actually do nothing except be here + } + + @Test + public void shouldKillMutant1() { + assertEquals(1, CoveredByABeforeAfterClass.returnOne()); + } + + @Test + public void shouldKillMutantAgainButShouldNotBeRun() { + assertEquals(1, CoveredByABeforeAfterClass.returnOne()); + } +} diff --git a/pitest/src/test/java/com/example/CoveredByABeforeAfterClass.java b/pitest/src/test/java/com/example/CoveredByABeforeAfterClass.java index 56710ea0e..a99a0f1ad 100644 --- a/pitest/src/test/java/com/example/CoveredByABeforeAfterClass.java +++ b/pitest/src/test/java/com/example/CoveredByABeforeAfterClass.java @@ -1,7 +1,7 @@ -package com.example; - -public class CoveredByABeforeAfterClass { - public static int returnOne() { - return 1; - } -} +package com.example; + +public class CoveredByABeforeAfterClass { + public static int returnOne() { + return 1; + } +} diff --git a/pitest/src/test/java/com/example/CoveredByJUnitThreeSuite.java b/pitest/src/test/java/com/example/CoveredByJUnitThreeSuite.java index 7b14e8bea..bfe146bcf 100644 --- a/pitest/src/test/java/com/example/CoveredByJUnitThreeSuite.java +++ b/pitest/src/test/java/com/example/CoveredByJUnitThreeSuite.java @@ -1,8 +1,8 @@ -package com.example; - -public class CoveredByJUnitThreeSuite { - - public int foo() { - return 1; - } -} +package com.example; + +public class CoveredByJUnitThreeSuite { + + public int foo() { + return 1; + } +} diff --git a/pitest/src/test/java/com/example/HasExcludedMethodsTestee.java b/pitest/src/test/java/com/example/HasExcludedMethodsTestee.java index 7790950b4..ffe7abd58 100644 --- a/pitest/src/test/java/com/example/HasExcludedMethodsTestee.java +++ b/pitest/src/test/java/com/example/HasExcludedMethodsTestee.java @@ -1,23 +1,23 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -public class HasExcludedMethodsTestee { - - public static int excludeMe(final int i) { - return i + 1; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +public class HasExcludedMethodsTestee { + + public static int excludeMe(final int i) { + return i + 1; + } + +} diff --git a/pitest/src/test/java/com/example/HasExcludedMethodsTesteeTest.java b/pitest/src/test/java/com/example/HasExcludedMethodsTesteeTest.java index 11bf537d3..02a9e4b1e 100644 --- a/pitest/src/test/java/com/example/HasExcludedMethodsTesteeTest.java +++ b/pitest/src/test/java/com/example/HasExcludedMethodsTesteeTest.java @@ -1,28 +1,28 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class HasExcludedMethodsTesteeTest { - - @Test - public void testExcludedMethod() { - assertEquals(11, HasExcludedMethodsTestee.excludeMe(10)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HasExcludedMethodsTesteeTest { + + @Test + public void testExcludedMethod() { + assertEquals(11, HasExcludedMethodsTestee.excludeMe(10)); + } + +} diff --git a/pitest/src/test/java/com/example/JUnitParamsTest.java b/pitest/src/test/java/com/example/JUnitParamsTest.java index 4591d9814..035082fd8 100644 --- a/pitest/src/test/java/com/example/JUnitParamsTest.java +++ b/pitest/src/test/java/com/example/JUnitParamsTest.java @@ -1,23 +1,23 @@ -package com.example; - -import static junitparams.JUnitParamsRunner.$; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import junitparams.JUnitParamsRunner; - -@RunWith(JUnitParamsRunner.class) -public class JUnitParamsTest { - - @Test - @junitparams.Parameters(method = "getTestInputValues") - public void shouldGenerateCoverageForJUnitParams(final int input, - final int expectedResult) { - - } - - public Object[] getTestInputValues() { - return $($(1, 1), $(2, 2), $(3, 3)); - } +package com.example; + +import static junitparams.JUnitParamsRunner.$; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import junitparams.JUnitParamsRunner; + +@RunWith(JUnitParamsRunner.class) +public class JUnitParamsTest { + + @Test + @junitparams.Parameters(method = "getTestInputValues") + public void shouldGenerateCoverageForJUnitParams(final int input, + final int expectedResult) { + + } + + public Object[] getTestInputValues() { + return $($(1, 1), $(2, 2), $(3, 3)); + } } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/JUnitThreeSubSuite.java b/pitest/src/test/java/com/example/JUnitThreeSubSuite.java index 0adf75366..5a70251c3 100644 --- a/pitest/src/test/java/com/example/JUnitThreeSubSuite.java +++ b/pitest/src/test/java/com/example/JUnitThreeSubSuite.java @@ -1,13 +1,13 @@ -package com.example; - -import junit.framework.TestSuite; - -public class JUnitThreeSubSuite { - - public static junit.framework.Test suite() { - final TestSuite suite = new TestSuite(); - suite.addTest(new JUnitThreeTest("testSomething")); - return suite; - } - -} +package com.example; + +import junit.framework.TestSuite; + +public class JUnitThreeSubSuite { + + public static junit.framework.Test suite() { + final TestSuite suite = new TestSuite(); + suite.addTest(new JUnitThreeTest("testSomething")); + return suite; + } + +} diff --git a/pitest/src/test/java/com/example/JUnitThreeSuite.java b/pitest/src/test/java/com/example/JUnitThreeSuite.java index fb1bba816..6b3c660d8 100644 --- a/pitest/src/test/java/com/example/JUnitThreeSuite.java +++ b/pitest/src/test/java/com/example/JUnitThreeSuite.java @@ -1,17 +1,17 @@ -package com.example; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class JUnitThreeSuite extends TestCase { - public JUnitThreeSuite(final String testName) { - super(testName); - } - - public static junit.framework.Test suite() { - final TestSuite suite = new TestSuite(); - suite.addTest(JUnitThreeSubSuite.suite()); - return suite; - } - +package com.example; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class JUnitThreeSuite extends TestCase { + public JUnitThreeSuite(final String testName) { + super(testName); + } + + public static junit.framework.Test suite() { + final TestSuite suite = new TestSuite(); + suite.addTest(JUnitThreeSubSuite.suite()); + return suite; + } + } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/JUnitThreeTest.java b/pitest/src/test/java/com/example/JUnitThreeTest.java index ef8d62553..0e2f40234 100644 --- a/pitest/src/test/java/com/example/JUnitThreeTest.java +++ b/pitest/src/test/java/com/example/JUnitThreeTest.java @@ -1,15 +1,15 @@ -package com.example; - -import junit.framework.TestCase; - -public class JUnitThreeTest extends TestCase { - - public JUnitThreeTest(final String name) { - super(name); - } - - public void testSomething() { - assertEquals(1, new CoveredByJUnitThreeSuite().foo()); - } - +package com.example; + +import junit.framework.TestCase; + +public class JUnitThreeTest extends TestCase { + + public JUnitThreeTest(final String name) { + super(name); + } + + public void testSomething() { + assertEquals(1, new CoveredByJUnitThreeSuite().foo()); + } + } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/LineNumbersSpanBlocks.java b/pitest/src/test/java/com/example/LineNumbersSpanBlocks.java index 63a24542a..14d36f6bc 100644 --- a/pitest/src/test/java/com/example/LineNumbersSpanBlocks.java +++ b/pitest/src/test/java/com/example/LineNumbersSpanBlocks.java @@ -1,21 +1,21 @@ -package com.example; - -//@formatter:off -public class LineNumbersSpanBlocks { - public static int foo(int digits) { - final int result; - - if (digits == 1) { - final int day = 6; - - result = day * 7; - } else if (digits == 2) { - result = 13; - } else { - result = 0; - } - - return result; - } -} +package com.example; + +//@formatter:off +public class LineNumbersSpanBlocks { + public static int foo(int digits) { + final int result; + + if (digits == 1) { + final int day = 6; + + result = day * 7; + } else if (digits == 2) { + result = 13; + } else { + result = 0; + } + + return result; + } +} // @formatter:on \ No newline at end of file diff --git a/pitest/src/test/java/com/example/LoadsResourcesFromClassPath.java b/pitest/src/test/java/com/example/LoadsResourcesFromClassPath.java index 210140c5e..3feceefb3 100644 --- a/pitest/src/test/java/com/example/LoadsResourcesFromClassPath.java +++ b/pitest/src/test/java/com/example/LoadsResourcesFromClassPath.java @@ -1,18 +1,18 @@ -package com.example; - -import java.io.InputStream; - -import org.pitest.util.IsolationUtils; - -public class LoadsResourcesFromClassPath { - - public static boolean loadResource() { - final InputStream stream = IsolationUtils.getContextClassLoader() - .getResourceAsStream( - "resource folder with spaces/text in folder with spaces.txt"); - final boolean result = stream != null; // store result to nudge compiler - // towards single IRETURN - return result; - } - -} +package com.example; + +import java.io.InputStream; + +import org.pitest.util.IsolationUtils; + +public class LoadsResourcesFromClassPath { + + public static boolean loadResource() { + final InputStream stream = IsolationUtils.getContextClassLoader() + .getResourceAsStream( + "resource folder with spaces/text in folder with spaces.txt"); + final boolean result = stream != null; // store result to nudge compiler + // towards single IRETURN + return result; + } + +} diff --git a/pitest/src/test/java/com/example/LoadsResourcesFromClassPathTest.java b/pitest/src/test/java/com/example/LoadsResourcesFromClassPathTest.java index eb0c8aaf0..c71b095f2 100644 --- a/pitest/src/test/java/com/example/LoadsResourcesFromClassPathTest.java +++ b/pitest/src/test/java/com/example/LoadsResourcesFromClassPathTest.java @@ -1,14 +1,14 @@ -package com.example; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class LoadsResourcesFromClassPathTest { - - @Test - public void testReadsResource() { - assertTrue(LoadsResourcesFromClassPath.loadResource()); - } - -} +package com.example; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class LoadsResourcesFromClassPathTest { + + @Test + public void testReadsResource() { + assertTrue(LoadsResourcesFromClassPath.loadResource()); + } + +} diff --git a/pitest/src/test/java/com/example/TheoryTest.java b/pitest/src/test/java/com/example/TheoryTest.java index 5efdecfd8..bb8e8e44f 100644 --- a/pitest/src/test/java/com/example/TheoryTest.java +++ b/pitest/src/test/java/com/example/TheoryTest.java @@ -1,43 +1,43 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example; - -import org.junit.experimental.theories.DataPoint; -import org.junit.experimental.theories.Theories; -import org.junit.experimental.theories.Theory; -import org.junit.runner.RunWith; - -import junit.framework.TestCase; - -@RunWith(Theories.class) -public class TheoryTest extends TestCase { - @DataPoint - public static Integer i = 1; - - @Theory - public void testTheory1(final Integer i) { - assertEquals(1, i.intValue()); - } - - @Theory - public void testTheory2(final Integer i) { - - } - - @Theory - public void testTheory3(final Integer i) { - - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example; + +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.RunWith; + +import junit.framework.TestCase; + +@RunWith(Theories.class) +public class TheoryTest extends TestCase { + @DataPoint + public static Integer i = 1; + + @Theory + public void testTheory1(final Integer i) { + assertEquals(1, i.intValue()); + } + + @Theory + public void testTheory2(final Integer i) { + + } + + @Theory + public void testTheory3(final Integer i) { + + } +} diff --git a/pitest/src/test/java/com/example/coverage/execute/samples/simple/LastLineOfContructorCheck.java b/pitest/src/test/java/com/example/coverage/execute/samples/simple/LastLineOfContructorCheck.java index 4da656d3d..93395d322 100644 --- a/pitest/src/test/java/com/example/coverage/execute/samples/simple/LastLineOfContructorCheck.java +++ b/pitest/src/test/java/com/example/coverage/execute/samples/simple/LastLineOfContructorCheck.java @@ -1,8 +1,8 @@ -package com.example.coverage.execute.samples.simple; - -public class LastLineOfContructorCheck { - public LastLineOfContructorCheck() { - super(); - } - -} +package com.example.coverage.execute.samples.simple; + +public class LastLineOfContructorCheck { + public LastLineOfContructorCheck() { + super(); + } + +} diff --git a/pitest/src/test/java/com/example/coverage/execute/samples/simple/OneBlock.java b/pitest/src/test/java/com/example/coverage/execute/samples/simple/OneBlock.java index 1e9225e82..c1f65fe8d 100644 --- a/pitest/src/test/java/com/example/coverage/execute/samples/simple/OneBlock.java +++ b/pitest/src/test/java/com/example/coverage/execute/samples/simple/OneBlock.java @@ -1,7 +1,7 @@ -package com.example.coverage.execute.samples.simple; - -public class OneBlock { - int foo() { - return 1; - } -} +package com.example.coverage.execute.samples.simple; + +public class OneBlock { + int foo() { + return 1; + } +} diff --git a/pitest/src/test/java/com/example/coverage/execute/samples/simple/ThreeBlocks.java b/pitest/src/test/java/com/example/coverage/execute/samples/simple/ThreeBlocks.java index 30687f3de..97301a3c7 100644 --- a/pitest/src/test/java/com/example/coverage/execute/samples/simple/ThreeBlocks.java +++ b/pitest/src/test/java/com/example/coverage/execute/samples/simple/ThreeBlocks.java @@ -1,10 +1,10 @@ -package com.example.coverage.execute.samples.simple; - -public class ThreeBlocks { - int foo(int i) { - if (i > 30) { - return 1; - } - return 2; - } -} +package com.example.coverage.execute.samples.simple; + +public class ThreeBlocks { + int foo(int i) { + if (i > 30) { + return 1; + } + return 2; + } +} diff --git a/pitest/src/test/java/com/example/coverage/execute/samples/simple/ThreeMultiLineBlocks.java b/pitest/src/test/java/com/example/coverage/execute/samples/simple/ThreeMultiLineBlocks.java index 652ecdee1..8b65feee4 100644 --- a/pitest/src/test/java/com/example/coverage/execute/samples/simple/ThreeMultiLineBlocks.java +++ b/pitest/src/test/java/com/example/coverage/execute/samples/simple/ThreeMultiLineBlocks.java @@ -1,13 +1,13 @@ -package com.example.coverage.execute.samples.simple; - -public class ThreeMultiLineBlocks { - int foo(int i) { - System.out.println("foo"); - if (i > 30) { - System.out.println("foo"); - return 1; - } - System.out.println("foo"); - return 2; - } -} +package com.example.coverage.execute.samples.simple; + +public class ThreeMultiLineBlocks { + int foo(int i) { + System.out.println("foo"); + if (i > 30) { + System.out.println("foo"); + return 1; + } + System.out.println("foo"); + return 2; + } +} diff --git a/pitest/src/test/java/com/example/testng/AbstractClass.java b/pitest/src/test/java/com/example/testng/AbstractClass.java index 634d5c291..68f0911cf 100644 --- a/pitest/src/test/java/com/example/testng/AbstractClass.java +++ b/pitest/src/test/java/com/example/testng/AbstractClass.java @@ -1,26 +1,26 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -import org.testng.annotations.Test; - -@Test -public abstract class AbstractClass { - - public void aTest() { - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +import org.testng.annotations.Test; + +@Test +public abstract class AbstractClass { + + public void aTest() { + + } + +} diff --git a/pitest/src/test/java/com/example/testng/AbstractTestNGClass.java b/pitest/src/test/java/com/example/testng/AbstractTestNGClass.java index 5a31a4309..968c586f3 100644 --- a/pitest/src/test/java/com/example/testng/AbstractTestNGClass.java +++ b/pitest/src/test/java/com/example/testng/AbstractTestNGClass.java @@ -1,13 +1,13 @@ -package com.example.testng; - -public abstract class AbstractTestNGClass { - @org.testng.annotations.Test - public void aTest() { - - } - - @org.testng.annotations.Test - public void anotherTest() { - - } +package com.example.testng; + +public abstract class AbstractTestNGClass { + @org.testng.annotations.Test + public void aTest() { + + } + + @org.testng.annotations.Test + public void anotherTest() { + + } } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/testng/AnnotatedAtClassLevel.java b/pitest/src/test/java/com/example/testng/AnnotatedAtClassLevel.java index e83182508..25a83aacc 100644 --- a/pitest/src/test/java/com/example/testng/AnnotatedAtClassLevel.java +++ b/pitest/src/test/java/com/example/testng/AnnotatedAtClassLevel.java @@ -1,26 +1,26 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -@org.testng.annotations.Test -public class AnnotatedAtClassLevel { - public void aTest() { - - } - - public void anotherTest() { - - } +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +@org.testng.annotations.Test +public class AnnotatedAtClassLevel { + public void aTest() { + + } + + public void anotherTest() { + + } } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/testng/AnnotatedAtMethodLevel.java b/pitest/src/test/java/com/example/testng/AnnotatedAtMethodLevel.java index 4d2453fec..b6c21fbfe 100644 --- a/pitest/src/test/java/com/example/testng/AnnotatedAtMethodLevel.java +++ b/pitest/src/test/java/com/example/testng/AnnotatedAtMethodLevel.java @@ -1,27 +1,27 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -public class AnnotatedAtMethodLevel { - @org.testng.annotations.Test - public void aTest() { - - } - - @org.testng.annotations.Test - public void anotherTest() { - - } +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +public class AnnotatedAtMethodLevel { + @org.testng.annotations.Test + public void aTest() { + + } + + @org.testng.annotations.Test + public void anotherTest() { + + } } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/testng/AnnotatedBase.java b/pitest/src/test/java/com/example/testng/AnnotatedBase.java index c696e9305..8fec30507 100644 --- a/pitest/src/test/java/com/example/testng/AnnotatedBase.java +++ b/pitest/src/test/java/com/example/testng/AnnotatedBase.java @@ -1,30 +1,30 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -import org.testng.annotations.Test; - -@Test -public class AnnotatedBase { - - public void aBaseTest() { - - } - - protected void notATest() { - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +import org.testng.annotations.Test; + +@Test +public class AnnotatedBase { + + public void aBaseTest() { + + } + + protected void notATest() { + + } + +} diff --git a/pitest/src/test/java/com/example/testng/Fails.java b/pitest/src/test/java/com/example/testng/Fails.java index 4e7ca3277..c820574cb 100644 --- a/pitest/src/test/java/com/example/testng/Fails.java +++ b/pitest/src/test/java/com/example/testng/Fails.java @@ -1,29 +1,29 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -import static org.junit.Assert.assertTrue; - -public class Fails { - @org.testng.annotations.Test - public void fails() { - assertTrue(false); - } - - @org.testng.annotations.Test - public void passes() { - assertTrue(true); - } +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +import static org.junit.Assert.assertTrue; + +public class Fails { + @org.testng.annotations.Test + public void fails() { + assertTrue(false); + } + + @org.testng.annotations.Test + public void passes() { + assertTrue(true); + } } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/testng/FullyCoveredByTestNGTestee.java b/pitest/src/test/java/com/example/testng/FullyCoveredByTestNGTestee.java index 852e85946..63350a8dc 100644 --- a/pitest/src/test/java/com/example/testng/FullyCoveredByTestNGTestee.java +++ b/pitest/src/test/java/com/example/testng/FullyCoveredByTestNGTestee.java @@ -1,38 +1,38 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -public class FullyCoveredByTestNGTestee { - - public int coverMe() { - return 1; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +public class FullyCoveredByTestNGTestee { + + public int coverMe() { + return 1; + } + +} diff --git a/pitest/src/test/java/com/example/testng/FullyCoveredByTestNGTesteeTest.java b/pitest/src/test/java/com/example/testng/FullyCoveredByTestNGTesteeTest.java index d43661d34..acbcb32b3 100644 --- a/pitest/src/test/java/com/example/testng/FullyCoveredByTestNGTesteeTest.java +++ b/pitest/src/test/java/com/example/testng/FullyCoveredByTestNGTesteeTest.java @@ -1,28 +1,28 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -import static org.testng.AssertJUnit.assertEquals; - -import org.testng.annotations.Test; - -public class FullyCoveredByTestNGTesteeTest { - - @Test - public void testCoverMe() { - final FullyCoveredByTestNGTestee testee = new FullyCoveredByTestNGTestee(); - assertEquals(1, testee.coverMe()); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +import static org.testng.AssertJUnit.assertEquals; + +import org.testng.annotations.Test; + +public class FullyCoveredByTestNGTesteeTest { + + @Test + public void testCoverMe() { + final FullyCoveredByTestNGTestee testee = new FullyCoveredByTestNGTestee(); + assertEquals(1, testee.coverMe()); + } +} diff --git a/pitest/src/test/java/com/example/testng/HasGroups.java b/pitest/src/test/java/com/example/testng/HasGroups.java index 609e2f96a..5eb408c1d 100644 --- a/pitest/src/test/java/com/example/testng/HasGroups.java +++ b/pitest/src/test/java/com/example/testng/HasGroups.java @@ -1,36 +1,36 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -import org.testng.annotations.Test; - -public class HasGroups { - - @Test(groups = { "include", "exclude" }) - public void includeAndExcludeGroup() { - } - - @Test(groups = { "exclude" }) - public void excludeGroup() { - } - - @Test(groups = { "include" }) - public void includeGroup() { - } - - @Test - public void noGroup() { - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +import org.testng.annotations.Test; + +public class HasGroups { + + @Test(groups = { "include", "exclude" }) + public void includeAndExcludeGroup() { + } + + @Test(groups = { "exclude" }) + public void excludeGroup() { + } + + @Test(groups = { "include" }) + public void includeGroup() { + } + + @Test + public void noGroup() { + } +} diff --git a/pitest/src/test/java/com/example/testng/HasOnePassingAndOneFailingMethod.java b/pitest/src/test/java/com/example/testng/HasOnePassingAndOneFailingMethod.java index f7238e0a0..012f1d009 100644 --- a/pitest/src/test/java/com/example/testng/HasOnePassingAndOneFailingMethod.java +++ b/pitest/src/test/java/com/example/testng/HasOnePassingAndOneFailingMethod.java @@ -1,27 +1,27 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -public class HasOnePassingAndOneFailingMethod { - @org.testng.annotations.Test - public void passes() { - - } - - @org.testng.annotations.Test - public void fails() { - throw new RuntimeException("oops"); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +public class HasOnePassingAndOneFailingMethod { + @org.testng.annotations.Test + public void passes() { + + } + + @org.testng.annotations.Test + public void fails() { + throw new RuntimeException("oops"); + } +} diff --git a/pitest/src/test/java/com/example/testng/InheritsFromAnnotatedBase.java b/pitest/src/test/java/com/example/testng/InheritsFromAnnotatedBase.java index 60ffe8f9a..322328c1a 100644 --- a/pitest/src/test/java/com/example/testng/InheritsFromAnnotatedBase.java +++ b/pitest/src/test/java/com/example/testng/InheritsFromAnnotatedBase.java @@ -1,23 +1,23 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -public class InheritsFromAnnotatedBase extends AnnotatedBase { - - public void aTest() { - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +public class InheritsFromAnnotatedBase extends AnnotatedBase { + + public void aTest() { + + } + +} diff --git a/pitest/src/test/java/com/example/testng/Passes.java b/pitest/src/test/java/com/example/testng/Passes.java index 5155fb592..2d7be4eac 100644 --- a/pitest/src/test/java/com/example/testng/Passes.java +++ b/pitest/src/test/java/com/example/testng/Passes.java @@ -1,23 +1,23 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -public class Passes { - @org.testng.annotations.Test - public void passes() { - - } - +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +public class Passes { + @org.testng.annotations.Test + public void passes() { + + } + } \ No newline at end of file diff --git a/pitest/src/test/java/com/example/testng/Skips.java b/pitest/src/test/java/com/example/testng/Skips.java index 06e94eab1..709fc77fb 100644 --- a/pitest/src/test/java/com/example/testng/Skips.java +++ b/pitest/src/test/java/com/example/testng/Skips.java @@ -1,11 +1,11 @@ -package com.example.testng; - -import org.testng.SkipException; - -public class Skips { - - @org.testng.annotations.Test() - public void skip() { - throw new SkipException("skipping"); - } -} +package com.example.testng; + +import org.testng.SkipException; + +public class Skips { + + @org.testng.annotations.Test() + public void skip() { + throw new SkipException("skipping"); + } +} diff --git a/pitest/src/test/java/com/example/testng/StaticMethods.java b/pitest/src/test/java/com/example/testng/StaticMethods.java index 66e29cba3..94397aa99 100644 --- a/pitest/src/test/java/com/example/testng/StaticMethods.java +++ b/pitest/src/test/java/com/example/testng/StaticMethods.java @@ -1,26 +1,26 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package com.example.testng; - -import org.testng.annotations.Test; - -@Test -public class StaticMethods { - - public static void aTest() { - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package com.example.testng; + +import org.testng.annotations.Test; + +@Test +public class StaticMethods { + + public static void aTest() { + + } + +} diff --git a/pitest/src/test/java/org/pitest/DescriptionMother.java b/pitest/src/test/java/org/pitest/DescriptionMother.java index bc8296c34..1cec89a53 100644 --- a/pitest/src/test/java/org/pitest/DescriptionMother.java +++ b/pitest/src/test/java/org/pitest/DescriptionMother.java @@ -1,25 +1,25 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest; - -import org.pitest.testapi.Description; - -public class DescriptionMother { - - public static Description createEmptyDescription(final String name) { - return new Description(name); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest; + +import org.pitest.testapi.Description; + +public class DescriptionMother { + + public static Description createEmptyDescription(final String name) { + return new Description(name); + } + +} diff --git a/pitest/src/test/java/org/pitest/SystemTest.java b/pitest/src/test/java/org/pitest/SystemTest.java index 575d95cac..a7587dd2c 100644 --- a/pitest/src/test/java/org/pitest/SystemTest.java +++ b/pitest/src/test/java/org/pitest/SystemTest.java @@ -1,5 +1,5 @@ -package org.pitest; - -public interface SystemTest { - -} +package org.pitest; + +public interface SystemTest { + +} diff --git a/pitest/src/test/java/org/pitest/TestJUnitConfiguration.java b/pitest/src/test/java/org/pitest/TestJUnitConfiguration.java index 1be0b7f4d..a416be392 100644 --- a/pitest/src/test/java/org/pitest/TestJUnitConfiguration.java +++ b/pitest/src/test/java/org/pitest/TestJUnitConfiguration.java @@ -1,646 +1,646 @@ -package org.pitest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.jmock.MockObjectTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Categories; -import org.junit.experimental.categories.Categories.IncludeCategory; -import org.junit.experimental.categories.Category; -import org.junit.experimental.theories.DataPoint; -import org.junit.experimental.theories.Theories; -import org.junit.experimental.theories.Theory; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Suite.SuiteClasses; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import java.util.Optional; -import org.pitest.help.PitHelpError; -import org.pitest.junit.JUnitCompatibleConfiguration; -import org.pitest.testapi.Description; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.testapi.TestListener; -import org.pitest.testapi.TestResult; -import org.pitest.testapi.TestUnit; -import org.pitest.testapi.execute.Container; -import org.pitest.testapi.execute.FindTestUnits; -import org.pitest.testapi.execute.Pitest; -import org.pitest.testapi.execute.containers.UnContainer; - -import com.example.JUnitParamsTest; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class TestJUnitConfiguration { - - private JUnitCompatibleConfiguration testee = new JUnitCompatibleConfiguration( - new TestGroupConfig(), - Collections.emptyList(), - Collections.emptyList()); - private Pitest pitest; - private Container container; - - @Mock - private TestListener listener; - - @Before - public void createTestee() { - MockitoAnnotations.initMocks(this); - this.container = new UnContainer(); - - this.pitest = new Pitest(this.listener); - } - - public static class SimpleJUnit4Test { - @Test - public void testOne() { - - } - } - - @Test - public void shouldFindJunit4Tests() { - run(SimpleJUnit4Test.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - public static class JUnit3TestWithSingleStringConstructorAndJUnit4Annotations - extends TestCase { - - private final String name; - - public JUnit3TestWithSingleStringConstructorAndJUnit4Annotations( - final String name) { - super(name); - this.name = name; - } - - @Test - public void testOne() { - assertEquals("testOne", this.name); - } - - @Test - public void testTwo() { - assertEquals("testTwo", this.name); - } - - } - - @Test - public void shouldCallSingleStringArgumentsConstructorWithTestNameWithAnnotations() { - run(JUnit3TestWithSingleStringConstructorAndJUnit4Annotations.class); - verify(this.listener, times(2)).onTestSuccess(any(TestResult.class)); - } - - public static class JUnit3TestWithSingleStringConstructor extends TestCase { - - private final String name; - - public JUnit3TestWithSingleStringConstructor(final String name) { - super(name); - this.name = name; - } - - public void testOne() { - assertEquals("testOne", this.name); - } - - public void testTwo() { - assertEquals("testTwo", this.name); - } - - } - - @Test - public void shouldCallSingleStringArgumentsConstructorWithTestName() { - run(JUnit3TestWithSingleStringConstructor.class); - verify(this.listener, times(2)).onTestSuccess(any(TestResult.class)); - } - - static class HideFromJunit1 { - public static class JUnit4TestWithUnmetExpectations { - @Test(expected = FileNotFoundException.class) - public void testOne() { - - } - } - } - - @Test - public void shouldFailTestsThatDoNotThrowExpectedException() { - run(HideFromJunit1.JUnit4TestWithUnmetExpectations.class); - verify(this.listener).onTestFailure(any(TestResult.class)); - } - - public static class JUnit4TestWithExpectations { - @Test(expected = FileNotFoundException.class) - public void testOne() throws FileNotFoundException { - throw new FileNotFoundException(); - } - } - - @Test - public void shouldPassTestsThatThrowExpectedException() { - run(JUnit4TestWithExpectations.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - public static class SimpleJUnit3Test extends TestCase { - public void testOne() { - - } - } - - @Test - public void testFindJUnit3Tests() { - run(SimpleJUnit3Test.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - public static class MixedJunit3And4Test extends TestCase { - @Test - public void testOne() { - - } - } - - @Test - public void shouldRunOnlyOneTestWhenMatchesBothJunit3And4Criteria() { - run(MixedJunit3And4Test.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - public static class BaseTestCaseWithTest extends TestCase { - public void testFoo() { - - } - - @Test - public void testBar() { - - } - } - - public static class InheritedTest extends BaseTestCaseWithTest { - - } - - public static class OverridesTestInParent extends BaseTestCaseWithTest { - @Override - public void testFoo() { - - } - } - - @Test - public void shouldRunTestsInheritedFromParent() { - run(InheritedTest.class); - verify(this.listener, times(2)).onTestSuccess(any(TestResult.class)); - } - - @Test - public void testOverriddenTestsCalledOnlyOnce() { - run(OverridesTestInParent.class); - verify(this.listener, times(2)).onTestSuccess(any(TestResult.class)); - } - - static abstract class HideFromJunit4 { - - public static class MixedJUnit3And4SetupAndTearDown extends TestCase { - public static int count = 0; - - @Override - @Before - public void setUp() { - count++; - } - - @Override - @After - public void tearDown() { - count = count + 10; - } - - @Test - public void testCallCount() { - assertEquals(1, count); - } - } - } - - @Test - public void shouldCallBeforeAndAfterMethodsEligableForBothJUnit3And4OnlyOnce() { - run(HideFromJunit4.MixedJUnit3And4SetupAndTearDown.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - assertEquals(11, HideFromJunit4.MixedJUnit3And4SetupAndTearDown.count); - } - - public static class TestWithTimeout { - - @Test(timeout = 5) - public void testBar() { - for (int i = 0; i != 10; i++) { - try { - Thread.sleep(1000); - } catch (final InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - - @Test - public void shouldTimeTestsOut() { - run(TestWithTimeout.class); - verify(this.listener).onTestFailure(any(TestResult.class)); - } - - @RunWith(Parameterized.class) - public static class ParameterisedTest { - int i; - - public ParameterisedTest(final int i) { - this.i = i; - } - - @Parameters - public static Collection params() { - return Arrays.asList(new Object[][] { { 1 }, { 2 }, { 3 } }); - } - - @Test - public void test() { - System.out.println(this.i); - } - - @Test - public void test2() { - System.out.println("> " + this.i); - } - - } - - @Test - public void shouldCreateTestForEachParameterOfParameterizedTest() { - run(ParameterisedTest.class); - verify(this.listener, times(6)).onTestSuccess(any(TestResult.class)); - } - - static abstract class HideFromJUnit8 { - @RunWith(Theories.class) - public static class TheoriesTest { - - @DataPoint - public static int i = 1; - - @Theory - public void testTheory(final int i) { - assertEquals(1, i); - } - - @Theory - public void failingTheory(final int i) { - fail(); - } - - @Theory - public void errorTheory(final int i) { - throw new NullPointerException(); - } - - } - } - - @Test - public void shouldRunTestsCreatedByCustomRunners() { - run(HideFromJUnit8.TheoriesTest.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - verify(this.listener, times(2)).onTestFailure(any(TestResult.class)); - } - - static abstract class HideFromJUnit9 { - - public static class JMockTest extends MockObjectTestCase { - org.jmock.Mock mock; - - @Override - public void setUp() { - this.mock = mock(Runnable.class); - this.mock.expects(once()).method("run"); - } - - public void testFails() { - - } - - public void testPasses() { - final Runnable r = (Runnable) this.mock.proxy(); - r.run(); - } - } - - } - - @Test - public void shouldRunJMock1Tests() { - run(HideFromJUnit9.JMockTest.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - verify(this.listener).onTestFailure(any(TestResult.class)); - } - - public static interface Marker { - } - - @RunWith(Categories.class) - @IncludeCategory(Marker.class) - @SuiteClasses({ MarkerTest1.class, MarkerTest2.class }) - public static class CustomSuite { - - } - - @Category(Marker.class) - public static class MarkerTest1 { - @Test - public void one() { - - } - - @Test - public void two() { - - } - } - - @Category(Marker.class) - public static class MarkerTest2 { - @Test - public void one() { - - } - - @Test - public void two() { - - } - } - - @Test - public void shouldSplitTestInSuitesIntoSeperateUnitsWhenUsingNonStandardSuiteRunners() { - final List actual = find(CustomSuite.class); - - System.out.println(actual); - - assertEquals(4, actual.size()); - - } - - @Ignore - public static class AnnotatedAsIgnored { - - @Test - public void ignoreMe() { - - } - - @Test - public void ignoreMeToo() { - - } - - } - - @Test - public void shouldSkipAllMethodsInClassAnnotatedWithIgnore() { - run(AnnotatedAsIgnored.class); - verify(this.listener, times(1)).onTestSkipped((any(TestResult.class))); - verify(this.listener, never()).onTestStart(any(Description.class)); - } - - public static class HasMethodAnnotatedAsIgnored { - - @Test - @Ignore - public void ignoreMe() { - - } - - @Test - @Ignore - public void ignoreMeToo() { - - } - - @Test - public void dontIgnoreMe() { - - } - - } - - @Test - public void shouldSkipAllMethodsAnnotatedWithIgnore() { - run(HasMethodAnnotatedAsIgnored.class); - verify(this.listener, times(2)).onTestSkipped((any(TestResult.class))); - verify(this.listener).onTestSuccess((any(TestResult.class))); - } - - public static class HasMethodAnnotatedAsIgnoredAndBeforeClassAnnotation { - - @BeforeClass - public static void foo() { - - } - - @Test - @Ignore - public void ignoreMe() { - - } - - @Test - public void dontIgnoreMe() { - - } - - } - - @Test - public void shouldNotSkipEnabledTestsInAClassWithBeforeClassAnotationAndAnIgnoredTest() { - run(HasMethodAnnotatedAsIgnoredAndBeforeClassAnnotation.class); - verify(this.listener).onTestSuccess((any(TestResult.class))); - } - - @Test - public void shouldNotReportAnErrorWhenCorrectJUnitVersionOnClasspath() { - assertEquals(Optional. empty(), this.testee.verifyEnvironment()); - } - - public static class HasAssumptionFailure { - @Test - public void testWithFailedAssumption() { - assumeTrue(false); - } - } - - @Test - public void shouldTreatAssumptionFailuesAsSuccess() { - // see http://junit.sourceforge.net/doc/ReleaseNotes4.4.html#assumptions - run(HasAssumptionFailure.class); - verify(this.listener).onTestSuccess((any(TestResult.class))); - } - - public static class JUnit3Test extends TestCase { - public void testSomething() { - - } - - public void testSomethingElse() { - - } - } - - public static class JUnit3SuiteMethod extends TestCase { - public JUnit3SuiteMethod(final String testName) { - super(testName); - } - - public static junit.framework.Test suite() { - final TestSuite suite = new TestSuite(); - suite.addTest(new JUnit3Test()); - return suite; - } - - } - - @Test - public void shouldDetectTestInJUnitThreeSuiteMethods() { - final List actual = find(JUnit3SuiteMethod.class); - assertEquals(2, actual.size()); - } - - public static class OwnSuiteMethod extends TestCase { - - public static TestSuite suite() { - return new TestSuite(OwnSuiteMethod.class); - } - - public void testOne() { - - } - - } - - @Test - public void shouldFindTestsInClassWithASuiteMethod() { - final List actual = find(OwnSuiteMethod.class); - assertEquals(1, actual.size()); - } - - public static class NoSuitableConstructor extends TestCase { - public NoSuitableConstructor(final int i, final int j, final long l) { - - } - - public void testSomething() { - - } - } - - @Test - public void shouldNotFindTestsInJUnit3TestsWithoutASuitableConstructor() { - final List actual = find(NoSuitableConstructor.class); - assertEquals(0, actual.size()); - } - - @Test - // see http://code.google.com/p/junitparams/ - public void shouldFindTestInJUnitParamsTest() { - run(JUnitParamsTest.class); - verify(this.listener, times(3)).onTestSuccess(any(TestResult.class)); - } - - public static class HasOneMethodAnnotatedAsIgnored { - - @Test - public void dontIgnoreMe() { - - } - - @Test - @Ignore - public void ignoreMe() { - - } - - @Test - public void dontIgnoreMeEither() { - - } - - } - - @Test - public void shouldRunOtherMethodsInAClassWithOneIgnoredTest() { - run(HasOneMethodAnnotatedAsIgnored.class); - verify(this.listener, times(2)).onTestSuccess((any(TestResult.class))); - } - - @Test - public void doesNotRunExcludedCategories() { - exclude(ExcludeMe.class); - run(HasExcludedCategory.class); - verify(this.listener, never()).onTestStart(any(Description.class)); - } - - @interface ExcludeMe { - - } - - @ExcludeMe - public static class HasExcludedCategory { - @Test - public void iAmExcluded() { - - } - } - - private void exclude(Class class1) { - final List exclude = Collections.singletonList(class1.getName()); - final List include = Collections.emptyList(); - this.testee = new JUnitCompatibleConfiguration( - new TestGroupConfig(include,exclude), - Collections.emptyList(), Collections.emptyList()); - } - - private void run(final Class clazz) { - this.pitest.run(this.container, this.testee, clazz); - } - - private List find(Class clazz) { - final FindTestUnits finder = new FindTestUnits(this.testee); - return finder.findTestUnitsForAllSuppliedClasses(Arrays - .> asList(clazz)); - } - -} +package org.pitest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.FileNotFoundException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.jmock.MockObjectTestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Categories; +import org.junit.experimental.categories.Categories.IncludeCategory; +import org.junit.experimental.categories.Category; +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.junit.runners.Suite.SuiteClasses; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import java.util.Optional; +import org.pitest.help.PitHelpError; +import org.pitest.junit.JUnitCompatibleConfiguration; +import org.pitest.testapi.Description; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.testapi.TestListener; +import org.pitest.testapi.TestResult; +import org.pitest.testapi.TestUnit; +import org.pitest.testapi.execute.Container; +import org.pitest.testapi.execute.FindTestUnits; +import org.pitest.testapi.execute.Pitest; +import org.pitest.testapi.execute.containers.UnContainer; + +import com.example.JUnitParamsTest; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class TestJUnitConfiguration { + + private JUnitCompatibleConfiguration testee = new JUnitCompatibleConfiguration( + new TestGroupConfig(), + Collections.emptyList(), + Collections.emptyList()); + private Pitest pitest; + private Container container; + + @Mock + private TestListener listener; + + @Before + public void createTestee() { + MockitoAnnotations.initMocks(this); + this.container = new UnContainer(); + + this.pitest = new Pitest(this.listener); + } + + public static class SimpleJUnit4Test { + @Test + public void testOne() { + + } + } + + @Test + public void shouldFindJunit4Tests() { + run(SimpleJUnit4Test.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + public static class JUnit3TestWithSingleStringConstructorAndJUnit4Annotations + extends TestCase { + + private final String name; + + public JUnit3TestWithSingleStringConstructorAndJUnit4Annotations( + final String name) { + super(name); + this.name = name; + } + + @Test + public void testOne() { + assertEquals("testOne", this.name); + } + + @Test + public void testTwo() { + assertEquals("testTwo", this.name); + } + + } + + @Test + public void shouldCallSingleStringArgumentsConstructorWithTestNameWithAnnotations() { + run(JUnit3TestWithSingleStringConstructorAndJUnit4Annotations.class); + verify(this.listener, times(2)).onTestSuccess(any(TestResult.class)); + } + + public static class JUnit3TestWithSingleStringConstructor extends TestCase { + + private final String name; + + public JUnit3TestWithSingleStringConstructor(final String name) { + super(name); + this.name = name; + } + + public void testOne() { + assertEquals("testOne", this.name); + } + + public void testTwo() { + assertEquals("testTwo", this.name); + } + + } + + @Test + public void shouldCallSingleStringArgumentsConstructorWithTestName() { + run(JUnit3TestWithSingleStringConstructor.class); + verify(this.listener, times(2)).onTestSuccess(any(TestResult.class)); + } + + static class HideFromJunit1 { + public static class JUnit4TestWithUnmetExpectations { + @Test(expected = FileNotFoundException.class) + public void testOne() { + + } + } + } + + @Test + public void shouldFailTestsThatDoNotThrowExpectedException() { + run(HideFromJunit1.JUnit4TestWithUnmetExpectations.class); + verify(this.listener).onTestFailure(any(TestResult.class)); + } + + public static class JUnit4TestWithExpectations { + @Test(expected = FileNotFoundException.class) + public void testOne() throws FileNotFoundException { + throw new FileNotFoundException(); + } + } + + @Test + public void shouldPassTestsThatThrowExpectedException() { + run(JUnit4TestWithExpectations.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + public static class SimpleJUnit3Test extends TestCase { + public void testOne() { + + } + } + + @Test + public void testFindJUnit3Tests() { + run(SimpleJUnit3Test.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + public static class MixedJunit3And4Test extends TestCase { + @Test + public void testOne() { + + } + } + + @Test + public void shouldRunOnlyOneTestWhenMatchesBothJunit3And4Criteria() { + run(MixedJunit3And4Test.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + public static class BaseTestCaseWithTest extends TestCase { + public void testFoo() { + + } + + @Test + public void testBar() { + + } + } + + public static class InheritedTest extends BaseTestCaseWithTest { + + } + + public static class OverridesTestInParent extends BaseTestCaseWithTest { + @Override + public void testFoo() { + + } + } + + @Test + public void shouldRunTestsInheritedFromParent() { + run(InheritedTest.class); + verify(this.listener, times(2)).onTestSuccess(any(TestResult.class)); + } + + @Test + public void testOverriddenTestsCalledOnlyOnce() { + run(OverridesTestInParent.class); + verify(this.listener, times(2)).onTestSuccess(any(TestResult.class)); + } + + static abstract class HideFromJunit4 { + + public static class MixedJUnit3And4SetupAndTearDown extends TestCase { + public static int count = 0; + + @Override + @Before + public void setUp() { + count++; + } + + @Override + @After + public void tearDown() { + count = count + 10; + } + + @Test + public void testCallCount() { + assertEquals(1, count); + } + } + } + + @Test + public void shouldCallBeforeAndAfterMethodsEligableForBothJUnit3And4OnlyOnce() { + run(HideFromJunit4.MixedJUnit3And4SetupAndTearDown.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + assertEquals(11, HideFromJunit4.MixedJUnit3And4SetupAndTearDown.count); + } + + public static class TestWithTimeout { + + @Test(timeout = 5) + public void testBar() { + for (int i = 0; i != 10; i++) { + try { + Thread.sleep(1000); + } catch (final InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + + @Test + public void shouldTimeTestsOut() { + run(TestWithTimeout.class); + verify(this.listener).onTestFailure(any(TestResult.class)); + } + + @RunWith(Parameterized.class) + public static class ParameterisedTest { + int i; + + public ParameterisedTest(final int i) { + this.i = i; + } + + @Parameters + public static Collection params() { + return Arrays.asList(new Object[][] { { 1 }, { 2 }, { 3 } }); + } + + @Test + public void test() { + System.out.println(this.i); + } + + @Test + public void test2() { + System.out.println("> " + this.i); + } + + } + + @Test + public void shouldCreateTestForEachParameterOfParameterizedTest() { + run(ParameterisedTest.class); + verify(this.listener, times(6)).onTestSuccess(any(TestResult.class)); + } + + static abstract class HideFromJUnit8 { + @RunWith(Theories.class) + public static class TheoriesTest { + + @DataPoint + public static int i = 1; + + @Theory + public void testTheory(final int i) { + assertEquals(1, i); + } + + @Theory + public void failingTheory(final int i) { + fail(); + } + + @Theory + public void errorTheory(final int i) { + throw new NullPointerException(); + } + + } + } + + @Test + public void shouldRunTestsCreatedByCustomRunners() { + run(HideFromJUnit8.TheoriesTest.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + verify(this.listener, times(2)).onTestFailure(any(TestResult.class)); + } + + static abstract class HideFromJUnit9 { + + public static class JMockTest extends MockObjectTestCase { + org.jmock.Mock mock; + + @Override + public void setUp() { + this.mock = mock(Runnable.class); + this.mock.expects(once()).method("run"); + } + + public void testFails() { + + } + + public void testPasses() { + final Runnable r = (Runnable) this.mock.proxy(); + r.run(); + } + } + + } + + @Test + public void shouldRunJMock1Tests() { + run(HideFromJUnit9.JMockTest.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + verify(this.listener).onTestFailure(any(TestResult.class)); + } + + public static interface Marker { + } + + @RunWith(Categories.class) + @IncludeCategory(Marker.class) + @SuiteClasses({ MarkerTest1.class, MarkerTest2.class }) + public static class CustomSuite { + + } + + @Category(Marker.class) + public static class MarkerTest1 { + @Test + public void one() { + + } + + @Test + public void two() { + + } + } + + @Category(Marker.class) + public static class MarkerTest2 { + @Test + public void one() { + + } + + @Test + public void two() { + + } + } + + @Test + public void shouldSplitTestInSuitesIntoSeperateUnitsWhenUsingNonStandardSuiteRunners() { + final List actual = find(CustomSuite.class); + + System.out.println(actual); + + assertEquals(4, actual.size()); + + } + + @Ignore + public static class AnnotatedAsIgnored { + + @Test + public void ignoreMe() { + + } + + @Test + public void ignoreMeToo() { + + } + + } + + @Test + public void shouldSkipAllMethodsInClassAnnotatedWithIgnore() { + run(AnnotatedAsIgnored.class); + verify(this.listener, times(1)).onTestSkipped((any(TestResult.class))); + verify(this.listener, never()).onTestStart(any(Description.class)); + } + + public static class HasMethodAnnotatedAsIgnored { + + @Test + @Ignore + public void ignoreMe() { + + } + + @Test + @Ignore + public void ignoreMeToo() { + + } + + @Test + public void dontIgnoreMe() { + + } + + } + + @Test + public void shouldSkipAllMethodsAnnotatedWithIgnore() { + run(HasMethodAnnotatedAsIgnored.class); + verify(this.listener, times(2)).onTestSkipped((any(TestResult.class))); + verify(this.listener).onTestSuccess((any(TestResult.class))); + } + + public static class HasMethodAnnotatedAsIgnoredAndBeforeClassAnnotation { + + @BeforeClass + public static void foo() { + + } + + @Test + @Ignore + public void ignoreMe() { + + } + + @Test + public void dontIgnoreMe() { + + } + + } + + @Test + public void shouldNotSkipEnabledTestsInAClassWithBeforeClassAnotationAndAnIgnoredTest() { + run(HasMethodAnnotatedAsIgnoredAndBeforeClassAnnotation.class); + verify(this.listener).onTestSuccess((any(TestResult.class))); + } + + @Test + public void shouldNotReportAnErrorWhenCorrectJUnitVersionOnClasspath() { + assertEquals(Optional. empty(), this.testee.verifyEnvironment()); + } + + public static class HasAssumptionFailure { + @Test + public void testWithFailedAssumption() { + assumeTrue(false); + } + } + + @Test + public void shouldTreatAssumptionFailuesAsSuccess() { + // see http://junit.sourceforge.net/doc/ReleaseNotes4.4.html#assumptions + run(HasAssumptionFailure.class); + verify(this.listener).onTestSuccess((any(TestResult.class))); + } + + public static class JUnit3Test extends TestCase { + public void testSomething() { + + } + + public void testSomethingElse() { + + } + } + + public static class JUnit3SuiteMethod extends TestCase { + public JUnit3SuiteMethod(final String testName) { + super(testName); + } + + public static junit.framework.Test suite() { + final TestSuite suite = new TestSuite(); + suite.addTest(new JUnit3Test()); + return suite; + } + + } + + @Test + public void shouldDetectTestInJUnitThreeSuiteMethods() { + final List actual = find(JUnit3SuiteMethod.class); + assertEquals(2, actual.size()); + } + + public static class OwnSuiteMethod extends TestCase { + + public static TestSuite suite() { + return new TestSuite(OwnSuiteMethod.class); + } + + public void testOne() { + + } + + } + + @Test + public void shouldFindTestsInClassWithASuiteMethod() { + final List actual = find(OwnSuiteMethod.class); + assertEquals(1, actual.size()); + } + + public static class NoSuitableConstructor extends TestCase { + public NoSuitableConstructor(final int i, final int j, final long l) { + + } + + public void testSomething() { + + } + } + + @Test + public void shouldNotFindTestsInJUnit3TestsWithoutASuitableConstructor() { + final List actual = find(NoSuitableConstructor.class); + assertEquals(0, actual.size()); + } + + @Test + // see http://code.google.com/p/junitparams/ + public void shouldFindTestInJUnitParamsTest() { + run(JUnitParamsTest.class); + verify(this.listener, times(3)).onTestSuccess(any(TestResult.class)); + } + + public static class HasOneMethodAnnotatedAsIgnored { + + @Test + public void dontIgnoreMe() { + + } + + @Test + @Ignore + public void ignoreMe() { + + } + + @Test + public void dontIgnoreMeEither() { + + } + + } + + @Test + public void shouldRunOtherMethodsInAClassWithOneIgnoredTest() { + run(HasOneMethodAnnotatedAsIgnored.class); + verify(this.listener, times(2)).onTestSuccess((any(TestResult.class))); + } + + @Test + public void doesNotRunExcludedCategories() { + exclude(ExcludeMe.class); + run(HasExcludedCategory.class); + verify(this.listener, never()).onTestStart(any(Description.class)); + } + + @interface ExcludeMe { + + } + + @ExcludeMe + public static class HasExcludedCategory { + @Test + public void iAmExcluded() { + + } + } + + private void exclude(Class class1) { + final List exclude = Collections.singletonList(class1.getName()); + final List include = Collections.emptyList(); + this.testee = new JUnitCompatibleConfiguration( + new TestGroupConfig(include,exclude), + Collections.emptyList(), Collections.emptyList()); + } + + private void run(final Class clazz) { + this.pitest.run(this.container, this.testee, clazz); + } + + private List find(Class clazz) { + final FindTestUnits finder = new FindTestUnits(this.testee); + return finder.findTestUnitsForAllSuppliedClasses(Arrays + .> asList(clazz)); + } + +} diff --git a/pitest/src/test/java/org/pitest/TestResultTest.java b/pitest/src/test/java/org/pitest/TestResultTest.java index f76f74eef..fb6ccc9ba 100644 --- a/pitest/src/test/java/org/pitest/TestResultTest.java +++ b/pitest/src/test/java/org/pitest/TestResultTest.java @@ -1,24 +1,24 @@ -package org.pitest; - -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.pitest.testapi.Description; -import org.pitest.testapi.TestResult; -import org.pitest.testapi.TestUnitState; -import org.pitest.util.XStreamCloning; - -public class TestResultTest { - - @Test - public void shouldCloneViaXStreamWithoutError() throws Exception { - try { - final TestResult testee = new TestResult((Description) null, null, - TestUnitState.FINISHED); - XStreamCloning.clone(testee); - } catch (final Throwable t) { - fail(); - } - } - -} +package org.pitest; + +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.pitest.testapi.Description; +import org.pitest.testapi.TestResult; +import org.pitest.testapi.TestUnitState; +import org.pitest.util.XStreamCloning; + +public class TestResultTest { + + @Test + public void shouldCloneViaXStreamWithoutError() throws Exception { + try { + final TestResult testee = new TestResult((Description) null, null, + TestUnitState.FINISHED); + XStreamCloning.clone(testee); + } catch (final Throwable t) { + fail(); + } + } + +} diff --git a/pitest/src/test/java/org/pitest/bytecode/FrameOptionsTest.java b/pitest/src/test/java/org/pitest/bytecode/FrameOptionsTest.java index 0e93a56ad..8a6f9d1e9 100644 --- a/pitest/src/test/java/org/pitest/bytecode/FrameOptionsTest.java +++ b/pitest/src/test/java/org/pitest/bytecode/FrameOptionsTest.java @@ -1,63 +1,63 @@ -package org.pitest.bytecode; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.objectweb.asm.ClassWriter; - -public class FrameOptionsTest { - - @Test - public void shouldComputeFramesForJava7() { - assertEquals(ClassWriter.COMPUTE_FRAMES, bytesToTestee("CAFEBABE00000033")); - } - - @Test - public void shouldComputeFramesForJava8() { - assertEquals(ClassWriter.COMPUTE_FRAMES, bytesToTestee("CAFEBABE00000034")); - } - - @Test - public void shouldNotComputeFramesForJava6() { - assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE00000032")); - } - - @Test - public void shouldNotComputeFramesForJava5() { - assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE00000031")); - } - - @Test - public void shouldNotComputeFramesForJava4() { - assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE00000030")); - } - - @Test - public void shouldNotComputeFramesForJava3() { - assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE0000002F")); - } - - @Test - public void shouldNotComputeFramesForJava2() { - assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE0000002E")); - } - - @Test - public void shouldNotComputeFramesForJava1() { - assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE0000002D")); - } - - private int bytesToTestee(String hex) { - return FrameOptions.pickFlags(toByteArray(hex)); - } - - private static byte[] toByteArray(String s) { - final int len = s.length(); - final byte[] data = new byte[len / 2]; - for (int i = 0; i < len; i += 2) { - data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character - .digit(s.charAt(i + 1), 16)); - } - return data; - } -} +package org.pitest.bytecode; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.objectweb.asm.ClassWriter; + +public class FrameOptionsTest { + + @Test + public void shouldComputeFramesForJava7() { + assertEquals(ClassWriter.COMPUTE_FRAMES, bytesToTestee("CAFEBABE00000033")); + } + + @Test + public void shouldComputeFramesForJava8() { + assertEquals(ClassWriter.COMPUTE_FRAMES, bytesToTestee("CAFEBABE00000034")); + } + + @Test + public void shouldNotComputeFramesForJava6() { + assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE00000032")); + } + + @Test + public void shouldNotComputeFramesForJava5() { + assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE00000031")); + } + + @Test + public void shouldNotComputeFramesForJava4() { + assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE00000030")); + } + + @Test + public void shouldNotComputeFramesForJava3() { + assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE0000002F")); + } + + @Test + public void shouldNotComputeFramesForJava2() { + assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE0000002E")); + } + + @Test + public void shouldNotComputeFramesForJava1() { + assertEquals(ClassWriter.COMPUTE_MAXS, bytesToTestee("CAFEBABE0000002D")); + } + + private int bytesToTestee(String hex) { + return FrameOptions.pickFlags(toByteArray(hex)); + } + + private static byte[] toByteArray(String s) { + final int len = s.length(); + final byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character + .digit(s.charAt(i + 1), 16)); + } + return data; + } +} diff --git a/pitest/src/test/java/org/pitest/bytecode/MethodDecoratorTest.java b/pitest/src/test/java/org/pitest/bytecode/MethodDecoratorTest.java index 281d8476b..d177fcf58 100644 --- a/pitest/src/test/java/org/pitest/bytecode/MethodDecoratorTest.java +++ b/pitest/src/test/java/org/pitest/bytecode/MethodDecoratorTest.java @@ -1,185 +1,185 @@ -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.bytecode; - -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; - -public abstract class MethodDecoratorTest { - - protected abstract MethodVisitor getTesteeVisitor(); - - @Mock - protected MethodVisitor mv; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void shouldForwardVisitCodeCallsToChild() { - getTesteeVisitor().visitCode(); - verify(this.mv).visitCode(); - } - - @Test - public void shouldForwardVisitEndCallsToChild() { - getTesteeVisitor().visitEnd(); - verify(this.mv).visitEnd(); - } - - @Test - public void shouldForwardVisitAnnotationCallsToChild() { - getTesteeVisitor().visitAnnotation("foo", true); - verify(this.mv).visitAnnotation("foo", true); - } - - @Test - public void shouldForwardVisitAnnotationDefaultCallsToChild() { - getTesteeVisitor().visitAnnotationDefault(); - verify(this.mv).visitAnnotationDefault(); - } - - @Test - public void shouldForwardVisitAttributeCallsToChild() { - getTesteeVisitor().visitAttribute(null); - verify(this.mv).visitAttribute(null); - } - - @Test - public void shouldForwardVisitFieldInsnCallsToChild() { - getTesteeVisitor().visitFieldInsn(1, "2", "3", "4"); - verify(this.mv).visitFieldInsn(1, "2", "3", "4"); - } - - @Test - public void shouldForwardVisitFrameCallsToChild() { - final Object[] f1 = { 1, 2, 3 }; - final Object[] f2 = { 2, 4, 6 }; - getTesteeVisitor().visitFrame(1, 2, f1, 3, f2); - verify(this.mv).visitFrame(1, 2, f1, 3, f2); - } - - @Test - public void shouldForwardVisitIincInsnToChild() { - getTesteeVisitor().visitIincInsn(1, 2); - verify(this.mv).visitIincInsn(1, 2); - } - - @Test - public void shouldForwardVisitInsnToChild() { - getTesteeVisitor().visitInsn(1); - verify(this.mv).visitInsn(1); - } - - @Test - public void shouldForwardVisitIntInsnToChild() { - getTesteeVisitor().visitIntInsn(1, 2); - verify(this.mv).visitIntInsn(1, 2); - } - - @Test - public void shouldForwardVisitJumpInsnToChild() { - final Label l = new Label(); - getTesteeVisitor().visitJumpInsn(1, l); - verify(this.mv).visitJumpInsn(1, l); - } - - @Test - public void shouldForwardVisitLabelToChild() { - final Label l = new Label(); - getTesteeVisitor().visitLabel(l); - verify(this.mv).visitLabel(l); - } - - @Test - public void shouldForwardVisitLdcInsnToChild() { - getTesteeVisitor().visitLdcInsn(1); - verify(this.mv).visitLdcInsn(1); - } - - @Test - public void shouldForwardVisitLineNumberToChild() { - final Label l = new Label(); - getTesteeVisitor().visitLineNumber(1, l); - verify(this.mv).visitLineNumber(1, l); - } - - @Test - public void shouldForwardVisitLocalVariableToChild() { - final Label l = new Label(); - final Label l2 = new Label(); - getTesteeVisitor().visitLocalVariable("foo", "bar", "one", l, l2, 2); - verify(this.mv).visitLocalVariable("foo", "bar", "one", l, l2, 2); - } - - @Test - public void shouldForwardVisitLookupSwitchInsnToChild() { - final Label l = new Label(); - final Label[] l2 = { new Label() }; - final int[] i = { 1, 2, 3 }; - getTesteeVisitor().visitLookupSwitchInsn(l, i, l2); - verify(this.mv).visitLookupSwitchInsn(l, i, l2); - } - - @Test - public void shouldForwardVisitMaxsToChild() { - getTesteeVisitor().visitMaxs(1, 2); - verify(this.mv).visitMaxs(1, 2); - } - - @Test - public void shouldForwardVisitMethodInsnToChild() { - getTesteeVisitor().visitMethodInsn(1, "a", "b", "c", false); - verify(this.mv).visitMethodInsn(1, "a", "b", "c", false); - } - - @Test - public void shouldForwardVisitMultiANewArrayInsnToChild() { - getTesteeVisitor().visitMultiANewArrayInsn("foo", 1); - verify(this.mv).visitMultiANewArrayInsn("foo", 1); - } - - @Test - public void shouldForwardVisitParameterAnnotationToChild() { - getTesteeVisitor().visitParameterAnnotation(1, "foo", false); - verify(this.mv).visitParameterAnnotation(1, "foo", false); - } - - @Test - public void shouldForwardVisitTableSwitchInsnToChild() { - final Label l = new Label(); - final Label[] l2 = { new Label() }; - getTesteeVisitor().visitTableSwitchInsn(1, 2, l, l2); - verify(this.mv).visitTableSwitchInsn(1, 2, l, l2); - } - - @Test - public void shouldForwardVisitTryCatchBlockToChild() { - final Label l = new Label(); - final Label l2 = new Label(); - final Label l3 = new Label(); - getTesteeVisitor().visitTryCatchBlock(l, l2, l3, "foo"); - verify(this.mv).visitTryCatchBlock(l, l2, l3, "foo"); - } - -} +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.bytecode; + +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; + +public abstract class MethodDecoratorTest { + + protected abstract MethodVisitor getTesteeVisitor(); + + @Mock + protected MethodVisitor mv; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldForwardVisitCodeCallsToChild() { + getTesteeVisitor().visitCode(); + verify(this.mv).visitCode(); + } + + @Test + public void shouldForwardVisitEndCallsToChild() { + getTesteeVisitor().visitEnd(); + verify(this.mv).visitEnd(); + } + + @Test + public void shouldForwardVisitAnnotationCallsToChild() { + getTesteeVisitor().visitAnnotation("foo", true); + verify(this.mv).visitAnnotation("foo", true); + } + + @Test + public void shouldForwardVisitAnnotationDefaultCallsToChild() { + getTesteeVisitor().visitAnnotationDefault(); + verify(this.mv).visitAnnotationDefault(); + } + + @Test + public void shouldForwardVisitAttributeCallsToChild() { + getTesteeVisitor().visitAttribute(null); + verify(this.mv).visitAttribute(null); + } + + @Test + public void shouldForwardVisitFieldInsnCallsToChild() { + getTesteeVisitor().visitFieldInsn(1, "2", "3", "4"); + verify(this.mv).visitFieldInsn(1, "2", "3", "4"); + } + + @Test + public void shouldForwardVisitFrameCallsToChild() { + final Object[] f1 = { 1, 2, 3 }; + final Object[] f2 = { 2, 4, 6 }; + getTesteeVisitor().visitFrame(1, 2, f1, 3, f2); + verify(this.mv).visitFrame(1, 2, f1, 3, f2); + } + + @Test + public void shouldForwardVisitIincInsnToChild() { + getTesteeVisitor().visitIincInsn(1, 2); + verify(this.mv).visitIincInsn(1, 2); + } + + @Test + public void shouldForwardVisitInsnToChild() { + getTesteeVisitor().visitInsn(1); + verify(this.mv).visitInsn(1); + } + + @Test + public void shouldForwardVisitIntInsnToChild() { + getTesteeVisitor().visitIntInsn(1, 2); + verify(this.mv).visitIntInsn(1, 2); + } + + @Test + public void shouldForwardVisitJumpInsnToChild() { + final Label l = new Label(); + getTesteeVisitor().visitJumpInsn(1, l); + verify(this.mv).visitJumpInsn(1, l); + } + + @Test + public void shouldForwardVisitLabelToChild() { + final Label l = new Label(); + getTesteeVisitor().visitLabel(l); + verify(this.mv).visitLabel(l); + } + + @Test + public void shouldForwardVisitLdcInsnToChild() { + getTesteeVisitor().visitLdcInsn(1); + verify(this.mv).visitLdcInsn(1); + } + + @Test + public void shouldForwardVisitLineNumberToChild() { + final Label l = new Label(); + getTesteeVisitor().visitLineNumber(1, l); + verify(this.mv).visitLineNumber(1, l); + } + + @Test + public void shouldForwardVisitLocalVariableToChild() { + final Label l = new Label(); + final Label l2 = new Label(); + getTesteeVisitor().visitLocalVariable("foo", "bar", "one", l, l2, 2); + verify(this.mv).visitLocalVariable("foo", "bar", "one", l, l2, 2); + } + + @Test + public void shouldForwardVisitLookupSwitchInsnToChild() { + final Label l = new Label(); + final Label[] l2 = { new Label() }; + final int[] i = { 1, 2, 3 }; + getTesteeVisitor().visitLookupSwitchInsn(l, i, l2); + verify(this.mv).visitLookupSwitchInsn(l, i, l2); + } + + @Test + public void shouldForwardVisitMaxsToChild() { + getTesteeVisitor().visitMaxs(1, 2); + verify(this.mv).visitMaxs(1, 2); + } + + @Test + public void shouldForwardVisitMethodInsnToChild() { + getTesteeVisitor().visitMethodInsn(1, "a", "b", "c", false); + verify(this.mv).visitMethodInsn(1, "a", "b", "c", false); + } + + @Test + public void shouldForwardVisitMultiANewArrayInsnToChild() { + getTesteeVisitor().visitMultiANewArrayInsn("foo", 1); + verify(this.mv).visitMultiANewArrayInsn("foo", 1); + } + + @Test + public void shouldForwardVisitParameterAnnotationToChild() { + getTesteeVisitor().visitParameterAnnotation(1, "foo", false); + verify(this.mv).visitParameterAnnotation(1, "foo", false); + } + + @Test + public void shouldForwardVisitTableSwitchInsnToChild() { + final Label l = new Label(); + final Label[] l2 = { new Label() }; + getTesteeVisitor().visitTableSwitchInsn(1, 2, l, l2); + verify(this.mv).visitTableSwitchInsn(1, 2, l, l2); + } + + @Test + public void shouldForwardVisitTryCatchBlockToChild() { + final Label l = new Label(); + final Label l2 = new Label(); + final Label l3 = new Label(); + getTesteeVisitor().visitTryCatchBlock(l, l2, l3, "foo"); + verify(this.mv).visitTryCatchBlock(l, l2, l3, "foo"); + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/AddlerHashTest.java b/pitest/src/test/java/org/pitest/classinfo/AddlerHashTest.java index 537db45cc..a82568662 100644 --- a/pitest/src/test/java/org/pitest/classinfo/AddlerHashTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/AddlerHashTest.java @@ -1,43 +1,43 @@ -package org.pitest.classinfo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.Serializable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.coverage.codeassist.ClassUtils; - -public class AddlerHashTest { - - private AddlerHash testee; - - @Before - public void setUp() { - this.testee = new AddlerHash(); - } - - @Test - public void shouldCreateChecksumOfSuppliedBytes() - throws ClassNotFoundException { - assertTrue(this.testee.hash(ClassUtils.classAsBytes(String.class)) != 0); - } - - @Test - public void shouldGenerateSameHashForSameInput() - throws ClassNotFoundException { - final long expected = this.testee.hash(ClassUtils - .classAsBytes(String.class)); - assertEquals(expected, - this.testee.hash(ClassUtils.classAsBytes(String.class))); - } - - @Test - public void shouldCreateDifferentHashesForDifferentClasses() - throws ClassNotFoundException { - assertTrue(this.testee.hash(ClassUtils.classAsBytes(Comparable.class)) != this.testee - .hash(ClassUtils.classAsBytes(Serializable.class))); - } - -} +package org.pitest.classinfo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.Serializable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.coverage.codeassist.ClassUtils; + +public class AddlerHashTest { + + private AddlerHash testee; + + @Before + public void setUp() { + this.testee = new AddlerHash(); + } + + @Test + public void shouldCreateChecksumOfSuppliedBytes() + throws ClassNotFoundException { + assertTrue(this.testee.hash(ClassUtils.classAsBytes(String.class)) != 0); + } + + @Test + public void shouldGenerateSameHashForSameInput() + throws ClassNotFoundException { + final long expected = this.testee.hash(ClassUtils + .classAsBytes(String.class)); + assertEquals(expected, + this.testee.hash(ClassUtils.classAsBytes(String.class))); + } + + @Test + public void shouldCreateDifferentHashesForDifferentClasses() + throws ClassNotFoundException { + assertTrue(this.testee.hash(ClassUtils.classAsBytes(Comparable.class)) != this.testee + .hash(ClassUtils.classAsBytes(Serializable.class))); + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/ClassIdentifierTest.java b/pitest/src/test/java/org/pitest/classinfo/ClassIdentifierTest.java index 13d9dcfb8..75713ca2e 100644 --- a/pitest/src/test/java/org/pitest/classinfo/ClassIdentifierTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/ClassIdentifierTest.java @@ -1,14 +1,14 @@ -package org.pitest.classinfo; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class ClassIdentifierTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(ClassIdentifier.class).verify(); - } - -} +package org.pitest.classinfo; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class ClassIdentifierTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(ClassIdentifier.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/ClassInfoMother.java b/pitest/src/test/java/org/pitest/classinfo/ClassInfoMother.java index b46b77e33..a0b9f9a4a 100644 --- a/pitest/src/test/java/org/pitest/classinfo/ClassInfoMother.java +++ b/pitest/src/test/java/org/pitest/classinfo/ClassInfoMother.java @@ -1,41 +1,41 @@ -package org.pitest.classinfo; - -import org.pitest.quickbuilder.Builder; - -public class ClassInfoMother { - - interface ClassInfoBuilderf extends Builder { - ClassInfoBuilder withId(Builder id); - } - - public static ClassInfo make(final ClassIdentifier id) { - return make(id, new DefaultClassPointer(null)); - } - - public static ClassInfo make(final ClassIdentifier id, final ClassInfo parent) { - return make(id, new DefaultClassPointer(parent)); - } - - public static ClassInfo make(final ClassIdentifier id, - final ClassPointer parent) { - final ClassInfoBuilder data = new ClassInfoBuilder(); - data.id = id; - return new ClassInfo(parent, new DefaultClassPointer(null), data); - } - - public static ClassInfo make(final ClassName name) { - return make(new ClassIdentifier(1, name)); - } - - public static ClassInfo make(final ClassName name, final String fileName) { - final DefaultClassPointer parent = new DefaultClassPointer(null); - final ClassInfoBuilder data = new ClassInfoBuilder(); - data.id = new ClassIdentifier(1, name); - data.sourceFile = fileName; - return new ClassInfo(parent, new DefaultClassPointer(null), data); - } - - public static ClassInfo make(final String name) { - return make(new ClassIdentifier(1, ClassName.fromString(name))); - } -} +package org.pitest.classinfo; + +import org.pitest.quickbuilder.Builder; + +public class ClassInfoMother { + + interface ClassInfoBuilderf extends Builder { + ClassInfoBuilder withId(Builder id); + } + + public static ClassInfo make(final ClassIdentifier id) { + return make(id, new DefaultClassPointer(null)); + } + + public static ClassInfo make(final ClassIdentifier id, final ClassInfo parent) { + return make(id, new DefaultClassPointer(parent)); + } + + public static ClassInfo make(final ClassIdentifier id, + final ClassPointer parent) { + final ClassInfoBuilder data = new ClassInfoBuilder(); + data.id = id; + return new ClassInfo(parent, new DefaultClassPointer(null), data); + } + + public static ClassInfo make(final ClassName name) { + return make(new ClassIdentifier(1, name)); + } + + public static ClassInfo make(final ClassName name, final String fileName) { + final DefaultClassPointer parent = new DefaultClassPointer(null); + final ClassInfoBuilder data = new ClassInfoBuilder(); + data.id = new ClassIdentifier(1, name); + data.sourceFile = fileName; + return new ClassInfo(parent, new DefaultClassPointer(null), data); + } + + public static ClassInfo make(final String name) { + return make(new ClassIdentifier(1, ClassName.fromString(name))); + } +} diff --git a/pitest/src/test/java/org/pitest/classinfo/ClassInfoTest.java b/pitest/src/test/java/org/pitest/classinfo/ClassInfoTest.java index 1958b3d79..c0e806b5b 100644 --- a/pitest/src/test/java/org/pitest/classinfo/ClassInfoTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/ClassInfoTest.java @@ -1,124 +1,124 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.objectweb.asm.Opcodes; -import java.util.Optional; - -public class ClassInfoTest { - - private ClassInfoBuilder data; - private ClassInfo testee; - - @Before - public void setUp() { - this.data = new ClassInfoBuilder(); - this.data.id = new ClassIdentifier(1, ClassName.fromString("foo")); - } - - @Test - public void shouldCreateDifferentHierarchicalHashWhenParentClassChanges() { - final ClassInfo parent = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - final ClassInfo classA = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - final ClassInfo classB = new ClassInfo(pointerTo(parent), - emptyClassPointer(), this.data); - - assertFalse(classA.getHierarchicalId().getHierarchicalHash() - .equals(classB.getHierarchicalId().getHierarchicalHash())); - } - - @Test - public void shouldCreateDifferentHierarchicalHashWhenOuterClassChanges() { - final ClassInfo outer = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - final ClassInfo classA = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - final ClassInfo classB = new ClassInfo(emptyClassPointer(), - pointerTo(outer), this.data); - - assertFalse(classA.getHierarchicalId().getHierarchicalHash() - .equals(classB.getHierarchicalId().getHierarchicalHash())); - } - - @Test - public void shouldReportWhenClassIsSynthetic() { - this.data.access = Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC; - final ClassInfo testee = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - assertTrue(testee.isSynthetic()); - } - - @Test - public void shouldReportWhenClassIsNotSynthetic() { - this.data.access = Opcodes.ACC_PUBLIC; - final ClassInfo testee = new ClassInfo(emptyClassPointer(), - emptyClassPointer(), this.data); - assertFalse(testee.isSynthetic()); - } - - private ClassPointer emptyClassPointer() { - return () -> Optional.empty(); - } - - private ClassPointer pointerTo(final ClassInfo ci) { - return () -> Optional.ofNullable(ci); - } - - @Test - public void isCodeLineReturnShouldTrueForCodeLines() { - final List codeLines = Arrays.asList(1, 2, 3, 4, 5, 6, 10); - addCodeLines(codeLines); - makeTestee(); - for (final int each : codeLines) { - assertTrue(this.testee.isCodeLine(each)); - } - } - - @Test - public void isCodeLineShouldReturnFalseForNonCodeLines() { - final List codeLines = Arrays.asList(1); - addCodeLines(codeLines); - makeTestee(); - assertFalse(this.testee.isCodeLine(2)); - } - - @Test - public void matchIfAbstractShouldReturnTrueForAbstractClasses() { - this.data.access = Opcodes.ACC_ABSTRACT; - makeTestee(); - assertTrue(ClassInfo.matchIfAbstract().test(this.testee)); - } - - private void makeTestee() { - this.testee = new ClassInfo(null, null, this.data); - } - - private void addCodeLines(final List lines) { - for (final int each : lines) { - this.data.registerCodeLine(each); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.objectweb.asm.Opcodes; +import java.util.Optional; + +public class ClassInfoTest { + + private ClassInfoBuilder data; + private ClassInfo testee; + + @Before + public void setUp() { + this.data = new ClassInfoBuilder(); + this.data.id = new ClassIdentifier(1, ClassName.fromString("foo")); + } + + @Test + public void shouldCreateDifferentHierarchicalHashWhenParentClassChanges() { + final ClassInfo parent = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + final ClassInfo classA = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + final ClassInfo classB = new ClassInfo(pointerTo(parent), + emptyClassPointer(), this.data); + + assertFalse(classA.getHierarchicalId().getHierarchicalHash() + .equals(classB.getHierarchicalId().getHierarchicalHash())); + } + + @Test + public void shouldCreateDifferentHierarchicalHashWhenOuterClassChanges() { + final ClassInfo outer = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + final ClassInfo classA = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + final ClassInfo classB = new ClassInfo(emptyClassPointer(), + pointerTo(outer), this.data); + + assertFalse(classA.getHierarchicalId().getHierarchicalHash() + .equals(classB.getHierarchicalId().getHierarchicalHash())); + } + + @Test + public void shouldReportWhenClassIsSynthetic() { + this.data.access = Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC; + final ClassInfo testee = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + assertTrue(testee.isSynthetic()); + } + + @Test + public void shouldReportWhenClassIsNotSynthetic() { + this.data.access = Opcodes.ACC_PUBLIC; + final ClassInfo testee = new ClassInfo(emptyClassPointer(), + emptyClassPointer(), this.data); + assertFalse(testee.isSynthetic()); + } + + private ClassPointer emptyClassPointer() { + return () -> Optional.empty(); + } + + private ClassPointer pointerTo(final ClassInfo ci) { + return () -> Optional.ofNullable(ci); + } + + @Test + public void isCodeLineReturnShouldTrueForCodeLines() { + final List codeLines = Arrays.asList(1, 2, 3, 4, 5, 6, 10); + addCodeLines(codeLines); + makeTestee(); + for (final int each : codeLines) { + assertTrue(this.testee.isCodeLine(each)); + } + } + + @Test + public void isCodeLineShouldReturnFalseForNonCodeLines() { + final List codeLines = Arrays.asList(1); + addCodeLines(codeLines); + makeTestee(); + assertFalse(this.testee.isCodeLine(2)); + } + + @Test + public void matchIfAbstractShouldReturnTrueForAbstractClasses() { + this.data.access = Opcodes.ACC_ABSTRACT; + makeTestee(); + assertTrue(ClassInfo.matchIfAbstract().test(this.testee)); + } + + private void makeTestee() { + this.testee = new ClassInfo(null, null, this.data); + } + + private void addCodeLines(final List lines) { + for (final int each : lines) { + this.data.registerCodeLine(each); + } + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/ClassInfoVisitorTest.java b/pitest/src/test/java/org/pitest/classinfo/ClassInfoVisitorTest.java index 86ee5fc5d..413a5d202 100644 --- a/pitest/src/test/java/org/pitest/classinfo/ClassInfoVisitorTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/ClassInfoVisitorTest.java @@ -1,161 +1,161 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import static java.lang.annotation.ElementType.TYPE; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.pitest.coverage.codeassist.ClassUtils; -import org.pitest.coverage.codeassist.samples.Bridge.HasBridgeMethod; -import org.pitest.coverage.codeassist.samples.HasDefaultConstructor; -import org.pitest.coverage.codeassist.samples.NoDefaultConstructor; - -public class ClassInfoVisitorTest { - - @Test - public void shouldDetectStandardCodeLines() throws Exception { - final String sampleName = NoDefaultConstructor.class.getName(); - final ClassInfoBuilder actual = getClassInfo(sampleName, - ClassUtils.classAsBytes(sampleName)); - - assertTrue(actual.codeLines.contains(25)); - } - - @Test - public void shouldDetectCodeLineAtClassDeclarationsWhenClassHasDefaultConstructor() - throws Exception { - final String sampleName = HasDefaultConstructor.class.getName(); - final ClassInfoBuilder actual = getClassInfo(sampleName, - ClassUtils.classAsBytes(sampleName)); - assertTrue( - "first line of class with default constructor should be a code line", - actual.codeLines.contains(17)); - assertFalse("line before should not be a code line", - actual.codeLines.contains(16)); - } - - @Test - public void shouldNotDetectCodeLineAtClassDeclarationsWhenClassHasNoDefaultConstructor() - throws Exception { - final String sampleName = NoDefaultConstructor.class.getName(); - final ClassInfoBuilder actual = getClassInfo(sampleName, - ClassUtils.classAsBytes(sampleName)); - assertFalse( - "first line of class without default constructor should not be a code line", - actual.codeLines.contains(17)); - } - - @Test - public void shouldNotRecordLineNumbersFromSyntheticBridgeMethods() - throws Exception { - final String sampleName = HasBridgeMethod.class.getName(); - final ClassInfoBuilder actual = getClassInfo(sampleName, - ClassUtils.classAsBytes(sampleName)); - assertFalse(actual.codeLines.contains(1)); - } - - @Test - public void shouldRecordSourceFile() throws ClassNotFoundException { - final String sampleName = String.class.getName(); - final ClassInfoBuilder actual = getClassInfo(sampleName, - ClassUtils.classAsBytes(sampleName)); - assertEquals("String.java", actual.sourceFile); - } - - @Test - public void shouldRecordClassAnnotationValues() throws ClassNotFoundException { - final String sampleName = HasSimpleValue.class.getName(); - final ClassInfoBuilder actual = getClassInfo(sampleName, - ClassUtils.classAsBytes(sampleName)); - - assertEquals(1, actual.classAnnotationValues.size()); - final Object expectedValue = "blah"; - final Object actualValue = actual.classAnnotationValues.get(ClassName - .fromClass(SimpleValue.class)); - assertEquals(expectedValue, actualValue); - } - - @Test - public void shouldRecordClassAnnotationArrayValues() - throws ClassNotFoundException { - final String sampleName = HasStringValues.class.getName(); - final ClassInfoBuilder actual = getClassInfo(sampleName, - ClassUtils.classAsBytes(sampleName)); - - assertEquals(1, actual.classAnnotationValues.size()); - final Object[] expectedStrings = { "this", "that" }; - final Object[] actualStrings = (Object[]) actual.classAnnotationValues - .get(ClassName.fromClass(StringValues.class)); - assertArrayEquals(expectedStrings, actualStrings); - } - - @Test - public void shouldStoreTypeArrayValuesAsClassNames() - throws ClassNotFoundException { - final String sampleName = HasCategory.class.getName(); - final ClassInfoBuilder actual = getClassInfo(sampleName, - ClassUtils.classAsBytes(sampleName)); - - assertEquals(1, actual.classAnnotationValues.size()); - final Object[] expectedCategoryNames = { First.class.getName(), - Second.class.getName() }; - final Object[] actualCategoryNames = (Object[]) actual.classAnnotationValues - .get(ClassName.fromClass(Category.class)); - assertArrayEquals(expectedCategoryNames, actualCategoryNames); - } - - private ClassInfoBuilder getClassInfo(final String name, final byte[] bytes) { - return ClassInfoVisitor.getClassInfo(ClassName.fromString(name), bytes, 0); - } - - @Target(TYPE) - @Retention(RetentionPolicy.RUNTIME) - private @interface SimpleValue { - String value(); - } - - @SimpleValue("blah") - private class HasSimpleValue { - } - - @Target(TYPE) - @Retention(RetentionPolicy.RUNTIME) - private @interface StringValues { - String[] value(); - } - - @StringValues({ "this", "that" }) - private class HasStringValues { - } - - private interface First { - } - - private interface Second { - } - - @Category({ First.class, Second.class }) - private class HasCategory { - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import static java.lang.annotation.ElementType.TYPE; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.pitest.coverage.codeassist.ClassUtils; +import org.pitest.coverage.codeassist.samples.Bridge.HasBridgeMethod; +import org.pitest.coverage.codeassist.samples.HasDefaultConstructor; +import org.pitest.coverage.codeassist.samples.NoDefaultConstructor; + +public class ClassInfoVisitorTest { + + @Test + public void shouldDetectStandardCodeLines() throws Exception { + final String sampleName = NoDefaultConstructor.class.getName(); + final ClassInfoBuilder actual = getClassInfo(sampleName, + ClassUtils.classAsBytes(sampleName)); + + assertTrue(actual.codeLines.contains(25)); + } + + @Test + public void shouldDetectCodeLineAtClassDeclarationsWhenClassHasDefaultConstructor() + throws Exception { + final String sampleName = HasDefaultConstructor.class.getName(); + final ClassInfoBuilder actual = getClassInfo(sampleName, + ClassUtils.classAsBytes(sampleName)); + assertTrue( + "first line of class with default constructor should be a code line", + actual.codeLines.contains(17)); + assertFalse("line before should not be a code line", + actual.codeLines.contains(16)); + } + + @Test + public void shouldNotDetectCodeLineAtClassDeclarationsWhenClassHasNoDefaultConstructor() + throws Exception { + final String sampleName = NoDefaultConstructor.class.getName(); + final ClassInfoBuilder actual = getClassInfo(sampleName, + ClassUtils.classAsBytes(sampleName)); + assertFalse( + "first line of class without default constructor should not be a code line", + actual.codeLines.contains(17)); + } + + @Test + public void shouldNotRecordLineNumbersFromSyntheticBridgeMethods() + throws Exception { + final String sampleName = HasBridgeMethod.class.getName(); + final ClassInfoBuilder actual = getClassInfo(sampleName, + ClassUtils.classAsBytes(sampleName)); + assertFalse(actual.codeLines.contains(1)); + } + + @Test + public void shouldRecordSourceFile() throws ClassNotFoundException { + final String sampleName = String.class.getName(); + final ClassInfoBuilder actual = getClassInfo(sampleName, + ClassUtils.classAsBytes(sampleName)); + assertEquals("String.java", actual.sourceFile); + } + + @Test + public void shouldRecordClassAnnotationValues() throws ClassNotFoundException { + final String sampleName = HasSimpleValue.class.getName(); + final ClassInfoBuilder actual = getClassInfo(sampleName, + ClassUtils.classAsBytes(sampleName)); + + assertEquals(1, actual.classAnnotationValues.size()); + final Object expectedValue = "blah"; + final Object actualValue = actual.classAnnotationValues.get(ClassName + .fromClass(SimpleValue.class)); + assertEquals(expectedValue, actualValue); + } + + @Test + public void shouldRecordClassAnnotationArrayValues() + throws ClassNotFoundException { + final String sampleName = HasStringValues.class.getName(); + final ClassInfoBuilder actual = getClassInfo(sampleName, + ClassUtils.classAsBytes(sampleName)); + + assertEquals(1, actual.classAnnotationValues.size()); + final Object[] expectedStrings = { "this", "that" }; + final Object[] actualStrings = (Object[]) actual.classAnnotationValues + .get(ClassName.fromClass(StringValues.class)); + assertArrayEquals(expectedStrings, actualStrings); + } + + @Test + public void shouldStoreTypeArrayValuesAsClassNames() + throws ClassNotFoundException { + final String sampleName = HasCategory.class.getName(); + final ClassInfoBuilder actual = getClassInfo(sampleName, + ClassUtils.classAsBytes(sampleName)); + + assertEquals(1, actual.classAnnotationValues.size()); + final Object[] expectedCategoryNames = { First.class.getName(), + Second.class.getName() }; + final Object[] actualCategoryNames = (Object[]) actual.classAnnotationValues + .get(ClassName.fromClass(Category.class)); + assertArrayEquals(expectedCategoryNames, actualCategoryNames); + } + + private ClassInfoBuilder getClassInfo(final String name, final byte[] bytes) { + return ClassInfoVisitor.getClassInfo(ClassName.fromString(name), bytes, 0); + } + + @Target(TYPE) + @Retention(RetentionPolicy.RUNTIME) + private @interface SimpleValue { + String value(); + } + + @SimpleValue("blah") + private class HasSimpleValue { + } + + @Target(TYPE) + @Retention(RetentionPolicy.RUNTIME) + private @interface StringValues { + String[] value(); + } + + @StringValues({ "this", "that" }) + private class HasStringValues { + } + + private interface First { + } + + private interface Second { + } + + @Category({ First.class, Second.class }) + private class HasCategory { + } +} diff --git a/pitest/src/test/java/org/pitest/classinfo/ClassNameTest.java b/pitest/src/test/java/org/pitest/classinfo/ClassNameTest.java index 2d3ca6064..1f525ba52 100644 --- a/pitest/src/test/java/org/pitest/classinfo/ClassNameTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/ClassNameTest.java @@ -1,172 +1,172 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class ClassNameTest { - - @Test - public void shouldConvertJavaNamesToInternalNames() { - final ClassName testee = ClassName.fromString("com.foo.bar"); - assertEquals("com/foo/bar", testee.asInternalName()); - } - - @Test - public void shouldConvertInternalNamesToJavaNames() { - final ClassName testee = ClassName.fromString("com/foo/bar"); - assertEquals("com.foo.bar", testee.asJavaName()); - } - - @Test - public void shouldTreatSameClassNameAsEqual() { - final ClassName left = ClassName.fromString("com/foo/bar"); - final ClassName right = ClassName.fromString("com.foo.bar"); - assertTrue(left.equals(right)); - assertTrue(right.equals(left)); - } - - @Test - public void shouldDisplayJavaNameInToString() { - final ClassName testee = ClassName.fromString("com/foo/bar"); - assertEquals("com.foo.bar", testee.toString()); - } - - @Test - public void getNameWithoutPackageShouldReturnNameOnlyWhenClassIsOuterClass() { - assertEquals(ClassName.fromString("String"), - ClassName.fromClass(String.class).getNameWithoutPackage()); - } - - static class Foo { - - } - - @Test - public void getNameWithoutPackageShouldReturnNameWhenClassIsInnerClass() { - assertEquals(ClassName.fromString("ClassNameTest$Foo"), - ClassName.fromClass(Foo.class).getNameWithoutPackage()); - } - - @Test - public void getNameWithoutPackageShouldReturnNameWhenClassInPackageDefault() { - assertEquals(ClassName.fromString("Foo"), - ClassName.fromString("Foo").getNameWithoutPackage()); - } - - @Test - public void getPackageShouldReturnEmptyPackageWhenClassInPackageDefault() { - assertEquals(ClassName.fromString(""), ClassName.fromString("Foo").getPackage()); - } - - @Test - public void getPackageShouldReturnPackageWhenClassWithinAPackage() { - assertEquals(ClassName.fromString("org.pitest.classinfo"), ClassName.fromClass( - ClassNameTest.class).getPackage()); - } - - @Test - public void withoutSuffixCharsShouldReturnPacakgeAndClassWithoutSuffixChars() { - assertEquals(ClassName.fromString("com.example.Foo"), ClassName.fromString( - "com.example.FooTest").withoutSuffixChars(4)); - } - - @Test - public void withoutPrefeixCharsShouldReturnPacakgeAndClassWithoutPrefixChars() { - assertEquals(ClassName.fromString("com.example.Foo"), ClassName.fromString( - "com.example.TestFoo").withoutPrefixChars(4)); - } - - @Test - public void shouldSortByName() { - final ClassName a = ClassName.fromString("a.a.c"); - final ClassName b = ClassName.fromString("a.b.c"); - final ClassName c = ClassName.fromString("b.a.c"); - - final List actual = Arrays.asList(b, c, a); - Collections.sort(actual); - assertEquals(Arrays.asList(a, b, c), actual); - } - - @Test - public void shouldConvertStringToClassName() { - assertEquals(ClassName.fromString("foo"), ClassName.stringToClassName() - .apply("foo")); - } - - @Test - public void shouldProduceSameHashCodeForSameClass() { - assertEquals(ClassName.fromString("org/example/Foo").hashCode(), ClassName - .fromString("org.example.Foo").hashCode()); - } - - @Test - public void shouldProduceDifferentHashCodeForDifferentClasses() { - assertFalse(ClassName.fromString("org/example/Foo").hashCode() == ClassName - .fromString("org.example.Bar").hashCode()); - } - - @Test - public void shouldTreatSameClassAsEqual() { - assertEquals(ClassName.fromString("org/example/Foo"), - ClassName.fromString("org.example.Foo")); - } - - @Test - public void shouldTreatDifferentClassesAsNotEqual() { - assertFalse(ClassName.fromString("org/example/Foo").equals( - ClassName.fromString("org.example.Bar"))); - } - - @Test - public void nameToClassShouldReturnClassWhenKnownToLoader() { - assertThat(ClassName.nameToClass().apply(ClassName.fromString("java.lang.String"))) - .contains(String.class); - } - - @Test - public void stringToClassShouldReturnEmptyWhenClassNotKnownToLoader() { - assertThat(ClassName.nameToClass() - .apply(ClassName.fromString("org.unknown.Unknown"))) - .isEmpty(); - } - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(ClassName.class).verify(); - } - - @Test - public void shouldUseCachedInstancesForObject() { - assertThat(ClassName.fromClass(Object.class)).isSameAs(ClassName.fromClass(Object.class)); - } - - @Test - public void shouldUseCachedInstancesForString() { - assertThat(ClassName.fromClass(String.class)).isSameAs(ClassName.fromClass(String.class)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class ClassNameTest { + + @Test + public void shouldConvertJavaNamesToInternalNames() { + final ClassName testee = ClassName.fromString("com.foo.bar"); + assertEquals("com/foo/bar", testee.asInternalName()); + } + + @Test + public void shouldConvertInternalNamesToJavaNames() { + final ClassName testee = ClassName.fromString("com/foo/bar"); + assertEquals("com.foo.bar", testee.asJavaName()); + } + + @Test + public void shouldTreatSameClassNameAsEqual() { + final ClassName left = ClassName.fromString("com/foo/bar"); + final ClassName right = ClassName.fromString("com.foo.bar"); + assertTrue(left.equals(right)); + assertTrue(right.equals(left)); + } + + @Test + public void shouldDisplayJavaNameInToString() { + final ClassName testee = ClassName.fromString("com/foo/bar"); + assertEquals("com.foo.bar", testee.toString()); + } + + @Test + public void getNameWithoutPackageShouldReturnNameOnlyWhenClassIsOuterClass() { + assertEquals(ClassName.fromString("String"), + ClassName.fromClass(String.class).getNameWithoutPackage()); + } + + static class Foo { + + } + + @Test + public void getNameWithoutPackageShouldReturnNameWhenClassIsInnerClass() { + assertEquals(ClassName.fromString("ClassNameTest$Foo"), + ClassName.fromClass(Foo.class).getNameWithoutPackage()); + } + + @Test + public void getNameWithoutPackageShouldReturnNameWhenClassInPackageDefault() { + assertEquals(ClassName.fromString("Foo"), + ClassName.fromString("Foo").getNameWithoutPackage()); + } + + @Test + public void getPackageShouldReturnEmptyPackageWhenClassInPackageDefault() { + assertEquals(ClassName.fromString(""), ClassName.fromString("Foo").getPackage()); + } + + @Test + public void getPackageShouldReturnPackageWhenClassWithinAPackage() { + assertEquals(ClassName.fromString("org.pitest.classinfo"), ClassName.fromClass( + ClassNameTest.class).getPackage()); + } + + @Test + public void withoutSuffixCharsShouldReturnPacakgeAndClassWithoutSuffixChars() { + assertEquals(ClassName.fromString("com.example.Foo"), ClassName.fromString( + "com.example.FooTest").withoutSuffixChars(4)); + } + + @Test + public void withoutPrefeixCharsShouldReturnPacakgeAndClassWithoutPrefixChars() { + assertEquals(ClassName.fromString("com.example.Foo"), ClassName.fromString( + "com.example.TestFoo").withoutPrefixChars(4)); + } + + @Test + public void shouldSortByName() { + final ClassName a = ClassName.fromString("a.a.c"); + final ClassName b = ClassName.fromString("a.b.c"); + final ClassName c = ClassName.fromString("b.a.c"); + + final List actual = Arrays.asList(b, c, a); + Collections.sort(actual); + assertEquals(Arrays.asList(a, b, c), actual); + } + + @Test + public void shouldConvertStringToClassName() { + assertEquals(ClassName.fromString("foo"), ClassName.stringToClassName() + .apply("foo")); + } + + @Test + public void shouldProduceSameHashCodeForSameClass() { + assertEquals(ClassName.fromString("org/example/Foo").hashCode(), ClassName + .fromString("org.example.Foo").hashCode()); + } + + @Test + public void shouldProduceDifferentHashCodeForDifferentClasses() { + assertFalse(ClassName.fromString("org/example/Foo").hashCode() == ClassName + .fromString("org.example.Bar").hashCode()); + } + + @Test + public void shouldTreatSameClassAsEqual() { + assertEquals(ClassName.fromString("org/example/Foo"), + ClassName.fromString("org.example.Foo")); + } + + @Test + public void shouldTreatDifferentClassesAsNotEqual() { + assertFalse(ClassName.fromString("org/example/Foo").equals( + ClassName.fromString("org.example.Bar"))); + } + + @Test + public void nameToClassShouldReturnClassWhenKnownToLoader() { + assertThat(ClassName.nameToClass().apply(ClassName.fromString("java.lang.String"))) + .contains(String.class); + } + + @Test + public void stringToClassShouldReturnEmptyWhenClassNotKnownToLoader() { + assertThat(ClassName.nameToClass() + .apply(ClassName.fromString("org.unknown.Unknown"))) + .isEmpty(); + } + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(ClassName.class).verify(); + } + + @Test + public void shouldUseCachedInstancesForObject() { + assertThat(ClassName.fromClass(Object.class)).isSameAs(ClassName.fromClass(Object.class)); + } + + @Test + public void shouldUseCachedInstancesForString() { + assertThat(ClassName.fromClass(String.class)).isSameAs(ClassName.fromClass(String.class)); + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/ComputeClassWriterTest.java b/pitest/src/test/java/org/pitest/classinfo/ComputeClassWriterTest.java index 8122c6a96..251f1eaac 100644 --- a/pitest/src/test/java/org/pitest/classinfo/ComputeClassWriterTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/ComputeClassWriterTest.java @@ -1,129 +1,129 @@ -package org.pitest.classinfo; - -import static org.junit.Assert.assertEquals; - -import java.util.HashMap; - -import org.junit.Test; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.util.IsolationUtils; - -public class ComputeClassWriterTest { - - private final ComputeClassWriter testee = new ComputeClassWriter( - new ClassloaderByteArraySource( - IsolationUtils - .getContextClassLoader()), - new HashMap(), 0); - - @Test - public void shouldResolveObjectAsSuperClassWhenNoCommonParentExists() { - assertEquals(ClassName.fromClass(Object.class).asInternalName(), - callTesteeWith(Integer.class, String.class)); - } - - static interface ICommon { - - } - - static class Parent { - - } - - static class Child1 extends Parent { - - } - - static class Child2 extends Parent { - - } - - @Test - public void shouldResolveSuperClassWhenCommonParentExists() { - assertEquals(ClassName.fromClass(Parent.class).asInternalName(), - callTesteeWith(Child1.class, Child2.class)); - } - - static class ImplementsICommon1 implements ICommon { - - } - - static class ImplementsICommon2 implements ICommon { - - } - - @Test - public void shouldResolveObjectAsSuperClassWhenImplementCommonInterface() { - assertEquals(ClassName.fromClass(Object.class).asInternalName(), - callTesteeWith(ImplementsICommon1.class, ImplementsICommon2.class)); - } - - static interface ICommon2 extends ICommon { - - } - - static interface ICommon3 extends ICommon { - - } - - @Test - public void shouldResolveObjectAsSuperClassWhenInterfacesExtendCommonInterface() { - assertEquals(ClassName.fromClass(Object.class).asInternalName(), - callTesteeWith(ICommon2.class, ICommon3.class)); - } - - @Test - public void shouldResolveParentInterfaceWhenSecondInterfaceExtendsTheFirst() { - assertEquals(ClassName.fromClass(ICommon.class).asInternalName(), - callTesteeWith(ICommon.class, ICommon2.class)); - } - - @Test - public void shouldResolveParentInterfaceWhenFirstInterfaceExtendsTheSecond() { - assertEquals(ClassName.fromClass(ICommon.class).asInternalName(), - callTesteeWith(ICommon2.class, ICommon.class)); - } - - static class GrandChild extends Child2 { - - } - - @Test - public void shouldResolveCommonParentWhenNotImmediateParentOfSecondType() { - assertEquals(ClassName.fromClass(Parent.class).asInternalName(), - callTesteeWith(Child1.class, GrandChild.class)); - } - - @Test - public void shouldResolveCommonParentWhenNotImmediateParentOfFirstType() { - assertEquals(ClassName.fromClass(Parent.class).asInternalName(), - callTesteeWith(GrandChild.class, Child1.class)); - } - - static interface ICommonGrandChild extends ICommon3 { - - } - - static interface ICommonGreatGrandChild extends ICommon3 { - - } - - @Test - public void shouldCommonParentInterfaceWhenNotImmediateParentOfSecondType() { - assertEquals(ClassName.fromClass(ICommon3.class).asInternalName(), - callTesteeWith(ICommon3.class, ICommonGreatGrandChild.class)); - } - - @Test - public void shouldCommonParentInterfaceWhenNotImmediateParentOfFirstType() { - assertEquals(ClassName.fromClass(ICommon3.class).asInternalName(), - callTesteeWith(ICommonGreatGrandChild.class, ICommon3.class)); - } - - private final String callTesteeWith(final Class first, - final Class second) { - return this.testee.getCommonSuperClass(ClassName.fromClass(first) - .asInternalName(), ClassName.fromClass(second).asInternalName()); - } - -} +package org.pitest.classinfo; + +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; + +import org.junit.Test; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.util.IsolationUtils; + +public class ComputeClassWriterTest { + + private final ComputeClassWriter testee = new ComputeClassWriter( + new ClassloaderByteArraySource( + IsolationUtils + .getContextClassLoader()), + new HashMap(), 0); + + @Test + public void shouldResolveObjectAsSuperClassWhenNoCommonParentExists() { + assertEquals(ClassName.fromClass(Object.class).asInternalName(), + callTesteeWith(Integer.class, String.class)); + } + + static interface ICommon { + + } + + static class Parent { + + } + + static class Child1 extends Parent { + + } + + static class Child2 extends Parent { + + } + + @Test + public void shouldResolveSuperClassWhenCommonParentExists() { + assertEquals(ClassName.fromClass(Parent.class).asInternalName(), + callTesteeWith(Child1.class, Child2.class)); + } + + static class ImplementsICommon1 implements ICommon { + + } + + static class ImplementsICommon2 implements ICommon { + + } + + @Test + public void shouldResolveObjectAsSuperClassWhenImplementCommonInterface() { + assertEquals(ClassName.fromClass(Object.class).asInternalName(), + callTesteeWith(ImplementsICommon1.class, ImplementsICommon2.class)); + } + + static interface ICommon2 extends ICommon { + + } + + static interface ICommon3 extends ICommon { + + } + + @Test + public void shouldResolveObjectAsSuperClassWhenInterfacesExtendCommonInterface() { + assertEquals(ClassName.fromClass(Object.class).asInternalName(), + callTesteeWith(ICommon2.class, ICommon3.class)); + } + + @Test + public void shouldResolveParentInterfaceWhenSecondInterfaceExtendsTheFirst() { + assertEquals(ClassName.fromClass(ICommon.class).asInternalName(), + callTesteeWith(ICommon.class, ICommon2.class)); + } + + @Test + public void shouldResolveParentInterfaceWhenFirstInterfaceExtendsTheSecond() { + assertEquals(ClassName.fromClass(ICommon.class).asInternalName(), + callTesteeWith(ICommon2.class, ICommon.class)); + } + + static class GrandChild extends Child2 { + + } + + @Test + public void shouldResolveCommonParentWhenNotImmediateParentOfSecondType() { + assertEquals(ClassName.fromClass(Parent.class).asInternalName(), + callTesteeWith(Child1.class, GrandChild.class)); + } + + @Test + public void shouldResolveCommonParentWhenNotImmediateParentOfFirstType() { + assertEquals(ClassName.fromClass(Parent.class).asInternalName(), + callTesteeWith(GrandChild.class, Child1.class)); + } + + static interface ICommonGrandChild extends ICommon3 { + + } + + static interface ICommonGreatGrandChild extends ICommon3 { + + } + + @Test + public void shouldCommonParentInterfaceWhenNotImmediateParentOfSecondType() { + assertEquals(ClassName.fromClass(ICommon3.class).asInternalName(), + callTesteeWith(ICommon3.class, ICommonGreatGrandChild.class)); + } + + @Test + public void shouldCommonParentInterfaceWhenNotImmediateParentOfFirstType() { + assertEquals(ClassName.fromClass(ICommon3.class).asInternalName(), + callTesteeWith(ICommonGreatGrandChild.class, ICommon3.class)); + } + + private final String callTesteeWith(final Class first, + final Class second) { + return this.testee.getCommonSuperClass(ClassName.fromClass(first) + .asInternalName(), ClassName.fromClass(second).asInternalName()); + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/HierarchicalClassIdTest.java b/pitest/src/test/java/org/pitest/classinfo/HierarchicalClassIdTest.java index f94488a8e..92f3e4c00 100644 --- a/pitest/src/test/java/org/pitest/classinfo/HierarchicalClassIdTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/HierarchicalClassIdTest.java @@ -1,14 +1,14 @@ -package org.pitest.classinfo; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class HierarchicalClassIdTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(HierarchicalClassId.class).verify(); - } - -} +package org.pitest.classinfo; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class HierarchicalClassIdTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(HierarchicalClassId.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/NameToClassInfoTest.java b/pitest/src/test/java/org/pitest/classinfo/NameToClassInfoTest.java index c36518b1c..fb55b12ae 100644 --- a/pitest/src/test/java/org/pitest/classinfo/NameToClassInfoTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/NameToClassInfoTest.java @@ -1,18 +1,18 @@ -package org.pitest.classinfo; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import org.junit.Test; - -public class NameToClassInfoTest { - - @Test - public void shouldFetchClassWhenApplied() { - final Repository repository = mock(Repository.class); - final NameToClassInfo testee = new NameToClassInfo(repository); - testee.apply(ClassName.fromString("foo")); - verify(repository).fetchClass(ClassName.fromString("foo")); - } - -} +package org.pitest.classinfo; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import org.junit.Test; + +public class NameToClassInfoTest { + + @Test + public void shouldFetchClassWhenApplied() { + final Repository repository = mock(Repository.class); + final NameToClassInfo testee = new NameToClassInfo(repository); + testee.apply(ClassName.fromString("foo")); + verify(repository).fetchClass(ClassName.fromString("foo")); + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/RepositoryTest.java b/pitest/src/test/java/org/pitest/classinfo/RepositoryTest.java index 81f79a857..b41ed76bf 100644 --- a/pitest/src/test/java/org/pitest/classinfo/RepositoryTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/RepositoryTest.java @@ -1,291 +1,291 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.Serializable; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.coverage.codeassist.ClassUtils; -import java.util.Optional; -import org.pitest.util.IsolationUtils; - -public class RepositoryTest { - - private Repository testee; - - @Mock - private ClassByteArraySource source; - - @Mock - private HashFunction hashFunction; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new Repository(new ClassloaderByteArraySource( - IsolationUtils.getContextClassLoader()), this.hashFunction); - } - - @Test - public void shouldReturnTrueWhenAskedForKnownClass() { - assertTrue(this.testee.hasClass(ClassName.fromClass(Integer.class))); - } - - @Test - public void shouldReturnFalseWhenAskedForUnknownClass() { - assertFalse(this.testee.hasClass(ClassName.fromString("never.heard.of.you"))); - } - - @Test - public void shouldOnlyCheckSourceForUnknownClassesOnce() { - this.testee = new Repository(this.source); - when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); - this.testee.hasClass(ClassName.fromString("foo")); - this.testee.hasClass(ClassName.fromString("foo")); - verify(this.source, times(1)).getBytes("foo"); - } - - @Test - public void shouldReturnNoneWhenAskedForUnknownClass() { - assertEquals(Optional.empty(), - this.testee.fetchClass(ClassName.fromString("never.heard.of.you"))); - } - - @Test - public void shouldOnlyLookForUnknownClassesOnce() { - this.testee = new Repository(this.source); - when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); - this.testee.fetchClass(ClassName.fromString("foo")); - this.testee.fetchClass(ClassName.fromString("foo")); - verify(this.source, times(1)).getBytes("foo"); - } - - @Test - public void shouldOnlyQuerySourceForAnUnknownClassOnce() { - this.testee = new Repository(this.source); - when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); - this.testee.hasClass(ClassName.fromString("foo")); - this.testee.fetchClass(ClassName.fromString("foo")); - verify(this.source, times(1)).getBytes("foo"); - } - - @Test - public void shouldReturnInfoForClassOnClassPath() { - assertTrue(this.testee.fetchClass(Integer.class).isPresent()); - } - - @Test - public void shouldOnlyLookForKnownClassOnce() throws ClassNotFoundException { - this.testee = new Repository(this.source); - when(this.source.getBytes(anyString())).thenReturn( - Optional.ofNullable(ClassUtils.classAsBytes(String.class))); - this.testee.fetchClass(ClassName.fromString("foo")); - this.testee.fetchClass(ClassName.fromString("foo")); - verify(this.source, times(1)).getBytes("foo"); - } - - @Test - public void shouldDetectInterfacesAsInterfaces() { - final Optional anInterface = this.testee - .fetchClass(Serializable.class); - assertTrue(anInterface.get().isInterface()); - } - - @Test - public void shouldDetectInterfacesAsAbstract() { - final Optional anInterface = this.testee - .fetchClass(Serializable.class); - assertTrue(anInterface.get().isAbstract()); - } - - @Test - public void shouldDetectConcreteClassesAsNotInterfaces() { - final Optional aClass = this.testee.fetchClass(String.class); - assertFalse(aClass.get().isInterface()); - } - - @Test - public void shouldDetectConcreteClassesAsNotAbstract() { - final Optional aClass = this.testee.fetchClass(String.class); - assertFalse(aClass.get().isAbstract()); - } - - public static class SimpleInnerClass { - - } - - @Test - public void shouldReportOuterClassForStaticInnerClasses() { - final String actual = getOuterClassNameFor(SimpleInnerClass.class); - assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); - } - - @Test - public void shouldReportOuterClassForLocalClasses() { - final Object local = new Object() { - - }; - - final String actual = getOuterClassNameFor(local.getClass()); - assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); - } - - public class NonStaticInnerClass { - - } - - @Test - public void shouldReportOuterClassForNonStaticInnerClasses() { - final String actual = getOuterClassNameFor(NonStaticInnerClass.class); - assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); - } - - public static class OuterStaticInnerClass { - public static class InnerStaticClass { - - } - } - - @Test - public void shouldReportInnermstOuterClassForNestedInnerClasses() { - final String actual = getOuterClassNameFor(OuterStaticInnerClass.InnerStaticClass.class); - assertEquals( - RepositoryTest.OuterStaticInnerClass.class.getName().replace(".", "/"), - actual); - } - - static class Foo { - - } - - static class Bar extends Foo { - - } - - @Test - public void shouldReportSuperClass() { - final Optional aClass = this.testee.fetchClass(Bar.class); - assertEquals(ClassName.fromClass(Foo.class), aClass.get().getSuperClass() - .get().getName()); - } - - @Test - public void shouldReportSuperClassAsObjectWhenNoneDeclared() { - final Optional aClass = this.testee.fetchClass(Foo.class); - assertEquals(ClassName.fromClass(Object.class), aClass.get().getSuperClass() - .get().getName()); - } - - @Test - public void shouldReportNoSuperClassForObject() { - final Optional aClass = this.testee.fetchClass(Object.class); - assertEquals(Optional.empty(), aClass.get().getSuperClass()); - } - - @Test - public void shouldReportCodeLines() { - final Optional aClass = this.testee - .fetchClass(RepositoryTest.class); - aClass.get().isCodeLine(139); // flakey - } - - @Ignore - static class Annotated { - - } - - @Test - public void shouldRecordClassLevelAnnotations() { - final Optional aClass = this.testee.fetchClass(Annotated.class); - assertTrue(aClass.get().hasAnnotation(Ignore.class)); - } - - static class HasAnnotatedMethod { - @Test - public void foo() { - - } - } - - @Test - public void shouldRecordMethodLevelAnnotations() { - final Optional aClass = this.testee - .fetchClass(HasAnnotatedMethod.class); - assertTrue(aClass.get().hasAnnotation(Test.class)); - } - - static interface ITop { - - } - - static class Top implements ITop { - - } - - static class Middle extends Top { - - } - - static class Bottom extends Middle { - - } - - @Test - public void shouldCorrectlyNegotiateClassHierachies() { - final Optional aClass = this.testee.fetchClass(Bottom.class); - assertTrue(aClass.get().descendsFrom(Middle.class)); - assertTrue(aClass.get().descendsFrom(Top.class)); - assertTrue(aClass.get().descendsFrom(Object.class)); - assertFalse(aClass.get().descendsFrom(String.class)); - } - - @Test - public void doesNotTreatInterfacesAsPartOfClassHierachy() { - final Optional aClass = this.testee.fetchClass(Bottom.class); - assertFalse(aClass.get().descendsFrom(ITop.class)); - } - - @Test - public void shouldRecordSourceFile() { - final Optional aClass = this.testee.fetchClass(String.class); - assertEquals("String.java", aClass.get().getSourceFileName()); - } - - @Test - public void shouldCalculateHashForSuppledClass() { - this.testee.fetchClass(String.class); - verify(this.hashFunction).hash(any(byte[].class)); - } - - private String getOuterClassNameFor(final Class clazz) { - return this.testee.fetchClass(clazz).get().getOuterClass().get() - .getName().asInternalName(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.Serializable; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.coverage.codeassist.ClassUtils; +import java.util.Optional; +import org.pitest.util.IsolationUtils; + +public class RepositoryTest { + + private Repository testee; + + @Mock + private ClassByteArraySource source; + + @Mock + private HashFunction hashFunction; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new Repository(new ClassloaderByteArraySource( + IsolationUtils.getContextClassLoader()), this.hashFunction); + } + + @Test + public void shouldReturnTrueWhenAskedForKnownClass() { + assertTrue(this.testee.hasClass(ClassName.fromClass(Integer.class))); + } + + @Test + public void shouldReturnFalseWhenAskedForUnknownClass() { + assertFalse(this.testee.hasClass(ClassName.fromString("never.heard.of.you"))); + } + + @Test + public void shouldOnlyCheckSourceForUnknownClassesOnce() { + this.testee = new Repository(this.source); + when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); + this.testee.hasClass(ClassName.fromString("foo")); + this.testee.hasClass(ClassName.fromString("foo")); + verify(this.source, times(1)).getBytes("foo"); + } + + @Test + public void shouldReturnNoneWhenAskedForUnknownClass() { + assertEquals(Optional.empty(), + this.testee.fetchClass(ClassName.fromString("never.heard.of.you"))); + } + + @Test + public void shouldOnlyLookForUnknownClassesOnce() { + this.testee = new Repository(this.source); + when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); + this.testee.fetchClass(ClassName.fromString("foo")); + this.testee.fetchClass(ClassName.fromString("foo")); + verify(this.source, times(1)).getBytes("foo"); + } + + @Test + public void shouldOnlyQuerySourceForAnUnknownClassOnce() { + this.testee = new Repository(this.source); + when(this.source.getBytes(anyString())).thenReturn(Optional. empty()); + this.testee.hasClass(ClassName.fromString("foo")); + this.testee.fetchClass(ClassName.fromString("foo")); + verify(this.source, times(1)).getBytes("foo"); + } + + @Test + public void shouldReturnInfoForClassOnClassPath() { + assertTrue(this.testee.fetchClass(Integer.class).isPresent()); + } + + @Test + public void shouldOnlyLookForKnownClassOnce() throws ClassNotFoundException { + this.testee = new Repository(this.source); + when(this.source.getBytes(anyString())).thenReturn( + Optional.ofNullable(ClassUtils.classAsBytes(String.class))); + this.testee.fetchClass(ClassName.fromString("foo")); + this.testee.fetchClass(ClassName.fromString("foo")); + verify(this.source, times(1)).getBytes("foo"); + } + + @Test + public void shouldDetectInterfacesAsInterfaces() { + final Optional anInterface = this.testee + .fetchClass(Serializable.class); + assertTrue(anInterface.get().isInterface()); + } + + @Test + public void shouldDetectInterfacesAsAbstract() { + final Optional anInterface = this.testee + .fetchClass(Serializable.class); + assertTrue(anInterface.get().isAbstract()); + } + + @Test + public void shouldDetectConcreteClassesAsNotInterfaces() { + final Optional aClass = this.testee.fetchClass(String.class); + assertFalse(aClass.get().isInterface()); + } + + @Test + public void shouldDetectConcreteClassesAsNotAbstract() { + final Optional aClass = this.testee.fetchClass(String.class); + assertFalse(aClass.get().isAbstract()); + } + + public static class SimpleInnerClass { + + } + + @Test + public void shouldReportOuterClassForStaticInnerClasses() { + final String actual = getOuterClassNameFor(SimpleInnerClass.class); + assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); + } + + @Test + public void shouldReportOuterClassForLocalClasses() { + final Object local = new Object() { + + }; + + final String actual = getOuterClassNameFor(local.getClass()); + assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); + } + + public class NonStaticInnerClass { + + } + + @Test + public void shouldReportOuterClassForNonStaticInnerClasses() { + final String actual = getOuterClassNameFor(NonStaticInnerClass.class); + assertEquals(RepositoryTest.class.getName().replace(".", "/"), actual); + } + + public static class OuterStaticInnerClass { + public static class InnerStaticClass { + + } + } + + @Test + public void shouldReportInnermstOuterClassForNestedInnerClasses() { + final String actual = getOuterClassNameFor(OuterStaticInnerClass.InnerStaticClass.class); + assertEquals( + RepositoryTest.OuterStaticInnerClass.class.getName().replace(".", "/"), + actual); + } + + static class Foo { + + } + + static class Bar extends Foo { + + } + + @Test + public void shouldReportSuperClass() { + final Optional aClass = this.testee.fetchClass(Bar.class); + assertEquals(ClassName.fromClass(Foo.class), aClass.get().getSuperClass() + .get().getName()); + } + + @Test + public void shouldReportSuperClassAsObjectWhenNoneDeclared() { + final Optional aClass = this.testee.fetchClass(Foo.class); + assertEquals(ClassName.fromClass(Object.class), aClass.get().getSuperClass() + .get().getName()); + } + + @Test + public void shouldReportNoSuperClassForObject() { + final Optional aClass = this.testee.fetchClass(Object.class); + assertEquals(Optional.empty(), aClass.get().getSuperClass()); + } + + @Test + public void shouldReportCodeLines() { + final Optional aClass = this.testee + .fetchClass(RepositoryTest.class); + aClass.get().isCodeLine(139); // flakey + } + + @Ignore + static class Annotated { + + } + + @Test + public void shouldRecordClassLevelAnnotations() { + final Optional aClass = this.testee.fetchClass(Annotated.class); + assertTrue(aClass.get().hasAnnotation(Ignore.class)); + } + + static class HasAnnotatedMethod { + @Test + public void foo() { + + } + } + + @Test + public void shouldRecordMethodLevelAnnotations() { + final Optional aClass = this.testee + .fetchClass(HasAnnotatedMethod.class); + assertTrue(aClass.get().hasAnnotation(Test.class)); + } + + static interface ITop { + + } + + static class Top implements ITop { + + } + + static class Middle extends Top { + + } + + static class Bottom extends Middle { + + } + + @Test + public void shouldCorrectlyNegotiateClassHierachies() { + final Optional aClass = this.testee.fetchClass(Bottom.class); + assertTrue(aClass.get().descendsFrom(Middle.class)); + assertTrue(aClass.get().descendsFrom(Top.class)); + assertTrue(aClass.get().descendsFrom(Object.class)); + assertFalse(aClass.get().descendsFrom(String.class)); + } + + @Test + public void doesNotTreatInterfacesAsPartOfClassHierachy() { + final Optional aClass = this.testee.fetchClass(Bottom.class); + assertFalse(aClass.get().descendsFrom(ITop.class)); + } + + @Test + public void shouldRecordSourceFile() { + final Optional aClass = this.testee.fetchClass(String.class); + assertEquals("String.java", aClass.get().getSourceFileName()); + } + + @Test + public void shouldCalculateHashForSuppledClass() { + this.testee.fetchClass(String.class); + verify(this.hashFunction).hash(any(byte[].class)); + } + + private String getOuterClassNameFor(final Class clazz) { + return this.testee.fetchClass(clazz).get().getOuterClass().get() + .getName().asInternalName(); + } + +} diff --git a/pitest/src/test/java/org/pitest/classinfo/TestToClassMapperTest.java b/pitest/src/test/java/org/pitest/classinfo/TestToClassMapperTest.java index 3fc78f01e..5f2d976b9 100644 --- a/pitest/src/test/java/org/pitest/classinfo/TestToClassMapperTest.java +++ b/pitest/src/test/java/org/pitest/classinfo/TestToClassMapperTest.java @@ -1,68 +1,68 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classinfo; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import java.util.Optional; - -public class TestToClassMapperTest { - - @Mock - private ClassByteArraySource source; - - private Repository repository; - - private TestToClassMapper testee; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.repository = new Repository(this.source); - this.testee = new TestToClassMapper(this.repository); - } - - @Test - public void shouldMapTestsPostfixedWithTestToTesteeWhenTesteeExists() { - final byte[] bytes = { 0 }; - when(this.source.getBytes("com.example.Foo")) - .thenReturn(Optional.ofNullable(bytes)); - assertEquals(ClassName.fromString("com.example.Foo"), - this.testee.findTestee("com.example.FooTest").get()); - } - - @Test - public void shouldMapTestsPrefixedWithTestToTesteeWhenTesteeExists() { - final byte[] bytes = { 0 }; - when(this.source.getBytes("com.example.Foo")) - .thenReturn(Optional.ofNullable(bytes)); - assertEquals(ClassName.fromString("com.example.Foo"), - this.testee.findTestee("com.example.TestFoo").get()); - } - - @Test - public void shouldReturnNoneWhenNoTesteeExistsMatchingNamingConvention() { - final byte[] bytes = null; - when(this.source.getBytes("com.example.Foo")) - .thenReturn(Optional.ofNullable(bytes)); - assertEquals(Optional.empty(), this.testee.findTestee("com.example.TestFoo")); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classinfo; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import java.util.Optional; + +public class TestToClassMapperTest { + + @Mock + private ClassByteArraySource source; + + private Repository repository; + + private TestToClassMapper testee; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.repository = new Repository(this.source); + this.testee = new TestToClassMapper(this.repository); + } + + @Test + public void shouldMapTestsPostfixedWithTestToTesteeWhenTesteeExists() { + final byte[] bytes = { 0 }; + when(this.source.getBytes("com.example.Foo")) + .thenReturn(Optional.ofNullable(bytes)); + assertEquals(ClassName.fromString("com.example.Foo"), + this.testee.findTestee("com.example.FooTest").get()); + } + + @Test + public void shouldMapTestsPrefixedWithTestToTesteeWhenTesteeExists() { + final byte[] bytes = { 0 }; + when(this.source.getBytes("com.example.Foo")) + .thenReturn(Optional.ofNullable(bytes)); + assertEquals(ClassName.fromString("com.example.Foo"), + this.testee.findTestee("com.example.TestFoo").get()); + } + + @Test + public void shouldReturnNoneWhenNoTesteeExistsMatchingNamingConvention() { + final byte[] bytes = null; + when(this.source.getBytes("com.example.Foo")) + .thenReturn(Optional.ofNullable(bytes)); + assertEquals(Optional.empty(), this.testee.findTestee("com.example.TestFoo")); + } + +} diff --git a/pitest/src/test/java/org/pitest/classpath/ArchiveClassPathRootTest.java b/pitest/src/test/java/org/pitest/classpath/ArchiveClassPathRootTest.java index 785d6a0ad..e80285517 100644 --- a/pitest/src/test/java/org/pitest/classpath/ArchiveClassPathRootTest.java +++ b/pitest/src/test/java/org/pitest/classpath/ArchiveClassPathRootTest.java @@ -1,84 +1,84 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; - -public class ArchiveClassPathRootTest { - - private ArchiveClassPathRoot testee; - - @Before - public void setup() throws Exception { - // note mytests.jar is taken from - // http://johanneslink.net/projects/cpsuite.jsp - // assume GPL licence for this file. We do not link to any code within it - // however - this.testee = new ArchiveClassPathRoot(new File("mytests.jar")); - } - - @Test - public void classNamesShouldReturnAllClassNamesIArchive() { - final Collection expected = Arrays.asList( - "injar.p1.P1NoTest$InnerTest", "injar.p1.P1NoTest", "injar.p1.P1Test", - "injar.p2.P2Test"); - assertEquals(expected, this.testee.classNames()); - } - - @Test - public void getDataShouldReturnNullForUnknownClass() throws Exception { - assertNull(this.testee.getData("bar")); - } - - @Test - public void getDataShouldReturnInputStreamForAKnownClass() throws Exception { - assertNotNull(this.testee.getData("injar.p1.P1Test")); - } - - @Test - public void shouldReturnAReadableInputStream() { - final byte b[] = new byte[100]; - try { - final InputStream actual = this.testee.getData("injar.p1.P1Test"); - actual.read(b); - } catch (final IOException ex) { - fail(); - } - } - - @Test - public void getResourceShouldReturnNullForAnUnknownResource() - throws Exception { - assertNull(this.testee.getResource("bar")); - } - - @Test - public void getResourceShouldReturnURLForAKnownResource() throws Exception { - assertNotNull(this.testee.getResource("injar/p1/P1Test.class")); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; + +public class ArchiveClassPathRootTest { + + private ArchiveClassPathRoot testee; + + @Before + public void setup() throws Exception { + // note mytests.jar is taken from + // http://johanneslink.net/projects/cpsuite.jsp + // assume GPL licence for this file. We do not link to any code within it + // however + this.testee = new ArchiveClassPathRoot(new File("mytests.jar")); + } + + @Test + public void classNamesShouldReturnAllClassNamesIArchive() { + final Collection expected = Arrays.asList( + "injar.p1.P1NoTest$InnerTest", "injar.p1.P1NoTest", "injar.p1.P1Test", + "injar.p2.P2Test"); + assertEquals(expected, this.testee.classNames()); + } + + @Test + public void getDataShouldReturnNullForUnknownClass() throws Exception { + assertNull(this.testee.getData("bar")); + } + + @Test + public void getDataShouldReturnInputStreamForAKnownClass() throws Exception { + assertNotNull(this.testee.getData("injar.p1.P1Test")); + } + + @Test + public void shouldReturnAReadableInputStream() { + final byte b[] = new byte[100]; + try { + final InputStream actual = this.testee.getData("injar.p1.P1Test"); + actual.read(b); + } catch (final IOException ex) { + fail(); + } + } + + @Test + public void getResourceShouldReturnNullForAnUnknownResource() + throws Exception { + assertNull(this.testee.getResource("bar")); + } + + @Test + public void getResourceShouldReturnURLForAKnownResource() throws Exception { + assertNotNull(this.testee.getResource("injar/p1/P1Test.class")); + } + +} diff --git a/pitest/src/test/java/org/pitest/classpath/ClassPathTest.java b/pitest/src/test/java/org/pitest/classpath/ClassPathTest.java index 260fa64a5..0d71f29ee 100644 --- a/pitest/src/test/java/org/pitest/classpath/ClassPathTest.java +++ b/pitest/src/test/java/org/pitest/classpath/ClassPathTest.java @@ -1,91 +1,91 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import java.util.Optional; -import org.pitest.functional.prelude.Prelude; - -public class ClassPathTest { - - private ClassPath testee; - - @Mock - private ClassPathRoot firstComponent; - - @Mock - private ClassPathRoot secondComponent; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new ClassPath(this.firstComponent, this.secondComponent); - when(this.firstComponent.cacheLocation()).thenReturn(Optional.ofNullable("foo")); - when(this.firstComponent.classNames()).thenReturn( - Collections.singletonList("FooClass")); - when(this.secondComponent.cacheLocation()).thenReturn(Optional.ofNullable("bar")); - when(this.secondComponent.classNames()).thenReturn( - Collections.singletonList("BarClass")); - } - - @Test - public void shouldReturnBytesFromClasspathInputStream() throws IOException { - final InputStream stream = Mockito.mock(InputStream.class); - when(this.firstComponent.getData(any(String.class))).thenReturn(stream); - when(stream.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1); - this.testee.getClassData("foo"); - verify(stream).read(any(byte[].class), anyInt(), anyInt()); - verify(stream).close(); - } - - @Test - public void shouldReturnAllClassNames() { - assertEquals(Arrays.asList("FooClass", "BarClass"), - this.testee.classNames()); - } - - @Test - public void shouldFindMatchingClasses() { - assertEquals(Arrays.asList("FooClass"), - this.testee.findClasses(Prelude.isEqualTo("FooClass"))); - } - - @Test - public void shouldAllowSubComponentsToBeSelected() { - assertEquals(Collections.singletonList("FooClass"), this.testee - .getComponent(rootIsEqualTo("foo")).classNames()); - } - - private Predicate rootIsEqualTo(final String value) { - return a -> a.cacheLocation().get().equals(value); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import java.util.Optional; +import org.pitest.functional.prelude.Prelude; + +public class ClassPathTest { + + private ClassPath testee; + + @Mock + private ClassPathRoot firstComponent; + + @Mock + private ClassPathRoot secondComponent; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new ClassPath(this.firstComponent, this.secondComponent); + when(this.firstComponent.cacheLocation()).thenReturn(Optional.ofNullable("foo")); + when(this.firstComponent.classNames()).thenReturn( + Collections.singletonList("FooClass")); + when(this.secondComponent.cacheLocation()).thenReturn(Optional.ofNullable("bar")); + when(this.secondComponent.classNames()).thenReturn( + Collections.singletonList("BarClass")); + } + + @Test + public void shouldReturnBytesFromClasspathInputStream() throws IOException { + final InputStream stream = Mockito.mock(InputStream.class); + when(this.firstComponent.getData(any(String.class))).thenReturn(stream); + when(stream.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1); + this.testee.getClassData("foo"); + verify(stream).read(any(byte[].class), anyInt(), anyInt()); + verify(stream).close(); + } + + @Test + public void shouldReturnAllClassNames() { + assertEquals(Arrays.asList("FooClass", "BarClass"), + this.testee.classNames()); + } + + @Test + public void shouldFindMatchingClasses() { + assertEquals(Arrays.asList("FooClass"), + this.testee.findClasses(Prelude.isEqualTo("FooClass"))); + } + + @Test + public void shouldAllowSubComponentsToBeSelected() { + assertEquals(Collections.singletonList("FooClass"), this.testee + .getComponent(rootIsEqualTo("foo")).classNames()); + } + + private Predicate rootIsEqualTo(final String value) { + return a -> a.cacheLocation().get().equals(value); + } + +} diff --git a/pitest/src/test/java/org/pitest/classpath/CodeSourceTest.java b/pitest/src/test/java/org/pitest/classpath/CodeSourceTest.java index d11f79d9f..06e96f4b2 100644 --- a/pitest/src/test/java/org/pitest/classpath/CodeSourceTest.java +++ b/pitest/src/test/java/org/pitest/classpath/CodeSourceTest.java @@ -1,114 +1,114 @@ -package org.pitest.classpath; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.ClassInfoMother; -import org.pitest.classinfo.ClassName; -import org.pitest.classinfo.Repository; -import java.util.Optional; - -public class CodeSourceTest { - - private CodeSource testee; - - @Mock - private Repository repository; - - @Mock - private ProjectClassPaths classPath; - - private ClassInfo foo; - - private ClassInfo bar; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new CodeSource(this.classPath, this.repository); - this.foo = makeClassInfo("Foo"); - this.bar = makeClassInfo("Bar"); - } - - @Test - public void shouldIdentifyAllNonTestCodeOnClassPathWhenNoTestsPresent() { - when(this.classPath.code()).thenReturn( - Arrays.asList(this.foo.getName(), this.bar.getName())); - assertEquals(Arrays.asList(this.foo, this.bar), this.testee.getCode()); - } - - @Test - public void shouldIdentifyTestClassesOnTestPath() { - when(this.classPath.test()).thenReturn( - Arrays.asList(this.foo.getName(), this.bar.getName())); - assertThat(this.testee.getTests()).containsExactly(this.foo, this.bar); - } - - @Test - public void shouldProvideNamesOfCodeClasses() { - final ClassInfo foo = makeClassInfo("Foo"); - final ClassInfo bar = makeClassInfo("Bar"); - when(this.classPath.code()).thenReturn( - Arrays.asList(foo.getName(), bar.getName())); - - assertThat(this.testee.getCodeUnderTestNames()).containsOnly(ClassName.fromString("Foo") - , ClassName.fromString("Bar")); - } - - @Test - public void shouldMapTestsPostfixedWithTestToTesteeWhenTesteeExists() { - when(this.repository.hasClass(ClassName.fromString("com.example.Foo"))) - .thenReturn(true); - assertEquals(ClassName.fromString("com.example.Foo"), - this.testee.findTestee("com.example.FooTest").get()); - } - - @Test - public void shouldMapTestsPrefixedWithTestToTesteeWhenTesteeExists() { - when(this.repository.hasClass(ClassName.fromString("com.example.Foo"))) - .thenReturn(true); - assertEquals(ClassName.fromString("com.example.Foo"), - this.testee.findTestee("com.example.TestFoo").get()); - } - - @Test - public void shouldReturnNoneWhenNoTesteeExistsMatchingNamingConvention() { - when(this.repository.hasClass(ClassName.fromString("com.example.Foo"))) - .thenReturn(false); - assertEquals(Optional. empty(), - this.testee.findTestee("com.example.TestFoo")); - } - - @Test - public void shouldProvideDetailsOfRequestedClasses() { - when(this.repository.fetchClass(ClassName.fromString("Foo"))).thenReturn( - Optional.ofNullable(this.foo)); - when(this.repository.fetchClass(ClassName.fromString("Unknown"))) - .thenReturn(Optional. empty()); - assertEquals(Arrays.asList(this.foo), this.testee.getClassInfo(Arrays - .asList(ClassName.fromString("Foo"), ClassName.fromString("Unknown")))); - } - - @Test - public void shouldAllowClientsToRetrieveBytecode() { - this.testee.fetchClassBytes(ClassName.fromString("Foo")); - verify(this.repository).querySource(ClassName.fromString("Foo")); - } - - private ClassInfo makeClassInfo(final String name) { - final ClassInfo ci = ClassInfoMother.make(name); - when(this.repository.fetchClass(ClassName.fromString(name))).thenReturn( - Optional.ofNullable(ci)); - return ci; - } - -} +package org.pitest.classpath; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.ClassInfoMother; +import org.pitest.classinfo.ClassName; +import org.pitest.classinfo.Repository; +import java.util.Optional; + +public class CodeSourceTest { + + private CodeSource testee; + + @Mock + private Repository repository; + + @Mock + private ProjectClassPaths classPath; + + private ClassInfo foo; + + private ClassInfo bar; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new CodeSource(this.classPath, this.repository); + this.foo = makeClassInfo("Foo"); + this.bar = makeClassInfo("Bar"); + } + + @Test + public void shouldIdentifyAllNonTestCodeOnClassPathWhenNoTestsPresent() { + when(this.classPath.code()).thenReturn( + Arrays.asList(this.foo.getName(), this.bar.getName())); + assertEquals(Arrays.asList(this.foo, this.bar), this.testee.getCode()); + } + + @Test + public void shouldIdentifyTestClassesOnTestPath() { + when(this.classPath.test()).thenReturn( + Arrays.asList(this.foo.getName(), this.bar.getName())); + assertThat(this.testee.getTests()).containsExactly(this.foo, this.bar); + } + + @Test + public void shouldProvideNamesOfCodeClasses() { + final ClassInfo foo = makeClassInfo("Foo"); + final ClassInfo bar = makeClassInfo("Bar"); + when(this.classPath.code()).thenReturn( + Arrays.asList(foo.getName(), bar.getName())); + + assertThat(this.testee.getCodeUnderTestNames()).containsOnly(ClassName.fromString("Foo") + , ClassName.fromString("Bar")); + } + + @Test + public void shouldMapTestsPostfixedWithTestToTesteeWhenTesteeExists() { + when(this.repository.hasClass(ClassName.fromString("com.example.Foo"))) + .thenReturn(true); + assertEquals(ClassName.fromString("com.example.Foo"), + this.testee.findTestee("com.example.FooTest").get()); + } + + @Test + public void shouldMapTestsPrefixedWithTestToTesteeWhenTesteeExists() { + when(this.repository.hasClass(ClassName.fromString("com.example.Foo"))) + .thenReturn(true); + assertEquals(ClassName.fromString("com.example.Foo"), + this.testee.findTestee("com.example.TestFoo").get()); + } + + @Test + public void shouldReturnNoneWhenNoTesteeExistsMatchingNamingConvention() { + when(this.repository.hasClass(ClassName.fromString("com.example.Foo"))) + .thenReturn(false); + assertEquals(Optional. empty(), + this.testee.findTestee("com.example.TestFoo")); + } + + @Test + public void shouldProvideDetailsOfRequestedClasses() { + when(this.repository.fetchClass(ClassName.fromString("Foo"))).thenReturn( + Optional.ofNullable(this.foo)); + when(this.repository.fetchClass(ClassName.fromString("Unknown"))) + .thenReturn(Optional. empty()); + assertEquals(Arrays.asList(this.foo), this.testee.getClassInfo(Arrays + .asList(ClassName.fromString("Foo"), ClassName.fromString("Unknown")))); + } + + @Test + public void shouldAllowClientsToRetrieveBytecode() { + this.testee.fetchClassBytes(ClassName.fromString("Foo")); + verify(this.repository).querySource(ClassName.fromString("Foo")); + } + + private ClassInfo makeClassInfo(final String name) { + final ClassInfo ci = ClassInfoMother.make(name); + when(this.repository.fetchClass(ClassName.fromString(name))).thenReturn( + Optional.ofNullable(ci)); + return ci; + } + +} diff --git a/pitest/src/test/java/org/pitest/classpath/CompoundClassPathRootTest.java b/pitest/src/test/java/org/pitest/classpath/CompoundClassPathRootTest.java index 7f66ca761..04110b5b7 100644 --- a/pitest/src/test/java/org/pitest/classpath/CompoundClassPathRootTest.java +++ b/pitest/src/test/java/org/pitest/classpath/CompoundClassPathRootTest.java @@ -1,94 +1,94 @@ -package org.pitest.classpath; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -public class CompoundClassPathRootTest { - - private CompoundClassPathRoot testee; - - @Mock - private ClassPathRoot child1; - - @Mock - private ClassPathRoot child2; - - @Mock - private IOHeavyRoot heavyChild; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new CompoundClassPathRoot(Arrays.asList(this.child1,this.heavyChild, - this.child2)); - } - - @Test - public void shouldReturnNamesOfAllClassesKnownByChildren() { - - when(this.child1.classNames()).thenReturn(Collections.singletonList("Foo")); - when(this.child2.classNames()).thenReturn(Collections.singletonList("Bar")); - when(this.heavyChild.classNames()).thenReturn(Collections.singletonList("Heavy")); - - assertThat(this.testee.classNames()).containsOnly("Foo", "Bar", "Heavy"); - - } - - @Test - public void shouldReturnNullWhenNoChildCanSupplyData() throws IOException { - assertThat(this.testee.getData("unknown")).isNull(); - } - - @Test - public void shouldReturnNullWhenNoChildCanSupplyResource() throws IOException { - assertThat(this.testee.getResource("unknown")).isNull(); - } - - @Test - public void shouldReturnClassDataFromChildren() throws IOException { - when(this.child1.getData(any(String.class))).thenReturn(null); - final InputStream is = Mockito.mock(InputStream.class); - when(this.child1.getData(any(String.class))).thenReturn(is); - assertThat(this.testee.getData("Foo")).isSameAs(is); - } - - @Test - public void shouldReturnResourcesFromChildren() throws IOException { - when(this.child1.getResource(any(String.class))).thenReturn(null); - final URL url = new URL("http://localhost"); - when(this.child1.getResource(any(String.class))).thenReturn(url); - assertThat(this.testee.getResource("Foo")).isSameAs(url); - } - - @Test - public void shouldNotQueryHeavyRootsForClassesTheyDoNotContain() throws IOException { - when(this.child1.classNames()).thenReturn(Collections.singletonList("Foo")); - when(this.heavyChild.classNames()).thenReturn(Collections.singletonList("Heavy")); - when(this.child2.classNames()).thenReturn(Collections.singletonList("Bar")); - - - this.testee.getData("Bar"); - verify(this.heavyChild,never()).getData("Bar"); - - this.testee.getData("Heavy"); - verify(this.heavyChild).getData("Heavy"); - } - -} - - +package org.pitest.classpath; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +public class CompoundClassPathRootTest { + + private CompoundClassPathRoot testee; + + @Mock + private ClassPathRoot child1; + + @Mock + private ClassPathRoot child2; + + @Mock + private IOHeavyRoot heavyChild; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new CompoundClassPathRoot(Arrays.asList(this.child1,this.heavyChild, + this.child2)); + } + + @Test + public void shouldReturnNamesOfAllClassesKnownByChildren() { + + when(this.child1.classNames()).thenReturn(Collections.singletonList("Foo")); + when(this.child2.classNames()).thenReturn(Collections.singletonList("Bar")); + when(this.heavyChild.classNames()).thenReturn(Collections.singletonList("Heavy")); + + assertThat(this.testee.classNames()).containsOnly("Foo", "Bar", "Heavy"); + + } + + @Test + public void shouldReturnNullWhenNoChildCanSupplyData() throws IOException { + assertThat(this.testee.getData("unknown")).isNull(); + } + + @Test + public void shouldReturnNullWhenNoChildCanSupplyResource() throws IOException { + assertThat(this.testee.getResource("unknown")).isNull(); + } + + @Test + public void shouldReturnClassDataFromChildren() throws IOException { + when(this.child1.getData(any(String.class))).thenReturn(null); + final InputStream is = Mockito.mock(InputStream.class); + when(this.child1.getData(any(String.class))).thenReturn(is); + assertThat(this.testee.getData("Foo")).isSameAs(is); + } + + @Test + public void shouldReturnResourcesFromChildren() throws IOException { + when(this.child1.getResource(any(String.class))).thenReturn(null); + final URL url = new URL("http://localhost"); + when(this.child1.getResource(any(String.class))).thenReturn(url); + assertThat(this.testee.getResource("Foo")).isSameAs(url); + } + + @Test + public void shouldNotQueryHeavyRootsForClassesTheyDoNotContain() throws IOException { + when(this.child1.classNames()).thenReturn(Collections.singletonList("Foo")); + when(this.heavyChild.classNames()).thenReturn(Collections.singletonList("Heavy")); + when(this.child2.classNames()).thenReturn(Collections.singletonList("Bar")); + + + this.testee.getData("Bar"); + verify(this.heavyChild,never()).getData("Bar"); + + this.testee.getData("Heavy"); + verify(this.heavyChild).getData("Heavy"); + } + +} + + diff --git a/pitest/src/test/java/org/pitest/classpath/DirectoryClassPathRootTest.java b/pitest/src/test/java/org/pitest/classpath/DirectoryClassPathRootTest.java index ea555af5c..6e2d54d8c 100644 --- a/pitest/src/test/java/org/pitest/classpath/DirectoryClassPathRootTest.java +++ b/pitest/src/test/java/org/pitest/classpath/DirectoryClassPathRootTest.java @@ -1,29 +1,29 @@ -package org.pitest.classpath; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; - -import org.junit.Test; - -public class DirectoryClassPathRootTest { - - private DirectoryClassPathRoot testee; - - @Test - public void getDataShouldReturnNullForUnknownClass() throws Exception { - this.testee = new DirectoryClassPathRoot(new File("foo")); - assertNull(this.testee.getData("bar")); - } - - @Test - public void shouldReturnClassNames() { - final File root = new File("target/test-classes/"); // this is going to be - // flakey as hell - this.testee = new DirectoryClassPathRoot(root); - assertTrue(this.testee.classNames().contains( - DirectoryClassPathRootTest.class.getName())); - } - -} +package org.pitest.classpath; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Test; + +public class DirectoryClassPathRootTest { + + private DirectoryClassPathRoot testee; + + @Test + public void getDataShouldReturnNullForUnknownClass() throws Exception { + this.testee = new DirectoryClassPathRoot(new File("foo")); + assertNull(this.testee.getData("bar")); + } + + @Test + public void shouldReturnClassNames() { + final File root = new File("target/test-classes/"); // this is going to be + // flakey as hell + this.testee = new DirectoryClassPathRoot(root); + assertTrue(this.testee.classNames().contains( + DirectoryClassPathRootTest.class.getName())); + } + +} diff --git a/pitest/src/test/java/org/pitest/classpath/OtherClassLoaderClassPathRootTest.java b/pitest/src/test/java/org/pitest/classpath/OtherClassLoaderClassPathRootTest.java index aa0664e17..44eb66d99 100644 --- a/pitest/src/test/java/org/pitest/classpath/OtherClassLoaderClassPathRootTest.java +++ b/pitest/src/test/java/org/pitest/classpath/OtherClassLoaderClassPathRootTest.java @@ -1,52 +1,52 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.classpath; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.Before; -import org.junit.Test; - -public class OtherClassLoaderClassPathRootTest { - - private OtherClassLoaderClassPathRoot testee; - - @Before - public void setup() { - this.testee = new OtherClassLoaderClassPathRoot(Thread.currentThread() - .getContextClassLoader()); - } - - @Test(expected = UnsupportedOperationException.class) - public void getClassNamesShouldThrowUnsupportedOperation() { - this.testee.classNames(); - } - - @Test - public void shouldReturnsBytesForClassesVisibleToParentLoader() - throws Exception { - assertNotNull(this.testee.getData(OtherClassLoaderClassPathRootTest.class - .getName())); - assertNotNull(Test.class.getName()); - } - - @Test - public void testReturnsNullForClassesNotVisibleToParentLoader() - throws Exception { - assertNull(this.testee.getData("FooFoo")); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.classpath; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Before; +import org.junit.Test; + +public class OtherClassLoaderClassPathRootTest { + + private OtherClassLoaderClassPathRoot testee; + + @Before + public void setup() { + this.testee = new OtherClassLoaderClassPathRoot(Thread.currentThread() + .getContextClassLoader()); + } + + @Test(expected = UnsupportedOperationException.class) + public void getClassNamesShouldThrowUnsupportedOperation() { + this.testee.classNames(); + } + + @Test + public void shouldReturnsBytesForClassesVisibleToParentLoader() + throws Exception { + assertNotNull(this.testee.getData(OtherClassLoaderClassPathRootTest.class + .getName())); + assertNotNull(Test.class.getName()); + } + + @Test + public void testReturnsNullForClassesNotVisibleToParentLoader() + throws Exception { + assertNull(this.testee.getData("FooFoo")); + } + +} diff --git a/pitest/src/test/java/org/pitest/containers/TestContainersSendCorrectNotifications.java b/pitest/src/test/java/org/pitest/containers/TestContainersSendCorrectNotifications.java index 2b93e049f..216cfbf30 100644 --- a/pitest/src/test/java/org/pitest/containers/TestContainersSendCorrectNotifications.java +++ b/pitest/src/test/java/org/pitest/containers/TestContainersSendCorrectNotifications.java @@ -1,109 +1,109 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.containers; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.simpletest.ConfigurationForTesting; -import org.pitest.simpletest.TestAnnotationForTesting; -import org.pitest.testapi.Description; -import org.pitest.testapi.TestListener; -import org.pitest.testapi.TestResult; -import org.pitest.testapi.execute.Container; -import org.pitest.testapi.execute.Pitest; -import org.pitest.testapi.execute.containers.UnContainer; - -@RunWith(Parameterized.class) -public class TestContainersSendCorrectNotifications { - - private static interface ContainerFactory { - - Container getContainer(); - - } - - private final ContainerFactory containerFactory; - private Pitest pit; - - @Mock - private TestListener listener; - private ConfigurationForTesting config; - - public TestContainersSendCorrectNotifications( - final ContainerFactory containerFactory) { - this.containerFactory = containerFactory; - } - - @Parameters - public static Collection containers() { - return Arrays.asList(new Object[][] { { uncontainerFactory() } }); - - } - - private static Object uncontainerFactory() { - return (ContainerFactory) () -> new UnContainer(); - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.config = new ConfigurationForTesting(); - this.pit = new Pitest(this.listener); - } - - public static class OnePassingTest { - @TestAnnotationForTesting - public void one() { - - } - }; - - public static class OneFailingTest { - @TestAnnotationForTesting - public void one() { - throw new AssertionError(); - } - }; - - @Test - public void shouldSendCorrectNotificationsForSinglePassingTest() { - run(OnePassingTest.class); - verify(this.listener).onTestStart(any(Description.class)); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - @Test - public void shouldSendCorrectNotificationsForSingleFailingTest() { - run(OneFailingTest.class); - verify(this.listener).onTestStart(any(Description.class)); - verify(this.listener).onTestFailure(any(TestResult.class)); - } - - private void run(final Class clazz) { - this.pit.run(this.containerFactory.getContainer(), this.config, clazz); - } - +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.containers; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.simpletest.ConfigurationForTesting; +import org.pitest.simpletest.TestAnnotationForTesting; +import org.pitest.testapi.Description; +import org.pitest.testapi.TestListener; +import org.pitest.testapi.TestResult; +import org.pitest.testapi.execute.Container; +import org.pitest.testapi.execute.Pitest; +import org.pitest.testapi.execute.containers.UnContainer; + +@RunWith(Parameterized.class) +public class TestContainersSendCorrectNotifications { + + private static interface ContainerFactory { + + Container getContainer(); + + } + + private final ContainerFactory containerFactory; + private Pitest pit; + + @Mock + private TestListener listener; + private ConfigurationForTesting config; + + public TestContainersSendCorrectNotifications( + final ContainerFactory containerFactory) { + this.containerFactory = containerFactory; + } + + @Parameters + public static Collection containers() { + return Arrays.asList(new Object[][] { { uncontainerFactory() } }); + + } + + private static Object uncontainerFactory() { + return (ContainerFactory) () -> new UnContainer(); + } + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.config = new ConfigurationForTesting(); + this.pit = new Pitest(this.listener); + } + + public static class OnePassingTest { + @TestAnnotationForTesting + public void one() { + + } + }; + + public static class OneFailingTest { + @TestAnnotationForTesting + public void one() { + throw new AssertionError(); + } + }; + + @Test + public void shouldSendCorrectNotificationsForSinglePassingTest() { + run(OnePassingTest.class); + verify(this.listener).onTestStart(any(Description.class)); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + @Test + public void shouldSendCorrectNotificationsForSingleFailingTest() { + run(OneFailingTest.class); + verify(this.listener).onTestStart(any(Description.class)); + verify(this.listener).onTestFailure(any(TestResult.class)); + } + + private void run(final Class clazz) { + this.pit.run(this.containerFactory.getContainer(), this.config, clazz); + } + } \ No newline at end of file diff --git a/pitest/src/test/java/org/pitest/coverage/BlockLocationTest.java b/pitest/src/test/java/org/pitest/coverage/BlockLocationTest.java index 400129f38..3b2439e35 100644 --- a/pitest/src/test/java/org/pitest/coverage/BlockLocationTest.java +++ b/pitest/src/test/java/org/pitest/coverage/BlockLocationTest.java @@ -1,14 +1,14 @@ -package org.pitest.coverage; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class BlockLocationTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(BlockLocation.class).verify(); - } - -} +package org.pitest.coverage; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class BlockLocationTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(BlockLocation.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/ClassLineTest.java b/pitest/src/test/java/org/pitest/coverage/ClassLineTest.java index bdfa2d08c..b78e7fb0e 100644 --- a/pitest/src/test/java/org/pitest/coverage/ClassLineTest.java +++ b/pitest/src/test/java/org/pitest/coverage/ClassLineTest.java @@ -1,14 +1,14 @@ -package org.pitest.coverage; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class ClassLineTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(ClassLine.class).verify(); - } - -} +package org.pitest.coverage; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class ClassLineTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(ClassLine.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/CoverageResultTest.java b/pitest/src/test/java/org/pitest/coverage/CoverageResultTest.java index 642f61a0b..3bf380abe 100644 --- a/pitest/src/test/java/org/pitest/coverage/CoverageResultTest.java +++ b/pitest/src/test/java/org/pitest/coverage/CoverageResultTest.java @@ -1,45 +1,45 @@ -package org.pitest.coverage; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; - -public class CoverageResultTest { - - private CoverageResult testee; - - @Test - public void shouldCalculateCorrectNumberOfCoveredBlocksWhenNoneCovered() { - this.testee = new CoverageResult(null, 0, true, - Collections. emptyList()); - assertEquals(0, this.testee.getNumberOfCoveredBlocks()); - } - - @Test - public void shouldCalculateCorrectNumberOfCoveredBlocksWhenOneClassHasCoverage() { - this.testee = new CoverageResult(null, 0, true, - Collections.singletonList(makeCoverage("foo", 1))); - assertEquals(1, this.testee.getNumberOfCoveredBlocks()); - } - - @Test - public void shouldCalculateCorrectNumberOfCoveredBlocksWhenMultiplesClassesHaveCoverage() { - this.testee = new CoverageResult(null, 0, true, Arrays.asList( - makeCoverage("foo", 42), makeCoverage("bar", 42))); - assertEquals(2, this.testee.getNumberOfCoveredBlocks()); - } - - private BlockLocation makeCoverage(final String name, final int block) { - final Location l = Location.location(ClassName.fromString(name), - MethodName.fromString("amethod"), "methodDesc"); - final BlockLocation bl = new BlockLocation(l, block); - return bl; - } - -} +package org.pitest.coverage; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; + +public class CoverageResultTest { + + private CoverageResult testee; + + @Test + public void shouldCalculateCorrectNumberOfCoveredBlocksWhenNoneCovered() { + this.testee = new CoverageResult(null, 0, true, + Collections. emptyList()); + assertEquals(0, this.testee.getNumberOfCoveredBlocks()); + } + + @Test + public void shouldCalculateCorrectNumberOfCoveredBlocksWhenOneClassHasCoverage() { + this.testee = new CoverageResult(null, 0, true, + Collections.singletonList(makeCoverage("foo", 1))); + assertEquals(1, this.testee.getNumberOfCoveredBlocks()); + } + + @Test + public void shouldCalculateCorrectNumberOfCoveredBlocksWhenMultiplesClassesHaveCoverage() { + this.testee = new CoverageResult(null, 0, true, Arrays.asList( + makeCoverage("foo", 42), makeCoverage("bar", 42))); + assertEquals(2, this.testee.getNumberOfCoveredBlocks()); + } + + private BlockLocation makeCoverage(final String name, final int block) { + final Location l = Location.location(ClassName.fromString(name), + MethodName.fromString("amethod"), "methodDesc"); + final BlockLocation bl = new BlockLocation(l, block); + return bl; + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/CoverageTransformerTest.java b/pitest/src/test/java/org/pitest/coverage/CoverageTransformerTest.java index 119831335..e17efa6d9 100644 --- a/pitest/src/test/java/org/pitest/coverage/CoverageTransformerTest.java +++ b/pitest/src/test/java/org/pitest/coverage/CoverageTransformerTest.java @@ -1,118 +1,118 @@ -package org.pitest.coverage; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.instrument.IllegalClassFormatException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Vector; -import java.util.concurrent.ConcurrentHashMap; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.util.ASMifier; -import org.objectweb.asm.util.CheckClassAdapter; -import org.objectweb.asm.util.TraceClassVisitor; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.classpath.OtherClassLoaderClassPathRoot; -import org.pitest.functional.predicate.False; -import org.pitest.util.IsolationUtils; -import org.pitest.util.StreamUtil; - -import sun.pitest.CodeCoverageStore; -import sun.pitest.InvokeReceiver; - -public class CoverageTransformerTest { - - private final ClassLoader loader = IsolationUtils - .getContextClassLoader(); - - private final ClassByteArraySource bytes = new ClassloaderByteArraySource( - this.loader); - - @Mock - private InvokeReceiver invokeQueue; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - CodeCoverageStore.init(this.invokeQueue); - } - - @After - public void tearDown() { - CodeCoverageStore.resetAllStaticState(); - } - - @Test - public void shouldNotTransformClassesNotMatchingPredicate() - throws IllegalClassFormatException { - final CoverageTransformer testee = new CoverageTransformer( - False. instance()); - assertNull(testee.transform(null, "anything", null, null, null)); - } - - @Test - public void shouldTransformClasseMatchingPredicate() - throws IllegalClassFormatException { - final CoverageTransformer testee = new CoverageTransformer( - s -> true); - final byte[] bs = this.bytes.getBytes(String.class.getName()).get(); - assertFalse(Arrays.equals(bs, - testee.transform(null, "anything", null, null, bs))); - } - - @Test - public void shouldGenerateValidClasses() throws IllegalClassFormatException { - assertValidClass(String.class); - assertValidClass(Integer.class); - assertValidClass(Vector.class); - assertValidClass(ArrayList.class); - assertValidClass(Collections.class); - assertValidClass(ConcurrentHashMap.class); - assertValidClass(Math.class); - } - - private void assertValidClass(final Class clazz) - throws IllegalClassFormatException { - final byte[] bs = transform(clazz); - // printClass(bs); - final StringWriter sw = new StringWriter(); - CheckClassAdapter.verify(new ClassReader(bs), false, new PrintWriter(sw)); - assertTrue(sw.toString(), sw.toString().length() == 0); - - } - - protected void printRaw(final Class clazz) throws IOException { - final OtherClassLoaderClassPathRoot r = new OtherClassLoaderClassPathRoot( - IsolationUtils.getContextClassLoader()); - printClass(StreamUtil.streamToByteArray(r.getData(clazz.getName()))); - } - - protected void printClass(final byte[] bs) { - final ClassReader reader = new ClassReader(bs); - reader.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter( - System.out)), ClassReader.EXPAND_FRAMES); - } - - private byte[] transform(final Class clazz) - throws IllegalClassFormatException { - final CoverageTransformer testee = new CoverageTransformer( - s -> true); - final byte[] bs = testee.transform(this.loader, clazz.getName(), null, - null, this.bytes.getBytes(clazz.getName()).get()); - return bs; - } - -} +package org.pitest.coverage; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.instrument.IllegalClassFormatException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Vector; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.util.ASMifier; +import org.objectweb.asm.util.CheckClassAdapter; +import org.objectweb.asm.util.TraceClassVisitor; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.classpath.OtherClassLoaderClassPathRoot; +import org.pitest.functional.predicate.False; +import org.pitest.util.IsolationUtils; +import org.pitest.util.StreamUtil; + +import sun.pitest.CodeCoverageStore; +import sun.pitest.InvokeReceiver; + +public class CoverageTransformerTest { + + private final ClassLoader loader = IsolationUtils + .getContextClassLoader(); + + private final ClassByteArraySource bytes = new ClassloaderByteArraySource( + this.loader); + + @Mock + private InvokeReceiver invokeQueue; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + CodeCoverageStore.init(this.invokeQueue); + } + + @After + public void tearDown() { + CodeCoverageStore.resetAllStaticState(); + } + + @Test + public void shouldNotTransformClassesNotMatchingPredicate() + throws IllegalClassFormatException { + final CoverageTransformer testee = new CoverageTransformer( + False. instance()); + assertNull(testee.transform(null, "anything", null, null, null)); + } + + @Test + public void shouldTransformClasseMatchingPredicate() + throws IllegalClassFormatException { + final CoverageTransformer testee = new CoverageTransformer( + s -> true); + final byte[] bs = this.bytes.getBytes(String.class.getName()).get(); + assertFalse(Arrays.equals(bs, + testee.transform(null, "anything", null, null, bs))); + } + + @Test + public void shouldGenerateValidClasses() throws IllegalClassFormatException { + assertValidClass(String.class); + assertValidClass(Integer.class); + assertValidClass(Vector.class); + assertValidClass(ArrayList.class); + assertValidClass(Collections.class); + assertValidClass(ConcurrentHashMap.class); + assertValidClass(Math.class); + } + + private void assertValidClass(final Class clazz) + throws IllegalClassFormatException { + final byte[] bs = transform(clazz); + // printClass(bs); + final StringWriter sw = new StringWriter(); + CheckClassAdapter.verify(new ClassReader(bs), false, new PrintWriter(sw)); + assertTrue(sw.toString(), sw.toString().length() == 0); + + } + + protected void printRaw(final Class clazz) throws IOException { + final OtherClassLoaderClassPathRoot r = new OtherClassLoaderClassPathRoot( + IsolationUtils.getContextClassLoader()); + printClass(StreamUtil.streamToByteArray(r.getData(clazz.getName()))); + } + + protected void printClass(final byte[] bs) { + final ClassReader reader = new ClassReader(bs); + reader.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter( + System.out)), ClassReader.EXPAND_FRAMES); + } + + private byte[] transform(final Class clazz) + throws IllegalClassFormatException { + final CoverageTransformer testee = new CoverageTransformer( + s -> true); + final byte[] bs = testee.transform(this.loader, clazz.getName(), null, + null, this.bytes.getBytes(clazz.getName()).get()); + return bs; + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/TestInfoNameComparatorTest.java b/pitest/src/test/java/org/pitest/coverage/TestInfoNameComparatorTest.java index 67163fe19..2b8834f1d 100644 --- a/pitest/src/test/java/org/pitest/coverage/TestInfoNameComparatorTest.java +++ b/pitest/src/test/java/org/pitest/coverage/TestInfoNameComparatorTest.java @@ -1,36 +1,36 @@ -package org.pitest.coverage; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import java.util.Optional; - -public class TestInfoNameComparatorTest { - - private TestInfoNameComparator testee; - private TestInfo lhs; - private TestInfo rhs; - - @Before - public void setUp() { - this.testee = new TestInfoNameComparator(); - this.lhs = new TestInfo("foo", "0name", 0, Optional. empty(), 0); - this.rhs = new TestInfo("foo", "1name", 0, Optional. empty(), 0); - } - - @Test - public void shouldCompareTestsBasedOnTheirNames() { - assertEquals(-1, this.testee.compare(this.lhs, this.rhs)); - assertEquals(1, this.testee.compare(this.rhs, this.lhs)); - } - - @Test - public void shouldTreatIdenticallyNamesTestsAsEqual() { - final TestInfo sameName = new TestInfo("bar", "0name", 1000, - Optional. empty(), 0); - assertEquals(0, this.testee.compare(this.lhs, sameName)); - } - -} +package org.pitest.coverage; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import java.util.Optional; + +public class TestInfoNameComparatorTest { + + private TestInfoNameComparator testee; + private TestInfo lhs; + private TestInfo rhs; + + @Before + public void setUp() { + this.testee = new TestInfoNameComparator(); + this.lhs = new TestInfo("foo", "0name", 0, Optional. empty(), 0); + this.rhs = new TestInfo("foo", "1name", 0, Optional. empty(), 0); + } + + @Test + public void shouldCompareTestsBasedOnTheirNames() { + assertEquals(-1, this.testee.compare(this.lhs, this.rhs)); + assertEquals(1, this.testee.compare(this.rhs, this.lhs)); + } + + @Test + public void shouldTreatIdenticallyNamesTestsAsEqual() { + final TestInfo sameName = new TestInfo("bar", "0name", 1000, + Optional. empty(), 0); + assertEquals(0, this.testee.compare(this.lhs, sameName)); + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/TestInfoTest.java b/pitest/src/test/java/org/pitest/coverage/TestInfoTest.java index 8789f441c..55a4e8955 100644 --- a/pitest/src/test/java/org/pitest/coverage/TestInfoTest.java +++ b/pitest/src/test/java/org/pitest/coverage/TestInfoTest.java @@ -1,13 +1,13 @@ -package org.pitest.coverage; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class TestInfoTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(TestInfo.class).verify(); - } -} +package org.pitest.coverage; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class TestInfoTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(TestInfo.class).verify(); + } +} diff --git a/pitest/src/test/java/org/pitest/coverage/analysis/BlockTest.java b/pitest/src/test/java/org/pitest/coverage/analysis/BlockTest.java index 8be88aec7..6e671decc 100644 --- a/pitest/src/test/java/org/pitest/coverage/analysis/BlockTest.java +++ b/pitest/src/test/java/org/pitest/coverage/analysis/BlockTest.java @@ -1,14 +1,14 @@ -package org.pitest.coverage.analysis; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class BlockTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(Block.class).verify(); - } - -} +package org.pitest.coverage.analysis; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class BlockTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(Block.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/codeassist/ClassUtils.java b/pitest/src/test/java/org/pitest/coverage/codeassist/ClassUtils.java index 3d9d6806c..80f214e3d 100644 --- a/pitest/src/test/java/org/pitest/coverage/codeassist/ClassUtils.java +++ b/pitest/src/test/java/org/pitest/coverage/codeassist/ClassUtils.java @@ -1,57 +1,57 @@ -package org.pitest.coverage.codeassist; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.lang.instrument.IllegalClassFormatException; -import java.net.URL; - -/** - * User: dima Date: Feb 8, 2009 Time: 4:26:15 PM - */ -public class ClassUtils { - private ClassUtils() { - } - - public static byte[] classAsBytes(final Class clazz) - throws ClassNotFoundException { - return classAsBytes(clazz.getName()); - } - - public static byte[] classAsBytes(final String className) - throws ClassNotFoundException { - - final URL resource = ClassUtils.class.getClassLoader().getResource( - convertClassNameToFileName(className)); - try (BufferedInputStream stream = new BufferedInputStream( - resource.openStream())) { - final byte[] result = new byte[resource.openConnection() - .getContentLength()]; - - int i; - int counter = 0; - while ((i = stream.read()) != -1) { - result[counter] = (byte) i; - counter++; - } - return result; - } catch (final IOException e) { - throw new ClassNotFoundException("", e); - } - } - - private static String convertClassNameToFileName(final String className) { - return className.replace(".", "/") + ".class"; - } - - public static Class createClass(final byte[] bytes) - throws IllegalClassFormatException { - return new MyClassLoader().createClass(bytes); - } - - private static final class MyClassLoader extends ClassLoader { - public Class createClass(final byte[] bytes) - throws IllegalClassFormatException { - return defineClass(null, bytes, 0, bytes.length); - } - } -} +package org.pitest.coverage.codeassist; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.lang.instrument.IllegalClassFormatException; +import java.net.URL; + +/** + * User: dima Date: Feb 8, 2009 Time: 4:26:15 PM + */ +public class ClassUtils { + private ClassUtils() { + } + + public static byte[] classAsBytes(final Class clazz) + throws ClassNotFoundException { + return classAsBytes(clazz.getName()); + } + + public static byte[] classAsBytes(final String className) + throws ClassNotFoundException { + + final URL resource = ClassUtils.class.getClassLoader().getResource( + convertClassNameToFileName(className)); + try (BufferedInputStream stream = new BufferedInputStream( + resource.openStream())) { + final byte[] result = new byte[resource.openConnection() + .getContentLength()]; + + int i; + int counter = 0; + while ((i = stream.read()) != -1) { + result[counter] = (byte) i; + counter++; + } + return result; + } catch (final IOException e) { + throw new ClassNotFoundException("", e); + } + } + + private static String convertClassNameToFileName(final String className) { + return className.replace(".", "/") + ".class"; + } + + public static Class createClass(final byte[] bytes) + throws IllegalClassFormatException { + return new MyClassLoader().createClass(bytes); + } + + private static final class MyClassLoader extends ClassLoader { + public Class createClass(final byte[] bytes) + throws IllegalClassFormatException { + return defineClass(null, bytes, 0, bytes.length); + } + } +} diff --git a/pitest/src/test/java/org/pitest/coverage/codeassist/CoverageClassVisitorTest.java b/pitest/src/test/java/org/pitest/coverage/codeassist/CoverageClassVisitorTest.java index af277dda6..b1c13b47c 100644 --- a/pitest/src/test/java/org/pitest/coverage/codeassist/CoverageClassVisitorTest.java +++ b/pitest/src/test/java/org/pitest/coverage/codeassist/CoverageClassVisitorTest.java @@ -1,50 +1,50 @@ -package org.pitest.coverage.codeassist; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.objectweb.asm.ClassWriter; -import org.pitest.coverage.CoverageClassVisitor; - -import sun.pitest.CodeCoverageStore; -import sun.pitest.InvokeReceiver; - -public class CoverageClassVisitorTest { - - private CoverageClassVisitor testee; - private int classId; - - @Mock - private ClassWriter w; - - @Mock - private InvokeReceiver invokeQueue; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - CodeCoverageStore.init(this.invokeQueue); - CodeCoverageStore.reset(); - this.classId = CodeCoverageStore.registerClass("foo"); - this.testee = new CoverageClassVisitor(this.classId, this.w); - } - - @Test - public void shouldRegisterProbesWithCodeCoverageStore() { - this.testee.registerProbes(6); - this.testee.visitEnd(); - - CodeCoverageStore.visitProbes(this.classId, 0, new boolean[] { false, - false, true, false, false, false, false }); - - assertEquals(Arrays.asList(CodeCoverageStore.encode(this.classId, 2)), - CodeCoverageStore.getHits()); - - } - -} +package org.pitest.coverage.codeassist; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.objectweb.asm.ClassWriter; +import org.pitest.coverage.CoverageClassVisitor; + +import sun.pitest.CodeCoverageStore; +import sun.pitest.InvokeReceiver; + +public class CoverageClassVisitorTest { + + private CoverageClassVisitor testee; + private int classId; + + @Mock + private ClassWriter w; + + @Mock + private InvokeReceiver invokeQueue; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + CodeCoverageStore.init(this.invokeQueue); + CodeCoverageStore.reset(); + this.classId = CodeCoverageStore.registerClass("foo"); + this.testee = new CoverageClassVisitor(this.classId, this.w); + } + + @Test + public void shouldRegisterProbesWithCodeCoverageStore() { + this.testee.registerProbes(6); + this.testee.visitEnd(); + + CodeCoverageStore.visitProbes(this.classId, 0, new boolean[] { false, + false, true, false, false, false, false }); + + assertEquals(Arrays.asList(CodeCoverageStore.encode(this.classId, 2)), + CodeCoverageStore.getHits()); + + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/codeassist/LineMapperTest.java b/pitest/src/test/java/org/pitest/coverage/codeassist/LineMapperTest.java index bfb7b493b..bc7221b5a 100644 --- a/pitest/src/test/java/org/pitest/coverage/codeassist/LineMapperTest.java +++ b/pitest/src/test/java/org/pitest/coverage/codeassist/LineMapperTest.java @@ -1,120 +1,120 @@ -package org.pitest.coverage.codeassist; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - -import java.util.Map; -import java.util.Set; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.CodeSource; -import org.pitest.coverage.BlockLocation; -import org.pitest.coverage.LineMap; -import org.pitest.coverage.analysis.LineMapper; -import java.util.Optional; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; - -import com.example.coverage.execute.samples.simple.LastLineOfContructorCheck; -import com.example.coverage.execute.samples.simple.OneBlock; -import com.example.coverage.execute.samples.simple.ThreeBlocks; -import com.example.coverage.execute.samples.simple.ThreeMultiLineBlocks; - -@RunWith(MockitoJUnitRunner.class) -public class LineMapperTest { - - @Mock - CodeSource source; - - @Test - public void shouldMapAllLinesWhenMethodContainsSingleBlock() throws Exception { - final Map> actual = analyse(OneBlock.class); - - final Location l = Location.location(ClassName.fromClass(OneBlock.class), - MethodName.fromString("foo"), "()I"); - final BlockLocation bl = new BlockLocation(l, 0); - - assertThat(actual.get(bl)).containsOnly(5); - - } - - @Test - public void shouldMapAllLinesWhenMethodContainsThreeBlocks() throws Exception { - final Map> actual = analyse(ThreeBlocks.class); - - final Location l = Location.location(ClassName.fromClass(ThreeBlocks.class), - MethodName.fromString("foo"), "(I)I"); - - assertThat(actual.get(BlockLocation.blockLocation(l, 0))).containsOnly(5); - assertThat(actual.get(BlockLocation.blockLocation(l, 1))).containsOnly(6); - assertThat(actual.get(BlockLocation.blockLocation(l, 2))).containsOnly(8); - } - - @Test - public void shouldMapAllLinesWhenMethodContainsThreeMultiLineBlocks() - throws Exception { - final Map> actual = analyse(ThreeMultiLineBlocks.class); - - final Location l = Location.location( - ClassName.fromClass(ThreeMultiLineBlocks.class), - MethodName.fromString("foo"), "(I)I"); - - assertThat(actual.get(BlockLocation.blockLocation(l, 0))).contains(5, 6); - assertThat(actual.get(BlockLocation.blockLocation(l, 1))).contains(7, 8); - assertThat(actual.get(BlockLocation.blockLocation(l, 2))).contains(10, 11); - } - - @Test - public void shouldMapLinesWhenLinesSpanBlocks() throws Exception { - - final Map> actual = analyse(com.example.LineNumbersSpanBlocks.class); - final Location l = Location.location( - ClassName.fromClass(com.example.LineNumbersSpanBlocks.class), - MethodName.fromString("foo"), "(I)I"); - - assertThat(actual.get(BlockLocation.blockLocation(l, 2))).containsOnly(12); - } - - @Test - public void shouldIncludeLastLinesConstructorsInBlock() throws Exception { - final Map> actual = analyse(LastLineOfContructorCheck.class); - final Location l = Location.location( - ClassName.fromClass(LastLineOfContructorCheck.class), - MethodName.fromString(""), "()V"); - - assertThat(actual.get(BlockLocation.blockLocation(l, 0))).contains(6); - } - - @Test - public void shouldI() throws Exception { - final Map> actual = analyse(ThreeBlocks2.class); - final Location l = Location.location(ClassName.fromClass(ThreeBlocks2.class), - MethodName.fromString("foo"), "(I)I"); - assertThat(actual.get(BlockLocation.blockLocation(l, 0))).containsOnly(105); - assertThat(actual.get(BlockLocation.blockLocation(l, 1))).containsOnly(106); - assertThat(actual.get(BlockLocation.blockLocation(l, 2))).containsOnly(108); - } - - static class ThreeBlocks2 { - int foo(int i) { - if (i > 30) { - return 1; - } - return 2; - } - } - - private Map> analyse(Class clazz) - throws ClassNotFoundException { - when(this.source.fetchClassBytes(any(ClassName.class))).thenReturn( - Optional.ofNullable(ClassUtils.classAsBytes(clazz))); - final LineMap testee = new LineMapper(this.source); - return testee.mapLines(ClassName.fromClass(clazz)); - } - -} +package org.pitest.coverage.codeassist; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +import java.util.Map; +import java.util.Set; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.CodeSource; +import org.pitest.coverage.BlockLocation; +import org.pitest.coverage.LineMap; +import org.pitest.coverage.analysis.LineMapper; +import java.util.Optional; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; + +import com.example.coverage.execute.samples.simple.LastLineOfContructorCheck; +import com.example.coverage.execute.samples.simple.OneBlock; +import com.example.coverage.execute.samples.simple.ThreeBlocks; +import com.example.coverage.execute.samples.simple.ThreeMultiLineBlocks; + +@RunWith(MockitoJUnitRunner.class) +public class LineMapperTest { + + @Mock + CodeSource source; + + @Test + public void shouldMapAllLinesWhenMethodContainsSingleBlock() throws Exception { + final Map> actual = analyse(OneBlock.class); + + final Location l = Location.location(ClassName.fromClass(OneBlock.class), + MethodName.fromString("foo"), "()I"); + final BlockLocation bl = new BlockLocation(l, 0); + + assertThat(actual.get(bl)).containsOnly(5); + + } + + @Test + public void shouldMapAllLinesWhenMethodContainsThreeBlocks() throws Exception { + final Map> actual = analyse(ThreeBlocks.class); + + final Location l = Location.location(ClassName.fromClass(ThreeBlocks.class), + MethodName.fromString("foo"), "(I)I"); + + assertThat(actual.get(BlockLocation.blockLocation(l, 0))).containsOnly(5); + assertThat(actual.get(BlockLocation.blockLocation(l, 1))).containsOnly(6); + assertThat(actual.get(BlockLocation.blockLocation(l, 2))).containsOnly(8); + } + + @Test + public void shouldMapAllLinesWhenMethodContainsThreeMultiLineBlocks() + throws Exception { + final Map> actual = analyse(ThreeMultiLineBlocks.class); + + final Location l = Location.location( + ClassName.fromClass(ThreeMultiLineBlocks.class), + MethodName.fromString("foo"), "(I)I"); + + assertThat(actual.get(BlockLocation.blockLocation(l, 0))).contains(5, 6); + assertThat(actual.get(BlockLocation.blockLocation(l, 1))).contains(7, 8); + assertThat(actual.get(BlockLocation.blockLocation(l, 2))).contains(10, 11); + } + + @Test + public void shouldMapLinesWhenLinesSpanBlocks() throws Exception { + + final Map> actual = analyse(com.example.LineNumbersSpanBlocks.class); + final Location l = Location.location( + ClassName.fromClass(com.example.LineNumbersSpanBlocks.class), + MethodName.fromString("foo"), "(I)I"); + + assertThat(actual.get(BlockLocation.blockLocation(l, 2))).containsOnly(12); + } + + @Test + public void shouldIncludeLastLinesConstructorsInBlock() throws Exception { + final Map> actual = analyse(LastLineOfContructorCheck.class); + final Location l = Location.location( + ClassName.fromClass(LastLineOfContructorCheck.class), + MethodName.fromString(""), "()V"); + + assertThat(actual.get(BlockLocation.blockLocation(l, 0))).contains(6); + } + + @Test + public void shouldI() throws Exception { + final Map> actual = analyse(ThreeBlocks2.class); + final Location l = Location.location(ClassName.fromClass(ThreeBlocks2.class), + MethodName.fromString("foo"), "(I)I"); + assertThat(actual.get(BlockLocation.blockLocation(l, 0))).containsOnly(105); + assertThat(actual.get(BlockLocation.blockLocation(l, 1))).containsOnly(106); + assertThat(actual.get(BlockLocation.blockLocation(l, 2))).containsOnly(108); + } + + static class ThreeBlocks2 { + int foo(int i) { + if (i > 30) { + return 1; + } + return 2; + } + } + + private Map> analyse(Class clazz) + throws ClassNotFoundException { + when(this.source.fetchClassBytes(any(ClassName.class))).thenReturn( + Optional.ofNullable(ClassUtils.classAsBytes(clazz))); + final LineMap testee = new LineMapper(this.source); + return testee.mapLines(ClassName.fromClass(clazz)); + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/Bridge.java b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/Bridge.java index 993ea434a..23d83ae12 100644 --- a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/Bridge.java +++ b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/Bridge.java @@ -1,30 +1,30 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.codeassist.samples; - -public class Bridge { - public static class A { - public T getT() { - return null; - } - } - - public static class HasBridgeMethod extends A { - @Override - public String getT() { - return null; - } - } +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.codeassist.samples; + +public class Bridge { + public static class A { + public T getT() { + return null; + } + } + + public static class HasBridgeMethod extends A { + @Override + public String getT() { + return null; + } + } } \ No newline at end of file diff --git a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/ClassWithAMethod.java b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/ClassWithAMethod.java index 7460baf2f..7d97fbca6 100644 --- a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/ClassWithAMethod.java +++ b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/ClassWithAMethod.java @@ -1,22 +1,22 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.codeassist.samples; - -public class ClassWithAMethod { - - public int aMethod() { - return 1; - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.codeassist.samples; + +public class ClassWithAMethod { + + public int aMethod() { + return 1; + } +} diff --git a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/ClassWithInitialisedField.java b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/ClassWithInitialisedField.java index b17406864..033f437a5 100644 --- a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/ClassWithInitialisedField.java +++ b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/ClassWithInitialisedField.java @@ -1,24 +1,24 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.codeassist.samples; - -import java.util.ArrayList; -import java.util.List; - -public class ClassWithInitialisedField { - - public final List f = new ArrayList<>(); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.codeassist.samples; + +import java.util.ArrayList; +import java.util.List; + +public class ClassWithInitialisedField { + + public final List f = new ArrayList<>(); + +} diff --git a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/HasDefaultConstructor.java b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/HasDefaultConstructor.java index 319f14819..4d506f220 100644 --- a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/HasDefaultConstructor.java +++ b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/HasDefaultConstructor.java @@ -1,19 +1,19 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.codeassist.samples; - -public class HasDefaultConstructor { - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.codeassist.samples; + +public class HasDefaultConstructor { + +} diff --git a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/NoDefaultConstructor.java b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/NoDefaultConstructor.java index de83f94e1..8135670f9 100644 --- a/pitest/src/test/java/org/pitest/coverage/codeassist/samples/NoDefaultConstructor.java +++ b/pitest/src/test/java/org/pitest/coverage/codeassist/samples/NoDefaultConstructor.java @@ -1,28 +1,28 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.coverage.codeassist.samples; - -public class NoDefaultConstructor { - - public NoDefaultConstructor() { - - } - - @Override - public String toString() { - return "hello"; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.codeassist.samples; + +public class NoDefaultConstructor { + + public NoDefaultConstructor() { + + } + + @Override + public String toString() { + return "hello"; + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/execute/CoverageOptionsTest.java b/pitest/src/test/java/org/pitest/coverage/execute/CoverageOptionsTest.java index eb622d3b7..9f18aa205 100644 --- a/pitest/src/test/java/org/pitest/coverage/execute/CoverageOptionsTest.java +++ b/pitest/src/test/java/org/pitest/coverage/execute/CoverageOptionsTest.java @@ -1,61 +1,61 @@ -package org.pitest.coverage.execute; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collections; - -import org.junit.Test; -import org.pitest.mutationtest.config.TestPluginArguments; - -public class CoverageOptionsTest { - - TestPluginArguments pitConfig = TestPluginArguments.defaults(); - - CoverageOptions testee = new CoverageOptions(Collections.singletonList("*"), Collections.emptyList(), this.pitConfig, false, 0); - - @Test - public void shouldIncludeTargettedClasses() { - this.testee = new CoverageOptions(Collections.singletonList("com/example/*"), Collections.emptyList(), this.pitConfig, false, 0); - - assertThat(this.testee.getFilter().test("com/example/Foo")).isTrue(); - } - - @Test - public void shouldExcludeExcludedClasses() { - this.testee = new CoverageOptions(Collections.singletonList("com/example/*"), Collections.singletonList("com/example/NotMe"), this.pitConfig, false, 0); - - assertThat(this.testee.getFilter().test("com/example/Foo")).isTrue(); - assertThat(this.testee.getFilter().test("com/example/NotMe")).isFalse(); - } - - @Test - public void shouldNotCoverJDKClassesWhenFilterIsBroad() { - assertThat(this.testee.getFilter().test("java/lang/Integer")).isFalse(); - } - - @Test - public void shouldNotCoverSunClassesWhenFilterIsBroad() { - assertThat(this.testee.getFilter().test("sun/foo/Bar")).isFalse(); - } - - @Test - public void shouldNotCoverJUnitWhenFilterIsBroad() { - assertThat(this.testee.getFilter().test("sun/foo/Bar")).isFalse(); - } - - @Test - public void shouldNotCoverPitestBootWhenFilterIsBroad() { - assertThat(this.testee.getFilter().test("org/pitest/boot/HotSwapAgent")).isFalse(); - } - - @Test - public void shouldNotCoverPitestCoverageWhenFilterIsBroad() { - assertThat(this.testee.getFilter().test("org/pitest/coverage/execute/Minion")).isFalse(); - } - - @Test - public void shouldNotCoverPitestRelocWhenFilterIsBroad() { - assertThat(this.testee.getFilter().test("org/pitest/reloc/Foo")).isFalse(); - } - -} +package org.pitest.coverage.execute; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; + +import org.junit.Test; +import org.pitest.mutationtest.config.TestPluginArguments; + +public class CoverageOptionsTest { + + TestPluginArguments pitConfig = TestPluginArguments.defaults(); + + CoverageOptions testee = new CoverageOptions(Collections.singletonList("*"), Collections.emptyList(), this.pitConfig, false, 0); + + @Test + public void shouldIncludeTargettedClasses() { + this.testee = new CoverageOptions(Collections.singletonList("com/example/*"), Collections.emptyList(), this.pitConfig, false, 0); + + assertThat(this.testee.getFilter().test("com/example/Foo")).isTrue(); + } + + @Test + public void shouldExcludeExcludedClasses() { + this.testee = new CoverageOptions(Collections.singletonList("com/example/*"), Collections.singletonList("com/example/NotMe"), this.pitConfig, false, 0); + + assertThat(this.testee.getFilter().test("com/example/Foo")).isTrue(); + assertThat(this.testee.getFilter().test("com/example/NotMe")).isFalse(); + } + + @Test + public void shouldNotCoverJDKClassesWhenFilterIsBroad() { + assertThat(this.testee.getFilter().test("java/lang/Integer")).isFalse(); + } + + @Test + public void shouldNotCoverSunClassesWhenFilterIsBroad() { + assertThat(this.testee.getFilter().test("sun/foo/Bar")).isFalse(); + } + + @Test + public void shouldNotCoverJUnitWhenFilterIsBroad() { + assertThat(this.testee.getFilter().test("sun/foo/Bar")).isFalse(); + } + + @Test + public void shouldNotCoverPitestBootWhenFilterIsBroad() { + assertThat(this.testee.getFilter().test("org/pitest/boot/HotSwapAgent")).isFalse(); + } + + @Test + public void shouldNotCoverPitestCoverageWhenFilterIsBroad() { + assertThat(this.testee.getFilter().test("org/pitest/coverage/execute/Minion")).isFalse(); + } + + @Test + public void shouldNotCoverPitestRelocWhenFilterIsBroad() { + assertThat(this.testee.getFilter().test("org/pitest/reloc/Foo")).isFalse(); + } + +} diff --git a/pitest/src/test/java/org/pitest/coverage/execute/DependencyFilterTest.java b/pitest/src/test/java/org/pitest/coverage/execute/DependencyFilterTest.java index 35d69f4bc..6a3b49ee6 100644 --- a/pitest/src/test/java/org/pitest/coverage/execute/DependencyFilterTest.java +++ b/pitest/src/test/java/org/pitest/coverage/execute/DependencyFilterTest.java @@ -1,112 +1,112 @@ -package org.pitest.coverage.execute; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.dependency.DependencyExtractor; -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; -import org.pitest.testapi.TestUnit; - -public class DependencyFilterTest { - - private DependencyFilter testee; - - @Mock - private DependencyExtractor extractor; - - private TestUnit aTestUnit; - - private TestUnit anotherTestUnit; - - private List tus; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - this.aTestUnit = makeTestUnit(new Description("foo", String.class)); - this.anotherTestUnit = makeTestUnit(new Description("bar", Integer.class)); - - this.testee = new DependencyFilter(this.extractor, null); - this.tus = Arrays.asList(this.aTestUnit, this.anotherTestUnit); - } - - @Test - public void shouldNotPerformAnalysisWhenDependencyDistanceIsLessThan0() - throws IOException { - when(this.extractor.getMaxDistance()).thenReturn(-1); - final List actual = this.testee - .filterTestsByDependencyAnalysis(this.tus); - assertSame(this.tus, actual); - verify(this.extractor, never()).extractCallDependenciesForPackages( - anyString(), any(Predicate.class)); - } - - @Test - public void shouldReturnOnlyTestUnitsForClassesWithinReach() - throws IOException { - when( - this.extractor.extractCallDependenciesForPackages(eq(this.aTestUnit - .getDescription().getFirstTestClass()), any(Predicate.class))) - .thenReturn(Arrays.asList("foo")); - when( - this.extractor.extractCallDependenciesForPackages( - eq(this.anotherTestUnit.getDescription().getFirstTestClass()), - any(Predicate.class))).thenReturn(Collections. emptyList()); - - assertEquals(Arrays.asList(this.aTestUnit), - this.testee.filterTestsByDependencyAnalysis(this.tus)); - - } - - @Test - public void shouldNotRecalculateDependenciesForAlreadyAnalysedClasses() - throws IOException { - - when( - this.extractor.extractCallDependenciesForPackages(eq(this.aTestUnit - .getDescription().getFirstTestClass()), any(Predicate.class))) - .thenReturn(Arrays.asList("foo")); - - this.tus = Arrays.asList(this.aTestUnit, this.aTestUnit); - - this.testee.filterTestsByDependencyAnalysis(this.tus); - verify(this.extractor, times(1)).extractCallDependenciesForPackages( - eq(this.aTestUnit.getDescription().getFirstTestClass()), - any(Predicate.class)); - } - - private TestUnit makeTestUnit(final Description d) { - return new TestUnit() { - - @Override - public void execute(final ResultCollector rc) { - - } - - @Override - public Description getDescription() { - return d; - } - - }; - } -} +package org.pitest.coverage.execute; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.dependency.DependencyExtractor; +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; +import org.pitest.testapi.TestUnit; + +public class DependencyFilterTest { + + private DependencyFilter testee; + + @Mock + private DependencyExtractor extractor; + + private TestUnit aTestUnit; + + private TestUnit anotherTestUnit; + + private List tus; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + this.aTestUnit = makeTestUnit(new Description("foo", String.class)); + this.anotherTestUnit = makeTestUnit(new Description("bar", Integer.class)); + + this.testee = new DependencyFilter(this.extractor, null); + this.tus = Arrays.asList(this.aTestUnit, this.anotherTestUnit); + } + + @Test + public void shouldNotPerformAnalysisWhenDependencyDistanceIsLessThan0() + throws IOException { + when(this.extractor.getMaxDistance()).thenReturn(-1); + final List actual = this.testee + .filterTestsByDependencyAnalysis(this.tus); + assertSame(this.tus, actual); + verify(this.extractor, never()).extractCallDependenciesForPackages( + anyString(), any(Predicate.class)); + } + + @Test + public void shouldReturnOnlyTestUnitsForClassesWithinReach() + throws IOException { + when( + this.extractor.extractCallDependenciesForPackages(eq(this.aTestUnit + .getDescription().getFirstTestClass()), any(Predicate.class))) + .thenReturn(Arrays.asList("foo")); + when( + this.extractor.extractCallDependenciesForPackages( + eq(this.anotherTestUnit.getDescription().getFirstTestClass()), + any(Predicate.class))).thenReturn(Collections. emptyList()); + + assertEquals(Arrays.asList(this.aTestUnit), + this.testee.filterTestsByDependencyAnalysis(this.tus)); + + } + + @Test + public void shouldNotRecalculateDependenciesForAlreadyAnalysedClasses() + throws IOException { + + when( + this.extractor.extractCallDependenciesForPackages(eq(this.aTestUnit + .getDescription().getFirstTestClass()), any(Predicate.class))) + .thenReturn(Arrays.asList("foo")); + + this.tus = Arrays.asList(this.aTestUnit, this.aTestUnit); + + this.testee.filterTestsByDependencyAnalysis(this.tus); + verify(this.extractor, times(1)).extractCallDependenciesForPackages( + eq(this.aTestUnit.getDescription().getFirstTestClass()), + any(Predicate.class)); + } + + private TestUnit makeTestUnit(final Description d) { + return new TestUnit() { + + @Override + public void execute(final ResultCollector rc) { + + } + + @Override + public Description getDescription() { + return d; + } + + }; + } +} diff --git a/pitest/src/test/java/org/pitest/dependency/DependencyAccessTest.java b/pitest/src/test/java/org/pitest/dependency/DependencyAccessTest.java index 42048fddb..d93de94ac 100644 --- a/pitest/src/test/java/org/pitest/dependency/DependencyAccessTest.java +++ b/pitest/src/test/java/org/pitest/dependency/DependencyAccessTest.java @@ -1,14 +1,14 @@ -package org.pitest.dependency; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class DependencyAccessTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(DependencyAccess.class).verify(); - } - -} +package org.pitest.dependency; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class DependencyAccessTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(DependencyAccess.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/dependency/DependencyClassVisitorTest.java b/pitest/src/test/java/org/pitest/dependency/DependencyClassVisitorTest.java index d8630fb33..2e7e8a542 100644 --- a/pitest/src/test/java/org/pitest/dependency/DependencyClassVisitorTest.java +++ b/pitest/src/test/java/org/pitest/dependency/DependencyClassVisitorTest.java @@ -1,113 +1,113 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.dependency; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Function; - -import org.junit.Before; -import org.junit.Test; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.pitest.classpath.ClassPath; -import org.pitest.dependency.DependencyAccess.Member; -import org.pitest.functional.FCollection; -import org.pitest.functional.SideEffect1; - -public class DependencyClassVisitorTest { - - private DependencyClassVisitor testee; - private final Set gatheredDependencies = new HashSet<>(); - private final Set gatheredAccess = new HashSet<>(); - private final ClassPath cp = new ClassPath(); - - @Before - public void setUp() { - final SideEffect1 se = a -> { - DependencyClassVisitorTest.this.gatheredAccess.add(a); - DependencyClassVisitorTest.this.gatheredDependencies.add(a.getDest() - .getOwner()); - }; - this.testee = new DependencyClassVisitor(new ClassWriter(0), se); - } - - public static class HasDependencyFromCallingNew { - public void foo() { - new Integer(1); - } - } - - @Test - public void shouldRecordDirectDependenciesFromCallingNew() throws Exception { - examineClassWithTestee(HasDependencyFromCallingNew.class); - assertEquals(classesToNames(Integer.class), this.gatheredDependencies); - } - - public enum AnEnum { - value - } - - public static class HasField { - AnEnum field = AnEnum.value; - - } - - @Test - public void shouldRecordDependenciesFromInitializedFields() throws Exception { - examineClassWithTestee(HasField.class); - assertEquals(classesToNames(AnEnum.class, HasField.class), - this.gatheredDependencies); - - } - - public static class MakesMethodCall { - public void foo() { - Arrays.asList(); - } - } - - @Test - public void shouldRecordDependenciesFromMethodCalls() throws Exception { - examineClassWithTestee(MakesMethodCall.class); - assertEquals(classesToNames(Arrays.class), this.gatheredDependencies); - final Member foo = new Member( - classToJvmName().apply(MakesMethodCall.class), "foo"); - assertTrue(this.gatheredAccess.contains(new DependencyAccess(foo, - new Member("java/util/Arrays", "asList")))); - } - - private void examineClassWithTestee(final Class clazz) throws IOException { - final byte[] bytes = this.cp.getClassData(clazz.getName()); - final ClassReader reader = new ClassReader(bytes); - reader.accept(this.testee, 0); - } - - private Set classesToNames(final Class... classes) { - final Set set = new HashSet<>(); - FCollection.mapTo(Arrays.asList(classes), classToJvmName(), set); - return set; - } - - private Function, String> classToJvmName() { - return a -> a.getName().replace(".", "/"); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.dependency; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Function; + +import org.junit.Before; +import org.junit.Test; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.pitest.classpath.ClassPath; +import org.pitest.dependency.DependencyAccess.Member; +import org.pitest.functional.FCollection; +import org.pitest.functional.SideEffect1; + +public class DependencyClassVisitorTest { + + private DependencyClassVisitor testee; + private final Set gatheredDependencies = new HashSet<>(); + private final Set gatheredAccess = new HashSet<>(); + private final ClassPath cp = new ClassPath(); + + @Before + public void setUp() { + final SideEffect1 se = a -> { + DependencyClassVisitorTest.this.gatheredAccess.add(a); + DependencyClassVisitorTest.this.gatheredDependencies.add(a.getDest() + .getOwner()); + }; + this.testee = new DependencyClassVisitor(new ClassWriter(0), se); + } + + public static class HasDependencyFromCallingNew { + public void foo() { + new Integer(1); + } + } + + @Test + public void shouldRecordDirectDependenciesFromCallingNew() throws Exception { + examineClassWithTestee(HasDependencyFromCallingNew.class); + assertEquals(classesToNames(Integer.class), this.gatheredDependencies); + } + + public enum AnEnum { + value + } + + public static class HasField { + AnEnum field = AnEnum.value; + + } + + @Test + public void shouldRecordDependenciesFromInitializedFields() throws Exception { + examineClassWithTestee(HasField.class); + assertEquals(classesToNames(AnEnum.class, HasField.class), + this.gatheredDependencies); + + } + + public static class MakesMethodCall { + public void foo() { + Arrays.asList(); + } + } + + @Test + public void shouldRecordDependenciesFromMethodCalls() throws Exception { + examineClassWithTestee(MakesMethodCall.class); + assertEquals(classesToNames(Arrays.class), this.gatheredDependencies); + final Member foo = new Member( + classToJvmName().apply(MakesMethodCall.class), "foo"); + assertTrue(this.gatheredAccess.contains(new DependencyAccess(foo, + new Member("java/util/Arrays", "asList")))); + } + + private void examineClassWithTestee(final Class clazz) throws IOException { + final byte[] bytes = this.cp.getClassData(clazz.getName()); + final ClassReader reader = new ClassReader(bytes); + reader.accept(this.testee, 0); + } + + private Set classesToNames(final Class... classes) { + final Set set = new HashSet<>(); + FCollection.mapTo(Arrays.asList(classes), classToJvmName(), set); + return set; + } + + private Function, String> classToJvmName() { + return a -> a.getName().replace(".", "/"); + } + +} diff --git a/pitest/src/test/java/org/pitest/dependency/DependencyExtractorTest.java b/pitest/src/test/java/org/pitest/dependency/DependencyExtractorTest.java index 69821a028..bc144c53e 100644 --- a/pitest/src/test/java/org/pitest/dependency/DependencyExtractorTest.java +++ b/pitest/src/test/java/org/pitest/dependency/DependencyExtractorTest.java @@ -1,176 +1,176 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.dependency; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -import org.junit.Test; -import org.pitest.classpath.ClassPathByteArraySource; - -public class DependencyExtractorTest { - - private DependencyExtractor testee; - - public static class Foo { - public void one() { - new Bar(); - } - - public void two() { - new Car(); - } - } - - public static class Bar { - Far f = new Far(); - } - - public static class Car { - - } - - public static class Far { - VeryFar f = new VeryFar(); - } - - public static class VeryFar { - - } - - public static class CyclicFoo { - CyclicBar b = new CyclicBar(); - } - - public static class CyclicBar { - CyclicFoo f = new CyclicFoo(); - } - - @Test - public void shouldFindOnlyImmediateDependenciesWhenDepthIsOne() - throws Exception { - constructWithDepthOf(1); - final Collection actual = this.testee - .extractCallDependenciesForPackages(Foo.class.getName(), - s -> true); - final Set expected = asSet(classToJvmName(Bar.class), - classToJvmName(Car.class)); - assertCollectionEquals(expected, actual); - } - - @Test - public void shouldTraverseTwoLevelsOfDependenciesWhenDepthIsTwo() - throws Exception { - constructWithDepthOf(2); - final Collection actual = this.testee - .extractCallDependenciesForPackages(Foo.class.getName(), - s -> true); - final Set expected = asSet(classToJvmName(Bar.class), - classToJvmName(Car.class), classToJvmName(Far.class)); - assertCollectionEquals(expected, actual); - } - - @Test - public void shouldTraverseUnboundedWhenDepthIsZero() throws Exception { - constructWithDepthOf(0); - final Collection actual = this.testee - .extractCallDependenciesForPackages(Foo.class.getName(), - s -> true); - final List expected = Arrays.asList(classToJvmName(Bar.class), - classToJvmName(Car.class), classToJvmName(Far.class), - classToJvmName(VeryFar.class)); - assertCollectionEquals(expected, actual); - } - - @Test - public void shouldNotPickUpDependenciesFromFilteredMethods() throws Exception { - constructWithDepthOf(0); - final Collection actual = this.testee.extractCallDependencies( - Foo.class.getName(), excludeMethodsCalledOne()); - final Set expected = asSet(classToJvmName(Car.class)); - assertCollectionEquals(expected, actual); - } - - @Test - public void shouldFindDependenciesReachedViaClassesNotMatchingFilter() - throws IOException { - constructWithDepthOf(5); - final Collection actual = this.testee - .extractCallDependenciesForPackages(Foo.class.getName(), - includeOnlyThingsCalled("VeryFar"), ignoreCoreClasses()); - final Set expected = asSet(classToJvmName(VeryFar.class)); - assertCollectionEquals(expected, actual); - } - - @Test - public void shouldHandleCyclicDependencies() throws Exception { - constructWithDepthOf(0); - final Collection actual = this.testee - .extractCallDependenciesForPackages(CyclicFoo.class.getName(), - s -> true); - final List expected = Arrays - .asList(classToJvmName(CyclicBar.class)); - assertCollectionEquals(expected, actual); - } - - private Predicate ignoreCoreClasses() { - return a -> !a.getDest().getOwner().startsWith("java"); - - } - - private Predicate includeOnlyThingsCalled(final String subString) { - return a -> a.contains(subString); - } - - private void constructWithDepthOf(final int depth) { - this.testee = new DependencyExtractor(new ClassPathByteArraySource(), depth); - - } - - private Predicate excludeMethodsCalledOne() { - return a -> !a.getSource().getName().equals("one"); - } - - private void assertCollectionEquals(final Collection expected, - final Collection actual) { - final Set expectedSet = new HashSet<>(); - expectedSet.addAll(expected); - - final Set actualSet = new HashSet<>(); - actualSet.addAll(actual); - - assertEquals(expectedSet, actualSet); - - } - - private Set asSet(final String... values) { - final Set set = new HashSet<>(); - set.addAll(Arrays.asList(values)); - return set; - } - - private String classToJvmName(final Class clazz) { - - return clazz.getName().replace(".", "/"); - - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.dependency; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +import org.junit.Test; +import org.pitest.classpath.ClassPathByteArraySource; + +public class DependencyExtractorTest { + + private DependencyExtractor testee; + + public static class Foo { + public void one() { + new Bar(); + } + + public void two() { + new Car(); + } + } + + public static class Bar { + Far f = new Far(); + } + + public static class Car { + + } + + public static class Far { + VeryFar f = new VeryFar(); + } + + public static class VeryFar { + + } + + public static class CyclicFoo { + CyclicBar b = new CyclicBar(); + } + + public static class CyclicBar { + CyclicFoo f = new CyclicFoo(); + } + + @Test + public void shouldFindOnlyImmediateDependenciesWhenDepthIsOne() + throws Exception { + constructWithDepthOf(1); + final Collection actual = this.testee + .extractCallDependenciesForPackages(Foo.class.getName(), + s -> true); + final Set expected = asSet(classToJvmName(Bar.class), + classToJvmName(Car.class)); + assertCollectionEquals(expected, actual); + } + + @Test + public void shouldTraverseTwoLevelsOfDependenciesWhenDepthIsTwo() + throws Exception { + constructWithDepthOf(2); + final Collection actual = this.testee + .extractCallDependenciesForPackages(Foo.class.getName(), + s -> true); + final Set expected = asSet(classToJvmName(Bar.class), + classToJvmName(Car.class), classToJvmName(Far.class)); + assertCollectionEquals(expected, actual); + } + + @Test + public void shouldTraverseUnboundedWhenDepthIsZero() throws Exception { + constructWithDepthOf(0); + final Collection actual = this.testee + .extractCallDependenciesForPackages(Foo.class.getName(), + s -> true); + final List expected = Arrays.asList(classToJvmName(Bar.class), + classToJvmName(Car.class), classToJvmName(Far.class), + classToJvmName(VeryFar.class)); + assertCollectionEquals(expected, actual); + } + + @Test + public void shouldNotPickUpDependenciesFromFilteredMethods() throws Exception { + constructWithDepthOf(0); + final Collection actual = this.testee.extractCallDependencies( + Foo.class.getName(), excludeMethodsCalledOne()); + final Set expected = asSet(classToJvmName(Car.class)); + assertCollectionEquals(expected, actual); + } + + @Test + public void shouldFindDependenciesReachedViaClassesNotMatchingFilter() + throws IOException { + constructWithDepthOf(5); + final Collection actual = this.testee + .extractCallDependenciesForPackages(Foo.class.getName(), + includeOnlyThingsCalled("VeryFar"), ignoreCoreClasses()); + final Set expected = asSet(classToJvmName(VeryFar.class)); + assertCollectionEquals(expected, actual); + } + + @Test + public void shouldHandleCyclicDependencies() throws Exception { + constructWithDepthOf(0); + final Collection actual = this.testee + .extractCallDependenciesForPackages(CyclicFoo.class.getName(), + s -> true); + final List expected = Arrays + .asList(classToJvmName(CyclicBar.class)); + assertCollectionEquals(expected, actual); + } + + private Predicate ignoreCoreClasses() { + return a -> !a.getDest().getOwner().startsWith("java"); + + } + + private Predicate includeOnlyThingsCalled(final String subString) { + return a -> a.contains(subString); + } + + private void constructWithDepthOf(final int depth) { + this.testee = new DependencyExtractor(new ClassPathByteArraySource(), depth); + + } + + private Predicate excludeMethodsCalledOne() { + return a -> !a.getSource().getName().equals("one"); + } + + private void assertCollectionEquals(final Collection expected, + final Collection actual) { + final Set expectedSet = new HashSet<>(); + expectedSet.addAll(expected); + + final Set actualSet = new HashSet<>(); + actualSet.addAll(actual); + + assertEquals(expectedSet, actualSet); + + } + + private Set asSet(final String... values) { + final Set set = new HashSet<>(); + set.addAll(Arrays.asList(values)); + return set; + } + + private String classToJvmName(final Class clazz) { + + return clazz.getName().replace(".", "/"); + + } +} diff --git a/pitest/src/test/java/org/pitest/dependency/IgnoreCoreClassesTest.java b/pitest/src/test/java/org/pitest/dependency/IgnoreCoreClassesTest.java index 19043f3f1..854d97598 100644 --- a/pitest/src/test/java/org/pitest/dependency/IgnoreCoreClassesTest.java +++ b/pitest/src/test/java/org/pitest/dependency/IgnoreCoreClassesTest.java @@ -1,91 +1,91 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.dependency; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import javax.net.SocketFactory; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; -import org.pitest.dependency.DependencyAccess.Member; -import org.pitest.dependency.DependencyExtractorTest.Foo; - -public class IgnoreCoreClassesTest { - - private IgnoreCoreClasses testee; - - @Before - public void setUp() { - this.testee = new IgnoreCoreClasses(); - } - - @Test - public void shouldIgnoreJavaLangClasses() { - assertIgnored(Integer.class); - } - - @SuppressWarnings("deprecation") - @Test - public void shouldIgnoreLegacyJUnitClasses() { - assertIgnored(junit.framework.Assert.class); - } - - @Test - public void shouldIgnoreJUnitClasses() { - assertIgnored(JUnit4.class); - } - - @Test - public void shouldIgnoreMockito() { - assertIgnored(Mockito.class); - } - - @Test - public void shouldIgnorePowerMock() { - assertIgnored("org.powermock.PowerMockIgnore"); - } - - private void assertIgnored(final String clazz) { - assertFalse(this.testee.test(makeAccessFor(clazz))); - } - - private void assertIgnored(final Class clazz) { - assertIgnored(clazz.getName()); - } - - @Test - public void shouldIgnoreJavaX() { - assertFalse(this.testee.test(makeAccessFor(SocketFactory.class))); - } - - @Test - public void shouldNotIgnoreOtherPackages() { - assertTrue(this.testee.test(makeAccessFor(Foo.class))); - } - - private DependencyAccess makeAccessFor(final Class clazz) { - return makeAccessFor(clazz.getName()); - } - - private DependencyAccess makeAccessFor(final String clazz) { - return new DependencyAccess(new Member("foo", "()V"), new Member(clazz, - "()V")); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.dependency; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import javax.net.SocketFactory; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runners.JUnit4; +import org.mockito.Mockito; +import org.pitest.dependency.DependencyAccess.Member; +import org.pitest.dependency.DependencyExtractorTest.Foo; + +public class IgnoreCoreClassesTest { + + private IgnoreCoreClasses testee; + + @Before + public void setUp() { + this.testee = new IgnoreCoreClasses(); + } + + @Test + public void shouldIgnoreJavaLangClasses() { + assertIgnored(Integer.class); + } + + @SuppressWarnings("deprecation") + @Test + public void shouldIgnoreLegacyJUnitClasses() { + assertIgnored(junit.framework.Assert.class); + } + + @Test + public void shouldIgnoreJUnitClasses() { + assertIgnored(JUnit4.class); + } + + @Test + public void shouldIgnoreMockito() { + assertIgnored(Mockito.class); + } + + @Test + public void shouldIgnorePowerMock() { + assertIgnored("org.powermock.PowerMockIgnore"); + } + + private void assertIgnored(final String clazz) { + assertFalse(this.testee.test(makeAccessFor(clazz))); + } + + private void assertIgnored(final Class clazz) { + assertIgnored(clazz.getName()); + } + + @Test + public void shouldIgnoreJavaX() { + assertFalse(this.testee.test(makeAccessFor(SocketFactory.class))); + } + + @Test + public void shouldNotIgnoreOtherPackages() { + assertTrue(this.testee.test(makeAccessFor(Foo.class))); + } + + private DependencyAccess makeAccessFor(final Class clazz) { + return makeAccessFor(clazz.getName()); + } + + private DependencyAccess makeAccessFor(final String clazz) { + return new DependencyAccess(new Member("foo", "()V"), new Member(clazz, + "()V")); + } + +} diff --git a/pitest/src/test/java/org/pitest/functional/FArrayTest.java b/pitest/src/test/java/org/pitest/functional/FArrayTest.java index 72280463c..c40f945b8 100644 --- a/pitest/src/test/java/org/pitest/functional/FArrayTest.java +++ b/pitest/src/test/java/org/pitest/functional/FArrayTest.java @@ -1,96 +1,96 @@ -/** - * - */ -package org.pitest.functional; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.junit.Test; -import org.pitest.functional.predicate.False; -import org.pitest.util.PitError; - -/** - * @author henry - * - */ -public class FArrayTest { - - final Integer[] is = { 1, 2, 3, 4, 5 }; - - @Test - public void shouldReturnAllEntriesWhenFilteredOnTrue() { - final List expected = Arrays.asList(this.is); - assertEquals(expected, FArray.filter(this.is, i -> true)); - } - - @Test - public void shouldReturnEmptyListWhenFilteredOnFalse() { - final List expected = Collections.emptyList(); - assertEquals(expected, FArray.filter(this.is, False.instance())); - } - - @Test - public void shouldReturnOnlyMatchesToPredicate() { - final Predicate p = a -> a <= 2; - final List expected = Arrays.asList(1, 2); - assertEquals(expected, FArray.filter(this.is, p)); - } - - @Test - public void shouldReturnEmptyListWhenGivenNull() { - assertEquals(Collections.emptyList(), FArray.filter(null, i -> true)); - } - - @Test - public void shouldApplyFlatMapToAllItems() { - final Function> f = a -> Arrays.asList(a, a); - final Collection expected = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, - 5, 5); - assertEquals(expected, FArray.flatMap(this.is, f)); - } - - @Test - public void flatMapShouldTreatNullAsEmptyIterable() { - assertEquals(Collections.emptyList(), - FArray.flatMap(null, objectToObjectIterable())); - } - - private Function> objectToObjectIterable() { - return a -> Collections.emptyList(); - } - - @Test - public void containsShouldReturnFalseWhenPredicateNotMet() { - final Integer[] xs = { 1, 2, 3 }; - assertFalse(FArray.contains(xs, False.instance())); - } - - @Test - public void containsShouldReturnTrueWhenPredicateMet() { - final Integer[] xs = { 1, 2, 3 }; - assertTrue(FArray.contains(xs, i -> true)); - } - - @Test - public void containsShouldStopProcessingOnFirstMatch() { - final Integer[] xs = { 1, 2, 3 }; - final Predicate predicate = a -> { - if (a == 2) { - throw new PitError("Did not shortcut"); - } - return a == 1; - }; - FArray.contains(xs, predicate); - // pass - } - -} +/** + * + */ +package org.pitest.functional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.junit.Test; +import org.pitest.functional.predicate.False; +import org.pitest.util.PitError; + +/** + * @author henry + * + */ +public class FArrayTest { + + final Integer[] is = { 1, 2, 3, 4, 5 }; + + @Test + public void shouldReturnAllEntriesWhenFilteredOnTrue() { + final List expected = Arrays.asList(this.is); + assertEquals(expected, FArray.filter(this.is, i -> true)); + } + + @Test + public void shouldReturnEmptyListWhenFilteredOnFalse() { + final List expected = Collections.emptyList(); + assertEquals(expected, FArray.filter(this.is, False.instance())); + } + + @Test + public void shouldReturnOnlyMatchesToPredicate() { + final Predicate p = a -> a <= 2; + final List expected = Arrays.asList(1, 2); + assertEquals(expected, FArray.filter(this.is, p)); + } + + @Test + public void shouldReturnEmptyListWhenGivenNull() { + assertEquals(Collections.emptyList(), FArray.filter(null, i -> true)); + } + + @Test + public void shouldApplyFlatMapToAllItems() { + final Function> f = a -> Arrays.asList(a, a); + final Collection expected = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, + 5, 5); + assertEquals(expected, FArray.flatMap(this.is, f)); + } + + @Test + public void flatMapShouldTreatNullAsEmptyIterable() { + assertEquals(Collections.emptyList(), + FArray.flatMap(null, objectToObjectIterable())); + } + + private Function> objectToObjectIterable() { + return a -> Collections.emptyList(); + } + + @Test + public void containsShouldReturnFalseWhenPredicateNotMet() { + final Integer[] xs = { 1, 2, 3 }; + assertFalse(FArray.contains(xs, False.instance())); + } + + @Test + public void containsShouldReturnTrueWhenPredicateMet() { + final Integer[] xs = { 1, 2, 3 }; + assertTrue(FArray.contains(xs, i -> true)); + } + + @Test + public void containsShouldStopProcessingOnFirstMatch() { + final Integer[] xs = { 1, 2, 3 }; + final Predicate predicate = a -> { + if (a == 2) { + throw new PitError("Did not shortcut"); + } + return a == 1; + }; + FArray.contains(xs, predicate); + // pass + } + +} diff --git a/pitest/src/test/java/org/pitest/functional/FCollectionTest.java b/pitest/src/test/java/org/pitest/functional/FCollectionTest.java index 400c3e373..79df34d33 100644 --- a/pitest/src/test/java/org/pitest/functional/FCollectionTest.java +++ b/pitest/src/test/java/org/pitest/functional/FCollectionTest.java @@ -1,195 +1,195 @@ -/** - * - */ -package org.pitest.functional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.functional.predicate.False; -import org.pitest.functional.prelude.Prelude; -import org.pitest.util.PitError; - -/** - * @author henry - * - */ -public class FCollectionTest { - - private List is; - - @Before - public void setUp() { - this.is = Arrays.asList(1, 2, 3, 4, 5); - } - - @Test - public void shouldReturnsAllEntriesWhenFilteredOnTrue() { - final List expected = this.is; - assertEquals(expected, FCollection.filter(this.is, i -> true)); - } - - @Test - public void shouldReturnEmptyListWhenFilteredOnFalse() { - final List expected = Collections.emptyList(); - assertEquals(expected, FCollection.filter(this.is, False.instance())); - } - - @Test - public void shouldReturnOnlyMatchesToPredicate() { - final Predicate p = a -> a <= 2; - final List expected = Arrays.asList(1, 2); - assertEquals(expected, FCollection.filter(this.is, p)); - } - - @Test - public void shouldApplyForEachToAllItems() { - final List actual = new ArrayList<>(); - final SideEffect1 e = a -> actual.add(a); - - FCollection.forEach(this.is, e); - - assertEquals(this.is, actual); - } - - @Test - public void shouldApplyMapToAllItems() { - assertEquals(this.is, FCollection.map(this.is, Prelude.id())); - } - - @Test - public void mapShouldTreatNullAsAnEmptyIterable() { - assertEquals(Collections.emptyList(), FCollection.map(null, Prelude.id())); - } - - @Test - public void shouldApplyFlatMapToAllItems() { - final Function> f = a -> Arrays.asList(a, a); - final Collection expected = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, - 5, 5); - assertEquals(expected, FCollection.flatMap(this.is, f)); - } - - @Test - public void flatMapShouldTreatNullAsEmptyIterable() { - assertEquals(Collections.emptyList(), - FCollection.flatMap(null, objectToObjectIterable())); - } - - private Function> objectToObjectIterable() { - return a -> Collections.emptyList(); - } - - @Test - public void containsShouldReturnFalseWhenPredicateNotMet() { - final Collection xs = Arrays.asList(1, 2, 3); - assertFalse(FCollection.contains(xs, False.instance())); - } - - @Test - public void containsShouldReturnTrueWhenPredicateMet() { - final Collection xs = Arrays.asList(1, 2, 3); - assertTrue(FCollection.contains(xs, i -> true)); - } - - @Test - public void containsShouldStopProcessingOnFirstMatch() { - final Collection xs = Arrays.asList(1, 2, 3); - final Predicate predicate = a -> { - if (a == 2) { - throw new PitError("Did not shortcut"); - } - return a == 1; - }; - FCollection.contains(xs, predicate); - // pass - } - - @Test - public void foldShouldFoldValues() { - final Collection xs = Arrays.asList(1, 2, 3); - final BiFunction f = (a, b) -> a + b; - - final int actual = FCollection.fold(f, 2, xs); - assertEquals(8, actual); - } - - @Test - public void flattenShouldReturnCollectionContainingAllSuppliedValues() { - final Collection> is = new ArrayList<>(); - is.add(Arrays.asList(1, 2, 3, 4, 5)); - is.add(Arrays.asList(6, 7, 8, 9)); - assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9), - FCollection.flatten(is)); - - } - - @Test - public void shouldSplitCollectionIntoOneBucketWhenListSizeEqualToBucketSize() { - this.is = Arrays.asList(1, 2, 3); - final List> actual = FCollection.splitToLength(3, this.is); - assertEquals(1, actual.size()); - assertThat(actual.get(0)).contains(1, 2, 3); - } - - @Test - public void shouldSplitCollectionIntoTwoBucketsWhenListSizeOneGreaterThanBucketSize() { - this.is = Arrays.asList(1, 2, 3); - final List> actual = FCollection.splitToLength(2, this.is); - assertEquals(2, actual.size()); - assertThat(actual.get(0)).contains(1, 2); - assertThat(actual.get(1)).contains(3); - } - - @Test - public void shouldSplitCollectionIntoManyBucketsWhenListManyTimesGreaterThanBucketSize() { - this.is = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - final List> actual = FCollection.splitToLength(2, this.is); - assertEquals(6, actual.size()); - assertThat(actual.get(0)).contains(1, 2); - assertThat(actual.get(1)).contains(3, 4); - assertThat(actual.get(5)).contains(11); - } - - @Test - public void shouldSplitIntoSingleBucketWhenAllItemsMeetsCriteria() { - this.is = Arrays.asList(1, 2, 3); - final Map> actual = FCollection.bucket( - this.is, fortyTwo()); - final Map> expected = new HashMap<>(); - expected.put(42, Arrays.asList(1, 2, 3)); - assertEquals(expected, actual); - } - - @Test - public void shouldSplitIntoMultipleBuckets() { - this.is = Arrays.asList(1, 2, 3); - final Map> actual = FCollection.bucket( - this.is, Prelude.id(Integer.class)); - final Map> expected = new HashMap<>(); - expected.put(1, Arrays.asList(1)); - expected.put(2, Arrays.asList(2)); - expected.put(3, Arrays.asList(3)); - assertEquals(expected, actual); - } - - private Function fortyTwo() { - return a -> 42; - } - -} +/** + * + */ +package org.pitest.functional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.functional.predicate.False; +import org.pitest.functional.prelude.Prelude; +import org.pitest.util.PitError; + +/** + * @author henry + * + */ +public class FCollectionTest { + + private List is; + + @Before + public void setUp() { + this.is = Arrays.asList(1, 2, 3, 4, 5); + } + + @Test + public void shouldReturnsAllEntriesWhenFilteredOnTrue() { + final List expected = this.is; + assertEquals(expected, FCollection.filter(this.is, i -> true)); + } + + @Test + public void shouldReturnEmptyListWhenFilteredOnFalse() { + final List expected = Collections.emptyList(); + assertEquals(expected, FCollection.filter(this.is, False.instance())); + } + + @Test + public void shouldReturnOnlyMatchesToPredicate() { + final Predicate p = a -> a <= 2; + final List expected = Arrays.asList(1, 2); + assertEquals(expected, FCollection.filter(this.is, p)); + } + + @Test + public void shouldApplyForEachToAllItems() { + final List actual = new ArrayList<>(); + final SideEffect1 e = a -> actual.add(a); + + FCollection.forEach(this.is, e); + + assertEquals(this.is, actual); + } + + @Test + public void shouldApplyMapToAllItems() { + assertEquals(this.is, FCollection.map(this.is, Prelude.id())); + } + + @Test + public void mapShouldTreatNullAsAnEmptyIterable() { + assertEquals(Collections.emptyList(), FCollection.map(null, Prelude.id())); + } + + @Test + public void shouldApplyFlatMapToAllItems() { + final Function> f = a -> Arrays.asList(a, a); + final Collection expected = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, + 5, 5); + assertEquals(expected, FCollection.flatMap(this.is, f)); + } + + @Test + public void flatMapShouldTreatNullAsEmptyIterable() { + assertEquals(Collections.emptyList(), + FCollection.flatMap(null, objectToObjectIterable())); + } + + private Function> objectToObjectIterable() { + return a -> Collections.emptyList(); + } + + @Test + public void containsShouldReturnFalseWhenPredicateNotMet() { + final Collection xs = Arrays.asList(1, 2, 3); + assertFalse(FCollection.contains(xs, False.instance())); + } + + @Test + public void containsShouldReturnTrueWhenPredicateMet() { + final Collection xs = Arrays.asList(1, 2, 3); + assertTrue(FCollection.contains(xs, i -> true)); + } + + @Test + public void containsShouldStopProcessingOnFirstMatch() { + final Collection xs = Arrays.asList(1, 2, 3); + final Predicate predicate = a -> { + if (a == 2) { + throw new PitError("Did not shortcut"); + } + return a == 1; + }; + FCollection.contains(xs, predicate); + // pass + } + + @Test + public void foldShouldFoldValues() { + final Collection xs = Arrays.asList(1, 2, 3); + final BiFunction f = (a, b) -> a + b; + + final int actual = FCollection.fold(f, 2, xs); + assertEquals(8, actual); + } + + @Test + public void flattenShouldReturnCollectionContainingAllSuppliedValues() { + final Collection> is = new ArrayList<>(); + is.add(Arrays.asList(1, 2, 3, 4, 5)); + is.add(Arrays.asList(6, 7, 8, 9)); + assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9), + FCollection.flatten(is)); + + } + + @Test + public void shouldSplitCollectionIntoOneBucketWhenListSizeEqualToBucketSize() { + this.is = Arrays.asList(1, 2, 3); + final List> actual = FCollection.splitToLength(3, this.is); + assertEquals(1, actual.size()); + assertThat(actual.get(0)).contains(1, 2, 3); + } + + @Test + public void shouldSplitCollectionIntoTwoBucketsWhenListSizeOneGreaterThanBucketSize() { + this.is = Arrays.asList(1, 2, 3); + final List> actual = FCollection.splitToLength(2, this.is); + assertEquals(2, actual.size()); + assertThat(actual.get(0)).contains(1, 2); + assertThat(actual.get(1)).contains(3); + } + + @Test + public void shouldSplitCollectionIntoManyBucketsWhenListManyTimesGreaterThanBucketSize() { + this.is = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); + final List> actual = FCollection.splitToLength(2, this.is); + assertEquals(6, actual.size()); + assertThat(actual.get(0)).contains(1, 2); + assertThat(actual.get(1)).contains(3, 4); + assertThat(actual.get(5)).contains(11); + } + + @Test + public void shouldSplitIntoSingleBucketWhenAllItemsMeetsCriteria() { + this.is = Arrays.asList(1, 2, 3); + final Map> actual = FCollection.bucket( + this.is, fortyTwo()); + final Map> expected = new HashMap<>(); + expected.put(42, Arrays.asList(1, 2, 3)); + assertEquals(expected, actual); + } + + @Test + public void shouldSplitIntoMultipleBuckets() { + this.is = Arrays.asList(1, 2, 3); + final Map> actual = FCollection.bucket( + this.is, Prelude.id(Integer.class)); + final Map> expected = new HashMap<>(); + expected.put(1, Arrays.asList(1)); + expected.put(2, Arrays.asList(2)); + expected.put(3, Arrays.asList(3)); + assertEquals(expected, actual); + } + + private Function fortyTwo() { + return a -> 42; + } + +} diff --git a/pitest/src/test/java/org/pitest/functional/predicate/AndTest.java b/pitest/src/test/java/org/pitest/functional/predicate/AndTest.java index 105ae30be..9137318bd 100644 --- a/pitest/src/test/java/org/pitest/functional/predicate/AndTest.java +++ b/pitest/src/test/java/org/pitest/functional/predicate/AndTest.java @@ -1,47 +1,47 @@ -package org.pitest.functional.predicate; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.pitest.functional.prelude.Prelude.and; - -import org.junit.Test; - -public class AndTest { - - @Test - public void shouldReturnFalseWhenSuppliedNoPredicate() { - final And testee = and(); - assertFalse(testee.test(null)); - } - - @Test - public void shouldBeTrueWhenGivenTrue() { - final And testee = and(i -> true); - assertTrue(testee.test(null)); - } - - @Test - public void shouldBeFalseWhenGivenFalse() { - final And testee = and(False.instance()); - assertFalse(testee.test(null)); - } - - @Test - public void shouldBeTrueWhenGivenTrueAndTrue() { - final And testee = and(i -> true, i -> true); - assertTrue(testee.test(null)); - } - - @Test - public void shouldBeFalseWhenGivenTrueAndFalse() { - final And testee = and( i -> true, i -> false); - assertFalse(testee.test(null)); - } - - @Test - public void shouldBeFalseWhenGivenFalseAndFalse() { - final And testee = and(False.instance(), False.instance()); - assertFalse(testee.test(null)); - } - -} +package org.pitest.functional.predicate; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.pitest.functional.prelude.Prelude.and; + +import org.junit.Test; + +public class AndTest { + + @Test + public void shouldReturnFalseWhenSuppliedNoPredicate() { + final And testee = and(); + assertFalse(testee.test(null)); + } + + @Test + public void shouldBeTrueWhenGivenTrue() { + final And testee = and(i -> true); + assertTrue(testee.test(null)); + } + + @Test + public void shouldBeFalseWhenGivenFalse() { + final And testee = and(False.instance()); + assertFalse(testee.test(null)); + } + + @Test + public void shouldBeTrueWhenGivenTrueAndTrue() { + final And testee = and(i -> true, i -> true); + assertTrue(testee.test(null)); + } + + @Test + public void shouldBeFalseWhenGivenTrueAndFalse() { + final And testee = and( i -> true, i -> false); + assertFalse(testee.test(null)); + } + + @Test + public void shouldBeFalseWhenGivenFalseAndFalse() { + final And testee = and(False.instance(), False.instance()); + assertFalse(testee.test(null)); + } + +} diff --git a/pitest/src/test/java/org/pitest/functional/predicate/FalseTest.java b/pitest/src/test/java/org/pitest/functional/predicate/FalseTest.java index 04e2a67bc..32ede2077 100644 --- a/pitest/src/test/java/org/pitest/functional/predicate/FalseTest.java +++ b/pitest/src/test/java/org/pitest/functional/predicate/FalseTest.java @@ -1,18 +1,18 @@ -package org.pitest.functional.predicate; - -import static org.junit.Assert.assertFalse; - -import org.junit.Test; - -/** - * @author henry - * - */ -public class FalseTest { - - @Test - public void shouldAlwaysBeFalse() { - assertFalse(False.instance().test(null)); - } - -} +package org.pitest.functional.predicate; + +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +/** + * @author henry + * + */ +public class FalseTest { + + @Test + public void shouldAlwaysBeFalse() { + assertFalse(False.instance().test(null)); + } + +} diff --git a/pitest/src/test/java/org/pitest/functional/predicate/NotTest.java b/pitest/src/test/java/org/pitest/functional/predicate/NotTest.java index 83f0695fb..8fc3da6ab 100644 --- a/pitest/src/test/java/org/pitest/functional/predicate/NotTest.java +++ b/pitest/src/test/java/org/pitest/functional/predicate/NotTest.java @@ -1,27 +1,27 @@ -/** - * - */ -package org.pitest.functional.predicate; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.pitest.functional.prelude.Prelude.not; - -import org.junit.Test; - -/** - * @author henry - * - */ -public class NotTest { - - @Test - public void shouldInvertTrue() { - assertFalse(not(i -> true).test(null)); - } - - @Test - public void shouldInvertFalse() { - assertTrue(not(False.instance()).test(null)); - } -} +/** + * + */ +package org.pitest.functional.predicate; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.pitest.functional.prelude.Prelude.not; + +import org.junit.Test; + +/** + * @author henry + * + */ +public class NotTest { + + @Test + public void shouldInvertTrue() { + assertFalse(not(i -> true).test(null)); + } + + @Test + public void shouldInvertFalse() { + assertTrue(not(False.instance()).test(null)); + } +} diff --git a/pitest/src/test/java/org/pitest/functional/predicate/OrTest.java b/pitest/src/test/java/org/pitest/functional/predicate/OrTest.java index 46a3f69a7..4070ba3de 100644 --- a/pitest/src/test/java/org/pitest/functional/predicate/OrTest.java +++ b/pitest/src/test/java/org/pitest/functional/predicate/OrTest.java @@ -1,47 +1,47 @@ -package org.pitest.functional.predicate; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.pitest.functional.prelude.Prelude.or; - -import org.junit.Test; - -public class OrTest { - - @Test - public void shouldBeFalseWhenGivenNoPredicates() { - final Or testee = or(); - assertFalse(testee.test(null)); - } - - @Test - public void shouldBeTrueWhenGivenTrue() { - final Or testee = or( i -> true); - assertTrue(testee.test(null)); - } - - @Test - public void shouldBeFalseWhenGivenFalse() { - final Or testee = or(False.instance()); - assertFalse(testee.test(null)); - } - - @Test - public void shouldBeTrueWhenTrueOrTrue() { - final Or testee = or( i -> true, i -> true); - assertTrue(testee.test(null)); - } - - @Test - public void shouldBeTrueWhenTrueOrFalse() { - final Or testee = or( i -> true, False.instance()); - assertTrue(testee.test(null)); - } - - @Test - public void shouldeFalseWhenFalseOrFalse() { - final Or testee = or(False.instance(), False.instance()); - assertFalse(testee.test(null)); - } - -} +package org.pitest.functional.predicate; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.pitest.functional.prelude.Prelude.or; + +import org.junit.Test; + +public class OrTest { + + @Test + public void shouldBeFalseWhenGivenNoPredicates() { + final Or testee = or(); + assertFalse(testee.test(null)); + } + + @Test + public void shouldBeTrueWhenGivenTrue() { + final Or testee = or( i -> true); + assertTrue(testee.test(null)); + } + + @Test + public void shouldBeFalseWhenGivenFalse() { + final Or testee = or(False.instance()); + assertFalse(testee.test(null)); + } + + @Test + public void shouldBeTrueWhenTrueOrTrue() { + final Or testee = or( i -> true, i -> true); + assertTrue(testee.test(null)); + } + + @Test + public void shouldBeTrueWhenTrueOrFalse() { + final Or testee = or( i -> true, False.instance()); + assertTrue(testee.test(null)); + } + + @Test + public void shouldeFalseWhenFalseOrFalse() { + final Or testee = or(False.instance(), False.instance()); + assertFalse(testee.test(null)); + } + +} diff --git a/pitest/src/test/java/org/pitest/functional/prelude/PreludeTest.java b/pitest/src/test/java/org/pitest/functional/prelude/PreludeTest.java index 7d826e40f..b4008d30c 100644 --- a/pitest/src/test/java/org/pitest/functional/prelude/PreludeTest.java +++ b/pitest/src/test/java/org/pitest/functional/prelude/PreludeTest.java @@ -1,56 +1,56 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.functional.prelude; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.verify; - -import java.io.PrintStream; - -import org.junit.Test; -import org.mockito.Mockito; - -public class PreludeTest { - - @Test - public void isNullShouldReturnsTrueWhenNull() { - assertTrue(Prelude.isNull().test(null)); - } - - @Test - public void isNullShouldReturnFalseWhenNotNull() { - assertFalse(Prelude.isNull().test(1)); - } - - @Test - public void isNotNullShouldReturnFalseWhenNull() { - assertFalse(Prelude.isNotNull().test(null)); - } - - @Test - public void isNotNullShouldReturnTrueWhenNotNull() { - assertTrue(Prelude.isNotNull().test(1)); - } - - @Test - public void printToShouldPrintValueToStream() { - final Integer i = Integer.valueOf(42); - final PrintStream stream = Mockito.mock(PrintStream.class); - Prelude.printTo(stream).apply(i); - verify(stream).print(i); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.functional.prelude; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; + +import java.io.PrintStream; + +import org.junit.Test; +import org.mockito.Mockito; + +public class PreludeTest { + + @Test + public void isNullShouldReturnsTrueWhenNull() { + assertTrue(Prelude.isNull().test(null)); + } + + @Test + public void isNullShouldReturnFalseWhenNotNull() { + assertFalse(Prelude.isNull().test(1)); + } + + @Test + public void isNotNullShouldReturnFalseWhenNull() { + assertFalse(Prelude.isNotNull().test(null)); + } + + @Test + public void isNotNullShouldReturnTrueWhenNotNull() { + assertTrue(Prelude.isNotNull().test(1)); + } + + @Test + public void printToShouldPrintValueToStream() { + final Integer i = Integer.valueOf(42); + final PrintStream stream = Mockito.mock(PrintStream.class); + Prelude.printTo(stream).apply(i); + verify(stream).print(i); + } + +} diff --git a/pitest/src/test/java/org/pitest/help/PitHelpErrorTest.java b/pitest/src/test/java/org/pitest/help/PitHelpErrorTest.java index 2f28e7682..ca8da1980 100644 --- a/pitest/src/test/java/org/pitest/help/PitHelpErrorTest.java +++ b/pitest/src/test/java/org/pitest/help/PitHelpErrorTest.java @@ -1,30 +1,30 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.help; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class PitHelpErrorTest { - - @Test - public void shouldFormatTextStrings() { - final PitHelpError testee = new PitHelpError(Help.WRONG_JUNIT_VERSION, - "3.8.1"); - assertTrue(testee.getMessage().contains("3.8.1")); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.help; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class PitHelpErrorTest { + + @Test + public void shouldFormatTextStrings() { + final PitHelpError testee = new PitHelpError(Help.WRONG_JUNIT_VERSION, + "3.8.1"); + assertTrue(testee.getMessage().contains("3.8.1")); + } + +} diff --git a/pitest/src/test/java/org/pitest/junit/JUnit4SuiteFinderTest.java b/pitest/src/test/java/org/pitest/junit/JUnit4SuiteFinderTest.java index 2c38e4a8b..7e900b06b 100644 --- a/pitest/src/test/java/org/pitest/junit/JUnit4SuiteFinderTest.java +++ b/pitest/src/test/java/org/pitest/junit/JUnit4SuiteFinderTest.java @@ -1,61 +1,61 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -public class JUnit4SuiteFinderTest { - - private JUnit4SuiteFinder testee; - - @Before - public void setUp() { - this.testee = new JUnit4SuiteFinder(); - } - - @Test - public void shouldReturnEmptyCollectionForUnannotatedClass() { - final Class noAnnotation = JUnit4SuiteFinderTest.class; - assertTrue(this.testee.apply(noAnnotation).isEmpty()); - } - - private static class HideFromJUnit { - - @RunWith(Suite.class) - @SuiteClasses({ String.class, Integer.class }) - private static class AnnotatedJUnit { - - } - } - - @Test - public void shouldReturnTestClassForEachClassInSuiteClassesAnnotationWhenRunnerIsSuite() { - final Class annotated = HideFromJUnit.AnnotatedJUnit.class; - final Collection> expected = Arrays.> asList( - String.class, Integer.class); - assertEquals(expected, this.testee.apply(annotated)); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +public class JUnit4SuiteFinderTest { + + private JUnit4SuiteFinder testee; + + @Before + public void setUp() { + this.testee = new JUnit4SuiteFinder(); + } + + @Test + public void shouldReturnEmptyCollectionForUnannotatedClass() { + final Class noAnnotation = JUnit4SuiteFinderTest.class; + assertTrue(this.testee.apply(noAnnotation).isEmpty()); + } + + private static class HideFromJUnit { + + @RunWith(Suite.class) + @SuiteClasses({ String.class, Integer.class }) + private static class AnnotatedJUnit { + + } + } + + @Test + public void shouldReturnTestClassForEachClassInSuiteClassesAnnotationWhenRunnerIsSuite() { + final Class annotated = HideFromJUnit.AnnotatedJUnit.class; + final Collection> expected = Arrays.> asList( + String.class, Integer.class); + assertEquals(expected, this.testee.apply(annotated)); + } + +} diff --git a/pitest/src/test/java/org/pitest/junit/JUnitCompatibleConfigurationTest.java b/pitest/src/test/java/org/pitest/junit/JUnitCompatibleConfigurationTest.java index e801291dc..55a6d4fb9 100644 --- a/pitest/src/test/java/org/pitest/junit/JUnitCompatibleConfigurationTest.java +++ b/pitest/src/test/java/org/pitest/junit/JUnitCompatibleConfigurationTest.java @@ -1,44 +1,44 @@ -package org.pitest.junit; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.testapi.TestGroupConfig; - -public class JUnitCompatibleConfigurationTest { - JUnitCompatibleConfiguration testee; - - @Before - public void setUp() throws Exception { - - this.testee = new JUnitCompatibleConfiguration(new TestGroupConfig(), Collections.emptyList(), - Collections.emptyList()); - } - - @Test - public void considersPre46Invalid() throws Exception { - assertThat(this.testee.isInvalidVersion("4.5"), is(true)); - assertThat(this.testee.isInvalidVersion("4.5-SNAPSHOT"), is(true)); - } - - @Test - public void canParseReleaseVersion() throws Exception { - assertThat(this.testee.isInvalidVersion("4.6"), is(false)); - assertThat(this.testee.isInvalidVersion("4.10"), is(false)); - } - - @Test - public void canParseSnapshotVersion() throws Exception { - assertThat(this.testee.isInvalidVersion("4.10-SNAPSHOT"), is(false)); - assertThat(this.testee.isInvalidVersion("4.5-SNAPSHOT"), is(true)); - } - - @Test - public void canParseReleaseCandidateVersion() throws Exception { - assertThat(this.testee.isInvalidVersion("4.10.rc1"), is(false)); - } +package org.pitest.junit; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.testapi.TestGroupConfig; + +public class JUnitCompatibleConfigurationTest { + JUnitCompatibleConfiguration testee; + + @Before + public void setUp() throws Exception { + + this.testee = new JUnitCompatibleConfiguration(new TestGroupConfig(), Collections.emptyList(), + Collections.emptyList()); + } + + @Test + public void considersPre46Invalid() throws Exception { + assertThat(this.testee.isInvalidVersion("4.5"), is(true)); + assertThat(this.testee.isInvalidVersion("4.5-SNAPSHOT"), is(true)); + } + + @Test + public void canParseReleaseVersion() throws Exception { + assertThat(this.testee.isInvalidVersion("4.6"), is(false)); + assertThat(this.testee.isInvalidVersion("4.10"), is(false)); + } + + @Test + public void canParseSnapshotVersion() throws Exception { + assertThat(this.testee.isInvalidVersion("4.10-SNAPSHOT"), is(false)); + assertThat(this.testee.isInvalidVersion("4.5-SNAPSHOT"), is(true)); + } + + @Test + public void canParseReleaseCandidateVersion() throws Exception { + assertThat(this.testee.isInvalidVersion("4.10.rc1"), is(false)); + } } \ No newline at end of file diff --git a/pitest/src/test/java/org/pitest/junit/JUnitCustomRunnerTestUnitFinderTest.java b/pitest/src/test/java/org/pitest/junit/JUnitCustomRunnerTestUnitFinderTest.java index 48c84cbd2..0cf0e22ed 100644 --- a/pitest/src/test/java/org/pitest/junit/JUnitCustomRunnerTestUnitFinderTest.java +++ b/pitest/src/test/java/org/pitest/junit/JUnitCustomRunnerTestUnitFinderTest.java @@ -1,462 +1,462 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.pitest.testapi.TestGroupConfig.emptyConfig; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.jmock.MockObjectTestCase; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExternalResource; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runner.Runner; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.RunnerBuilder; -import org.mockito.MockitoAnnotations; -import org.pitest.junit.RunnerSuiteFinderTest.ThrowsOnDiscoverySuite; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.testapi.TestUnit; - -import com.example.JUnitParamsTest; -import com.example.TheoryTest; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class JUnitCustomRunnerTestUnitFinderTest { - - private JUnitCustomRunnerTestUnitFinder testee; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - this.testee = new JUnitCustomRunnerTestUnitFinder(new TestGroupConfig(), Collections.emptyList(), - Collections.emptyList()); - } - - @Test - public void shouldFindTheoryTestViaMethodNameTest() { - final List includedMethods = new ArrayList<>(); - includedMethods.add("testTheory1"); - includedMethods.add("testTheory3"); - setIncludedTestMethods(includedMethods); - final Collection actual = findWithTestee(TheoryTest.class); - assertEquals(2, actual.size()); - } - - @Test - public void shouldFindTestsInJUnitTheoryTest() { - final Collection actual = findWithTestee(TheoryTest.class); - assertEquals(3, actual.size()); - } - - @RunWith(Parameterized.class) - public static class ParameterisedTest { - - public ParameterisedTest(final int i) { - - } - - @Parameters - public static Collection params() { - return Arrays.asList(new Object[][] { { 1 }, { 2 } }); - } - - @Test - public void test() { - } - - } - - @Test - public void shouldNotFindTestInParameterisedTestClass() { - final Collection actual = findWithTestee(ParameterisedTest.class); - assertEquals(0, actual.size()); - } - - public static class CustomSuiteRunner extends Suite { - - public CustomSuiteRunner(final Class klass, final RunnerBuilder rb) - throws InitializationError { - super(klass, rb); - } - - } - - public static class One { - @Test - public void one() { - - } - - @Test - public void two() { - - } - } - - public static class Two { - @Test - public void one() { - - } - - @Test - public void two() { - - } - } - - @RunWith(CustomSuiteRunner.class) - @SuiteClasses({ One.class, Two.class }) - public static class CustomSuite { - - } - - @Test - public void shouldNotFindTestsInCustomSuite() { - final Collection actual = findWithTestee(CustomSuite.class); - assertTrue(actual.isEmpty()); - } - - public static class Three { - @Test - public void one() { - - } - - @Test - public void two() { - - } - } - - @RunWith(CustomSuiteRunner.class) - @SuiteClasses({ CustomSuite.class, Three.class }) - public static class NestCustomSuite { - - } - - @Test - public void shouldNotFindTestsInNestedCustomSuites() { - final Collection actual = findWithTestee(NestCustomSuite.class); - assertTrue(actual.isEmpty()); - } - - private Collection findWithTestee(final Class clazz) { - return this.testee.findTestUnits(clazz); - } - - public static class NotATest { - - } - - @Test - public void shouldNotFindTestInNonTestClasses() { - final Collection actual = findWithTestee(NotATest.class); - assertTrue(actual.isEmpty()); - } - - public static class JMockTest extends MockObjectTestCase { - public void testExample() { - - } - } - - @Test - public void shouldFindTestUnitsInCustomJUnit3Class() { - final Collection actual = this.testee - .findTestUnits(JMockTest.class); - assertFalse(actual.isEmpty()); - } - - public static class JUnit3Test extends TestCase { - public void testStuff() { - - } - } - - public static class HasBeforeClassAnnotation { - - @BeforeClass - public static void before() { - - } - - @Test - public void testOne() { - - } - - @Test - public void testTwo() { - - } - - } - - @Test - public void shouldCreateSingleAtomicUnitWhenClassAnnotatedWithBeforeClass() { - final Collection actual = findWithTestee(HasBeforeClassAnnotation.class); - assertEquals(1, actual.size()); - } - - public static class HasAfterClassAnnotation { - - @AfterClass - public static void after() { - - } - - @Test - public void testOne() { - - } - - @Test - public void testTwo() { - - } - - } - - @Test - public void shouldCreateSingleAtomicUnitWhenClassAnnotatedWithAfterClass() { - final Collection actual = findWithTestee(HasAfterClassAnnotation.class); - assertEquals(1, actual.size()); - } - - public static class ClassRuleMethod { - - @ClassRule - public static TestRule rule() { - return new ExternalResource() { - }; - } - - @Test - public void testOne() { - } - - @Test - public void testTwo() { - } - } - - @Test - public void shouldCreateSingleAtomicUnitWhenAnyMethodAnnotatedWithClassRule() - throws Exception { - final Collection actual = findWithTestee(ClassRuleMethod.class); - assertEquals(1, actual.size()); - } - - public static class ClassRuleField { - - @ClassRule - public static TestRule rule = new ExternalResource() { - }; - - @Test - public void testOne() { - } - - @Test - public void testTwo() { - } - } - - @Test - public void shouldCreateSingleAtomicUnitWhenAnyFieldAnnotatedWithClassRule() - throws Exception { - final Collection actual = findWithTestee(ClassRuleMethod.class); - assertEquals(1, actual.size()); - } - - public static class NoPublicConstructor extends TestCase { - protected NoPublicConstructor() { - - } - - public void testFoo() { - - } - } - - @Test - public void shouldNotFindTestsInClassesExtendingTestCaseWithoutAPublicConstructor() { - final Collection actual = findWithTestee(NoPublicConstructor.class); - assertEquals(0, actual.size()); - } - - public static class OwnSuiteMethod extends TestCase { - - public static TestSuite suite() { - return new TestSuite(OwnSuiteMethod.class); - } - - public void testOne() { - - } - - public void testTwo() { - - } - - } - - @Test - public void shouldFindTestsInClassWithASuiteMethodThatReturnsItself() { - final Collection actual = findWithTestee(OwnSuiteMethod.class); - assertEquals(2, actual.size()); - } - - public static class SuiteMethod extends TestCase { - - public static TestSuite suite() { - return new TestSuite(JUnit3Test.class); - } - - } - - @Test - public void shouldNotFindTestsInClassWithASuiteMethodThatReturnsOthersClasses() { - final Collection actual = findWithTestee(SuiteMethod.class); - assertEquals(0, actual.size()); - } - - @Test - public void willFindSingleTestUnitInJUnitParamsTest() { - final Collection actual = findWithTestee(JUnitParamsTest.class); - assertEquals(1, actual.size()); - } - - @Test - public void shouldNotHaltWhenRunnerThrowsRuntimeException() { - try { - findWithTestee(ThrowsOnDiscoverySuite.class); - // pass - } catch(final RuntimeException ex) { - fail(); - } - } - - @Test - public void includesSuppliedCategories() { - setConfig(emptyConfig() - .withIncludedGroups(ACategory.class.getName())); - final Collection actual = findWithTestee(Tagged.class); - assertThat(actual).hasSize(1); - } - - @Test - public void excludesSuppliedCategories() { - setConfig(emptyConfig() - .withIncludedGroups(ACategory.class.getName()) - .withExcludedGroups(AnotherCategory.class.getName())); - final Collection actual = findWithTestee(Tagged.class); - assertThat(actual).isEmpty(); - } - - @Test - public void excludesInheritedCategories() { - setConfig(emptyConfig() - .withIncludedGroups(ACategory.class.getName()) - .withExcludedGroups(AnotherCategory.class.getName())); - final Collection actual = findWithTestee(IndirectlyTagged.class); - assertThat(actual).isEmpty(); - } - - @Test - public void excludesRunnersWhenRequested() { - excludeRunner(BlockJUnit4ClassRunner.class); - final Collection actual = findWithTestee(HasExplicitRunner.class); - assertThat(actual).isEmpty(); - } - - static interface ACategory { - - } - - static interface AnotherCategory { - - } - - @Category({ACategory.class, AnotherCategory.class}) - public static class Tagged { - @Test - public void testTwo() { - } - } - - public static class IndirectlyTagged extends Tagged { - @Test - public void test() { - } - } - - - @RunWith(BlockJUnit4ClassRunner.class) - public static class HasExplicitRunner { - @Test - public void foo() { - - } - } - - - private void setConfig(TestGroupConfig config) { - this.testee = new JUnitCustomRunnerTestUnitFinder( - config, Collections.emptyList(), Collections.emptyList()); - } - - - private void excludeRunner(Class class1) { - final List include = Collections.emptyList(); - final List exclude = Collections.emptyList(); - this.testee = new JUnitCustomRunnerTestUnitFinder( - new TestGroupConfig(include,exclude), Collections.singletonList(class1.getName()), - Collections.emptyList()); - } - - private void setIncludedTestMethods(Collection includedTestMethods) { - final List include = Collections.emptyList(); - final List exclude = Collections.emptyList(); - this.testee = new JUnitCustomRunnerTestUnitFinder( - new TestGroupConfig(include,exclude), Collections.emptyList(), includedTestMethods); - } - - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.pitest.testapi.TestGroupConfig.emptyConfig; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.jmock.MockObjectTestCase; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.rules.ExternalResource; +import org.junit.rules.TestRule; +import org.junit.runner.RunWith; +import org.junit.runner.Runner; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; +import org.mockito.MockitoAnnotations; +import org.pitest.junit.RunnerSuiteFinderTest.ThrowsOnDiscoverySuite; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.testapi.TestUnit; + +import com.example.JUnitParamsTest; +import com.example.TheoryTest; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class JUnitCustomRunnerTestUnitFinderTest { + + private JUnitCustomRunnerTestUnitFinder testee; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + this.testee = new JUnitCustomRunnerTestUnitFinder(new TestGroupConfig(), Collections.emptyList(), + Collections.emptyList()); + } + + @Test + public void shouldFindTheoryTestViaMethodNameTest() { + final List includedMethods = new ArrayList<>(); + includedMethods.add("testTheory1"); + includedMethods.add("testTheory3"); + setIncludedTestMethods(includedMethods); + final Collection actual = findWithTestee(TheoryTest.class); + assertEquals(2, actual.size()); + } + + @Test + public void shouldFindTestsInJUnitTheoryTest() { + final Collection actual = findWithTestee(TheoryTest.class); + assertEquals(3, actual.size()); + } + + @RunWith(Parameterized.class) + public static class ParameterisedTest { + + public ParameterisedTest(final int i) { + + } + + @Parameters + public static Collection params() { + return Arrays.asList(new Object[][] { { 1 }, { 2 } }); + } + + @Test + public void test() { + } + + } + + @Test + public void shouldNotFindTestInParameterisedTestClass() { + final Collection actual = findWithTestee(ParameterisedTest.class); + assertEquals(0, actual.size()); + } + + public static class CustomSuiteRunner extends Suite { + + public CustomSuiteRunner(final Class klass, final RunnerBuilder rb) + throws InitializationError { + super(klass, rb); + } + + } + + public static class One { + @Test + public void one() { + + } + + @Test + public void two() { + + } + } + + public static class Two { + @Test + public void one() { + + } + + @Test + public void two() { + + } + } + + @RunWith(CustomSuiteRunner.class) + @SuiteClasses({ One.class, Two.class }) + public static class CustomSuite { + + } + + @Test + public void shouldNotFindTestsInCustomSuite() { + final Collection actual = findWithTestee(CustomSuite.class); + assertTrue(actual.isEmpty()); + } + + public static class Three { + @Test + public void one() { + + } + + @Test + public void two() { + + } + } + + @RunWith(CustomSuiteRunner.class) + @SuiteClasses({ CustomSuite.class, Three.class }) + public static class NestCustomSuite { + + } + + @Test + public void shouldNotFindTestsInNestedCustomSuites() { + final Collection actual = findWithTestee(NestCustomSuite.class); + assertTrue(actual.isEmpty()); + } + + private Collection findWithTestee(final Class clazz) { + return this.testee.findTestUnits(clazz); + } + + public static class NotATest { + + } + + @Test + public void shouldNotFindTestInNonTestClasses() { + final Collection actual = findWithTestee(NotATest.class); + assertTrue(actual.isEmpty()); + } + + public static class JMockTest extends MockObjectTestCase { + public void testExample() { + + } + } + + @Test + public void shouldFindTestUnitsInCustomJUnit3Class() { + final Collection actual = this.testee + .findTestUnits(JMockTest.class); + assertFalse(actual.isEmpty()); + } + + public static class JUnit3Test extends TestCase { + public void testStuff() { + + } + } + + public static class HasBeforeClassAnnotation { + + @BeforeClass + public static void before() { + + } + + @Test + public void testOne() { + + } + + @Test + public void testTwo() { + + } + + } + + @Test + public void shouldCreateSingleAtomicUnitWhenClassAnnotatedWithBeforeClass() { + final Collection actual = findWithTestee(HasBeforeClassAnnotation.class); + assertEquals(1, actual.size()); + } + + public static class HasAfterClassAnnotation { + + @AfterClass + public static void after() { + + } + + @Test + public void testOne() { + + } + + @Test + public void testTwo() { + + } + + } + + @Test + public void shouldCreateSingleAtomicUnitWhenClassAnnotatedWithAfterClass() { + final Collection actual = findWithTestee(HasAfterClassAnnotation.class); + assertEquals(1, actual.size()); + } + + public static class ClassRuleMethod { + + @ClassRule + public static TestRule rule() { + return new ExternalResource() { + }; + } + + @Test + public void testOne() { + } + + @Test + public void testTwo() { + } + } + + @Test + public void shouldCreateSingleAtomicUnitWhenAnyMethodAnnotatedWithClassRule() + throws Exception { + final Collection actual = findWithTestee(ClassRuleMethod.class); + assertEquals(1, actual.size()); + } + + public static class ClassRuleField { + + @ClassRule + public static TestRule rule = new ExternalResource() { + }; + + @Test + public void testOne() { + } + + @Test + public void testTwo() { + } + } + + @Test + public void shouldCreateSingleAtomicUnitWhenAnyFieldAnnotatedWithClassRule() + throws Exception { + final Collection actual = findWithTestee(ClassRuleMethod.class); + assertEquals(1, actual.size()); + } + + public static class NoPublicConstructor extends TestCase { + protected NoPublicConstructor() { + + } + + public void testFoo() { + + } + } + + @Test + public void shouldNotFindTestsInClassesExtendingTestCaseWithoutAPublicConstructor() { + final Collection actual = findWithTestee(NoPublicConstructor.class); + assertEquals(0, actual.size()); + } + + public static class OwnSuiteMethod extends TestCase { + + public static TestSuite suite() { + return new TestSuite(OwnSuiteMethod.class); + } + + public void testOne() { + + } + + public void testTwo() { + + } + + } + + @Test + public void shouldFindTestsInClassWithASuiteMethodThatReturnsItself() { + final Collection actual = findWithTestee(OwnSuiteMethod.class); + assertEquals(2, actual.size()); + } + + public static class SuiteMethod extends TestCase { + + public static TestSuite suite() { + return new TestSuite(JUnit3Test.class); + } + + } + + @Test + public void shouldNotFindTestsInClassWithASuiteMethodThatReturnsOthersClasses() { + final Collection actual = findWithTestee(SuiteMethod.class); + assertEquals(0, actual.size()); + } + + @Test + public void willFindSingleTestUnitInJUnitParamsTest() { + final Collection actual = findWithTestee(JUnitParamsTest.class); + assertEquals(1, actual.size()); + } + + @Test + public void shouldNotHaltWhenRunnerThrowsRuntimeException() { + try { + findWithTestee(ThrowsOnDiscoverySuite.class); + // pass + } catch(final RuntimeException ex) { + fail(); + } + } + + @Test + public void includesSuppliedCategories() { + setConfig(emptyConfig() + .withIncludedGroups(ACategory.class.getName())); + final Collection actual = findWithTestee(Tagged.class); + assertThat(actual).hasSize(1); + } + + @Test + public void excludesSuppliedCategories() { + setConfig(emptyConfig() + .withIncludedGroups(ACategory.class.getName()) + .withExcludedGroups(AnotherCategory.class.getName())); + final Collection actual = findWithTestee(Tagged.class); + assertThat(actual).isEmpty(); + } + + @Test + public void excludesInheritedCategories() { + setConfig(emptyConfig() + .withIncludedGroups(ACategory.class.getName()) + .withExcludedGroups(AnotherCategory.class.getName())); + final Collection actual = findWithTestee(IndirectlyTagged.class); + assertThat(actual).isEmpty(); + } + + @Test + public void excludesRunnersWhenRequested() { + excludeRunner(BlockJUnit4ClassRunner.class); + final Collection actual = findWithTestee(HasExplicitRunner.class); + assertThat(actual).isEmpty(); + } + + static interface ACategory { + + } + + static interface AnotherCategory { + + } + + @Category({ACategory.class, AnotherCategory.class}) + public static class Tagged { + @Test + public void testTwo() { + } + } + + public static class IndirectlyTagged extends Tagged { + @Test + public void test() { + } + } + + + @RunWith(BlockJUnit4ClassRunner.class) + public static class HasExplicitRunner { + @Test + public void foo() { + + } + } + + + private void setConfig(TestGroupConfig config) { + this.testee = new JUnitCustomRunnerTestUnitFinder( + config, Collections.emptyList(), Collections.emptyList()); + } + + + private void excludeRunner(Class class1) { + final List include = Collections.emptyList(); + final List exclude = Collections.emptyList(); + this.testee = new JUnitCustomRunnerTestUnitFinder( + new TestGroupConfig(include,exclude), Collections.singletonList(class1.getName()), + Collections.emptyList()); + } + + private void setIncludedTestMethods(Collection includedTestMethods) { + final List include = Collections.emptyList(); + final List exclude = Collections.emptyList(); + this.testee = new JUnitCustomRunnerTestUnitFinder( + new TestGroupConfig(include,exclude), Collections.emptyList(), includedTestMethods); + } + + +} diff --git a/pitest/src/test/java/org/pitest/junit/ParameterisedJUnitTestFinderTest.java b/pitest/src/test/java/org/pitest/junit/ParameterisedJUnitTestFinderTest.java index fdbcf5c78..50f228fe7 100644 --- a/pitest/src/test/java/org/pitest/junit/ParameterisedJUnitTestFinderTest.java +++ b/pitest/src/test/java/org/pitest/junit/ParameterisedJUnitTestFinderTest.java @@ -1,78 +1,78 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.pitest.testapi.TestUnit; - -public class ParameterisedJUnitTestFinderTest { - - private ParameterisedJUnitTestFinder testee; - - @Before - public void setup() { - this.testee = new ParameterisedJUnitTestFinder(); - } - - @RunWith(Parameterized.class) - public static class ParameterisedTest { - - public ParameterisedTest(final int i) { - - } - - @Parameters - public static Collection params() { - return Arrays.asList(new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } }); - } - - @Test - public void test() { - } - - @Test - public void anotherTest() { - - } - - } - - @Test - public void shouldCreateTestUnitForEachParameterMethodCombinationOfParameterizedTest() { - final Collection actual = findWithTestee(ParameterisedTest.class); - assertEquals(8, actual.size()); - } - - @Test - public void shouldReturnNoTestForNonParameterisedTest() { - final Collection actual = findWithTestee(ParameterisedJUnitTestFinderTest.class); - assertTrue(actual.isEmpty()); - } - - private Collection findWithTestee(final Class clazz) { - return this.testee.findTestUnits(clazz); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.pitest.testapi.TestUnit; + +public class ParameterisedJUnitTestFinderTest { + + private ParameterisedJUnitTestFinder testee; + + @Before + public void setup() { + this.testee = new ParameterisedJUnitTestFinder(); + } + + @RunWith(Parameterized.class) + public static class ParameterisedTest { + + public ParameterisedTest(final int i) { + + } + + @Parameters + public static Collection params() { + return Arrays.asList(new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } }); + } + + @Test + public void test() { + } + + @Test + public void anotherTest() { + + } + + } + + @Test + public void shouldCreateTestUnitForEachParameterMethodCombinationOfParameterizedTest() { + final Collection actual = findWithTestee(ParameterisedTest.class); + assertEquals(8, actual.size()); + } + + @Test + public void shouldReturnNoTestForNonParameterisedTest() { + final Collection actual = findWithTestee(ParameterisedJUnitTestFinderTest.class); + assertTrue(actual.isEmpty()); + } + + private Collection findWithTestee(final Class clazz) { + return this.testee.findTestUnits(clazz); + } + +} diff --git a/pitest/src/test/java/org/pitest/junit/RunnerSuiteFinderTest.java b/pitest/src/test/java/org/pitest/junit/RunnerSuiteFinderTest.java index 3a917cadb..8e217dec3 100644 --- a/pitest/src/test/java/org/pitest/junit/RunnerSuiteFinderTest.java +++ b/pitest/src/test/java/org/pitest/junit/RunnerSuiteFinderTest.java @@ -1,159 +1,159 @@ -package org.pitest.junit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.RunnerBuilder; - -import com.example.TheoryTest; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class RunnerSuiteFinderTest { - - private RunnerSuiteFinder testee; - - @Before - public void setup() { - this.testee = new RunnerSuiteFinder(); - } - - @Test - public void shouldNotFindClassesInJUnitTheoryTest() { - final Collection> actual = findWithTestee(TheoryTest.class); - assertTrue(actual.isEmpty()); - } - - public static class CustomSuiteRunner extends Suite { - - public CustomSuiteRunner(final Class klass, final RunnerBuilder rb) - throws InitializationError { - super(klass, rb); - } - - } - - public static class One extends TestCase { - public void testSomething() { - } - } - - public static class Two extends One { - } - - @RunWith(CustomSuiteRunner.class) - @SuiteClasses({ One.class, Two.class }) - static class CustomSuite { - - } - - @Test - public void shouldFindSuiteClassesInCustomSuite() { - final Collection> actual = findWithTestee(CustomSuite.class); - final Collection> expected = Arrays.> asList(One.class, - Two.class); - - assertContains(expected, actual); - } - - public static class JUnit3Suite extends TestCase { - public static junit.framework.Test suite() { - - final TestSuite suite = new TestSuite(); - suite.addTestSuite(One.class); - suite.addTestSuite(Two.class); - - return suite; - } - } - - @Test - public void shouldFindSuiteClassesInJUnit3Suite() { - final Collection> actual = findWithTestee(JUnit3Suite.class); - final Collection> expected = Arrays.> asList(One.class, - Two.class); - assertContains(expected, actual); - } - - public static class JUnit3SuiteMethod extends TestCase { - public JUnit3SuiteMethod(final String testName) { - super(testName); - } - - public static junit.framework.Test suite() { - final TestSuite suite = new TestSuite(); - suite.addTest(new One()); - suite.addTest(new Two()); - return suite; - } - - } - - @Test - public void shouldFindSuiteClassesInJUnit3SuiteMethod() { - final Collection> actual = findWithTestee(JUnit3SuiteMethod.class); - final Collection> expected = Arrays.> asList(One.class, - Two.class); - assertContains(expected, actual); - } - - @Test - public void shouldFindSuiteClasseInNestedJUnit3Suite() { - final Collection> actual = findWithTestee(com.example.JUnitThreeSuite.class); - final Collection> expected = Arrays - .> asList(com.example.JUnitThreeTest.class); - assertContains(expected, actual); - } - - @Test - public void shouldNotHaltWhenRunnerThrowsRuntimeException() { - try { - findWithTestee(ThrowsOnDiscoverySuite.class); - // pass - } catch(final RuntimeException ex) { - fail(); - } - } - - @RunWith(ThrowsOnDiscoveryRunner.class) - @SuiteClasses({ One.class, Two.class }) - static class ThrowsOnDiscoverySuite { - - } - - public static class ThrowsOnDiscoveryRunner extends Suite { - - public ThrowsOnDiscoveryRunner(final Class klass, final RunnerBuilder rb) - throws InitializationError { - super(klass, rb); - } - - @Override - public Description getDescription() { - throw new RuntimeException(); - } - - } - - private Collection> findWithTestee(final Class clazz) { - return this.testee.apply(clazz); - } - - private void assertContains(final Collection> expected, - final Collection> actual) { - assertThat(actual).containsAll(expected); - } - -} +package org.pitest.junit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; + +import com.example.TheoryTest; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class RunnerSuiteFinderTest { + + private RunnerSuiteFinder testee; + + @Before + public void setup() { + this.testee = new RunnerSuiteFinder(); + } + + @Test + public void shouldNotFindClassesInJUnitTheoryTest() { + final Collection> actual = findWithTestee(TheoryTest.class); + assertTrue(actual.isEmpty()); + } + + public static class CustomSuiteRunner extends Suite { + + public CustomSuiteRunner(final Class klass, final RunnerBuilder rb) + throws InitializationError { + super(klass, rb); + } + + } + + public static class One extends TestCase { + public void testSomething() { + } + } + + public static class Two extends One { + } + + @RunWith(CustomSuiteRunner.class) + @SuiteClasses({ One.class, Two.class }) + static class CustomSuite { + + } + + @Test + public void shouldFindSuiteClassesInCustomSuite() { + final Collection> actual = findWithTestee(CustomSuite.class); + final Collection> expected = Arrays.> asList(One.class, + Two.class); + + assertContains(expected, actual); + } + + public static class JUnit3Suite extends TestCase { + public static junit.framework.Test suite() { + + final TestSuite suite = new TestSuite(); + suite.addTestSuite(One.class); + suite.addTestSuite(Two.class); + + return suite; + } + } + + @Test + public void shouldFindSuiteClassesInJUnit3Suite() { + final Collection> actual = findWithTestee(JUnit3Suite.class); + final Collection> expected = Arrays.> asList(One.class, + Two.class); + assertContains(expected, actual); + } + + public static class JUnit3SuiteMethod extends TestCase { + public JUnit3SuiteMethod(final String testName) { + super(testName); + } + + public static junit.framework.Test suite() { + final TestSuite suite = new TestSuite(); + suite.addTest(new One()); + suite.addTest(new Two()); + return suite; + } + + } + + @Test + public void shouldFindSuiteClassesInJUnit3SuiteMethod() { + final Collection> actual = findWithTestee(JUnit3SuiteMethod.class); + final Collection> expected = Arrays.> asList(One.class, + Two.class); + assertContains(expected, actual); + } + + @Test + public void shouldFindSuiteClasseInNestedJUnit3Suite() { + final Collection> actual = findWithTestee(com.example.JUnitThreeSuite.class); + final Collection> expected = Arrays + .> asList(com.example.JUnitThreeTest.class); + assertContains(expected, actual); + } + + @Test + public void shouldNotHaltWhenRunnerThrowsRuntimeException() { + try { + findWithTestee(ThrowsOnDiscoverySuite.class); + // pass + } catch(final RuntimeException ex) { + fail(); + } + } + + @RunWith(ThrowsOnDiscoveryRunner.class) + @SuiteClasses({ One.class, Two.class }) + static class ThrowsOnDiscoverySuite { + + } + + public static class ThrowsOnDiscoveryRunner extends Suite { + + public ThrowsOnDiscoveryRunner(final Class klass, final RunnerBuilder rb) + throws InitializationError { + super(klass, rb); + } + + @Override + public Description getDescription() { + throw new RuntimeException(); + } + + } + + private Collection> findWithTestee(final Class clazz) { + return this.testee.apply(clazz); + } + + private void assertContains(final Collection> expected, + final Collection> actual) { + assertThat(actual).containsAll(expected); + } + +} diff --git a/pitest/src/test/java/org/pitest/junit/TestInfoTest.java b/pitest/src/test/java/org/pitest/junit/TestInfoTest.java index d37203c26..a63206fd5 100644 --- a/pitest/src/test/java/org/pitest/junit/TestInfoTest.java +++ b/pitest/src/test/java/org/pitest/junit/TestInfoTest.java @@ -1,79 +1,79 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.junit; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classinfo.ClassInfo; -import org.pitest.classinfo.Repository; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.util.IsolationUtils; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class TestInfoTest { - - private Repository repository; - - @Before - public void setUp() { - this.repository = new Repository(new ClassloaderByteArraySource( - IsolationUtils.getContextClassLoader())); - } - - @Test - public void isATestShouldReturnTrueForJUnit3Tests() { - class JU3Test extends TestCase { - - } - assertTrue(TestInfo.isATest().test(fetchClass(JU3Test.class))); - } - - @Test - public void isATestShouldReturnTrueForJUnit3Suites() { - class JU3Test extends TestSuite { - - } - assertTrue(TestInfo.isATest().test(fetchClass(JU3Test.class))); - } - - @Test - public void isATestShouldReturnTrueForJUnit4Tests() { - assertTrue(TestInfo.isATest().test(fetchClass(TestInfoTest.class))); - } - - @Test - public void isATestShouldReturnFalseForNonTests() { - assertFalse(TestInfo.isATest().test(fetchClass(String.class))); - } - - static class Nested { - - } - - @Test - public void isWithinATestClassShouldReturnTrueForNestedClassesWithinATest() { - assertTrue(TestInfo.isWithinATestClass(fetchClass(Nested.class))); - } - - private ClassInfo fetchClass(final Class clazz) { - return this.repository.fetchClass(clazz).get(); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.junit; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classinfo.ClassInfo; +import org.pitest.classinfo.Repository; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.util.IsolationUtils; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class TestInfoTest { + + private Repository repository; + + @Before + public void setUp() { + this.repository = new Repository(new ClassloaderByteArraySource( + IsolationUtils.getContextClassLoader())); + } + + @Test + public void isATestShouldReturnTrueForJUnit3Tests() { + class JU3Test extends TestCase { + + } + assertTrue(TestInfo.isATest().test(fetchClass(JU3Test.class))); + } + + @Test + public void isATestShouldReturnTrueForJUnit3Suites() { + class JU3Test extends TestSuite { + + } + assertTrue(TestInfo.isATest().test(fetchClass(JU3Test.class))); + } + + @Test + public void isATestShouldReturnTrueForJUnit4Tests() { + assertTrue(TestInfo.isATest().test(fetchClass(TestInfoTest.class))); + } + + @Test + public void isATestShouldReturnFalseForNonTests() { + assertFalse(TestInfo.isATest().test(fetchClass(String.class))); + } + + static class Nested { + + } + + @Test + public void isWithinATestClassShouldReturnTrueForNestedClassesWithinATest() { + assertTrue(TestInfo.isWithinATestClass(fetchClass(Nested.class))); + } + + private ClassInfo fetchClass(final Class clazz) { + return this.repository.fetchClass(clazz).get(); + } + +} diff --git a/pitest/src/test/java/org/pitest/junit/adapter/AdaptedJUnitTestUnitTest.java b/pitest/src/test/java/org/pitest/junit/adapter/AdaptedJUnitTestUnitTest.java index 8149e0374..9d6e40361 100644 --- a/pitest/src/test/java/org/pitest/junit/adapter/AdaptedJUnitTestUnitTest.java +++ b/pitest/src/test/java/org/pitest/junit/adapter/AdaptedJUnitTestUnitTest.java @@ -1,110 +1,110 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.junit.adapter; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.manipulation.Filter; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import java.util.Optional; -import org.pitest.testapi.ResultCollector; - -public class AdaptedJUnitTestUnitTest { - - private AdaptedJUnitTestUnit testee; - - @Mock - ResultCollector rc; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - private static class HideFromJUnit { - - public static class JUnit4Test { - - @Test - public void pass() { - - } - - @Test - public void fail() { - org.junit.Assert.fail(); - } - - } - - } - - @Test - public void shouldCallNotifyStartWhenExecutingInOwnClassLoader() { - createTestee(HideFromJUnit.JUnit4Test.class, - "pass"); - this.testee.execute(this.rc); - verify(this.rc).notifyStart(this.testee.getDescription()); - } - - @Test - public void shouldCallNotifyEndOnSuccessWhenExecutingInOwnClassLoader() { - createTestee(HideFromJUnit.JUnit4Test.class, - "pass"); - this.testee.execute(this.rc); - verify(this.rc).notifyEnd(this.testee.getDescription()); - } - - @Test - public void shouldCallNotifyEndWithThrowableOnFailureWhenExecutingInOwnClassLoader() { - createTestee(HideFromJUnit.JUnit4Test.class, - "fail"); - this.testee.execute(this.rc); - verify(this.rc).notifyEnd(eq(this.testee.getDescription()), - any(Throwable.class)); - } - - private void createTestee( - final Class clazz, final String method) { - this.testee = new AdaptedJUnitTestUnit(clazz, - createFilter(clazz, method)); - } - - private Optional createFilter(final Class clazz, final String method) { - final Description d = Description.createTestDescription(clazz, method); - final Filter f = new Filter() { - - @Override - public boolean shouldRun(final Description description) { - return d.toString().equals(description.toString()); - } - - @Override - public String describe() { - return null; - } - - }; - return Optional.ofNullable(f); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.junit.adapter; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.manipulation.Filter; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import java.util.Optional; +import org.pitest.testapi.ResultCollector; + +public class AdaptedJUnitTestUnitTest { + + private AdaptedJUnitTestUnit testee; + + @Mock + ResultCollector rc; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + private static class HideFromJUnit { + + public static class JUnit4Test { + + @Test + public void pass() { + + } + + @Test + public void fail() { + org.junit.Assert.fail(); + } + + } + + } + + @Test + public void shouldCallNotifyStartWhenExecutingInOwnClassLoader() { + createTestee(HideFromJUnit.JUnit4Test.class, + "pass"); + this.testee.execute(this.rc); + verify(this.rc).notifyStart(this.testee.getDescription()); + } + + @Test + public void shouldCallNotifyEndOnSuccessWhenExecutingInOwnClassLoader() { + createTestee(HideFromJUnit.JUnit4Test.class, + "pass"); + this.testee.execute(this.rc); + verify(this.rc).notifyEnd(this.testee.getDescription()); + } + + @Test + public void shouldCallNotifyEndWithThrowableOnFailureWhenExecutingInOwnClassLoader() { + createTestee(HideFromJUnit.JUnit4Test.class, + "fail"); + this.testee.execute(this.rc); + verify(this.rc).notifyEnd(eq(this.testee.getDescription()), + any(Throwable.class)); + } + + private void createTestee( + final Class clazz, final String method) { + this.testee = new AdaptedJUnitTestUnit(clazz, + createFilter(clazz, method)); + } + + private Optional createFilter(final Class clazz, final String method) { + final Description d = Description.createTestDescription(clazz, method); + final Filter f = new Filter() { + + @Override + public boolean shouldRun(final Description description) { + return d.toString().equals(description.toString()); + } + + @Override + public String describe() { + return null; + } + + }; + return Optional.ofNullable(f); + } + +} diff --git a/pitest/src/test/java/org/pitest/junit/adapter/AdaptingRunListenerTest.java b/pitest/src/test/java/org/pitest/junit/adapter/AdaptingRunListenerTest.java index 77dc375d6..63bed84e1 100644 --- a/pitest/src/test/java/org/pitest/junit/adapter/AdaptingRunListenerTest.java +++ b/pitest/src/test/java/org/pitest/junit/adapter/AdaptingRunListenerTest.java @@ -1,94 +1,94 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.junit.adapter; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.StoppedByUserException; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.DescriptionMother; -import org.pitest.testapi.ResultCollector; - -public class AdaptingRunListenerTest { - - private AdaptingRunListener testee; - - private org.pitest.testapi.Description pitDescription; - - private Throwable throwable; - - @Mock - private Description junitDesc; - - @Mock - private ResultCollector rc; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.throwable = new NullPointerException(); - this.pitDescription = DescriptionMother.createEmptyDescription("foo"); - this.testee = new AdaptingRunListener(this.pitDescription, this.rc); - } - - @Test - public void shouldReportExceptionOnFailure() throws Exception { - this.testee.testFailure(new Failure(this.junitDesc, this.throwable)); - verify(this.rc).notifyEnd(this.pitDescription, this.throwable); - } - - @Test - public void shouldNotReportTestEndWithoutErrorAfterFailure() throws Exception { - this.testee.testFailure(new Failure(this.junitDesc, this.throwable)); - this.testee.testFinished(this.junitDesc); - verify(this.rc, never()).notifyEnd(this.pitDescription); - } - - @Test - public void shouldTreatAssumptionFailureAsSuccess() throws Exception { - this.testee.testAssumptionFailure(new Failure(this.junitDesc, - this.throwable)); - verify(this.rc, never()).notifyEnd(this.pitDescription, this.throwable); - this.testee.testFinished(this.junitDesc); - verify(this.rc).notifyEnd(this.pitDescription); - } - - @Test - public void shouldReportIgnoredTestsAsSkipped() throws Exception { - this.testee.testIgnored(this.junitDesc); - verify(this.rc).notifySkipped(this.pitDescription); - } - - @Test - public void shouldReportStartedTests() throws Exception { - this.testee.testStarted(this.junitDesc); - verify(this.rc).notifyStart(this.pitDescription); - } - - @Test(expected = StoppedByUserException.class) - public void shouldRunStoppedByUserExceptionIfMoreTestsRunAfterAFailure() - throws Exception { - this.testee.testFailure(new Failure(this.junitDesc, this.throwable)); - this.testee.testStarted(this.junitDesc); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.junit.adapter; + +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.StoppedByUserException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.DescriptionMother; +import org.pitest.testapi.ResultCollector; + +public class AdaptingRunListenerTest { + + private AdaptingRunListener testee; + + private org.pitest.testapi.Description pitDescription; + + private Throwable throwable; + + @Mock + private Description junitDesc; + + @Mock + private ResultCollector rc; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.throwable = new NullPointerException(); + this.pitDescription = DescriptionMother.createEmptyDescription("foo"); + this.testee = new AdaptingRunListener(this.pitDescription, this.rc); + } + + @Test + public void shouldReportExceptionOnFailure() throws Exception { + this.testee.testFailure(new Failure(this.junitDesc, this.throwable)); + verify(this.rc).notifyEnd(this.pitDescription, this.throwable); + } + + @Test + public void shouldNotReportTestEndWithoutErrorAfterFailure() throws Exception { + this.testee.testFailure(new Failure(this.junitDesc, this.throwable)); + this.testee.testFinished(this.junitDesc); + verify(this.rc, never()).notifyEnd(this.pitDescription); + } + + @Test + public void shouldTreatAssumptionFailureAsSuccess() throws Exception { + this.testee.testAssumptionFailure(new Failure(this.junitDesc, + this.throwable)); + verify(this.rc, never()).notifyEnd(this.pitDescription, this.throwable); + this.testee.testFinished(this.junitDesc); + verify(this.rc).notifyEnd(this.pitDescription); + } + + @Test + public void shouldReportIgnoredTestsAsSkipped() throws Exception { + this.testee.testIgnored(this.junitDesc); + verify(this.rc).notifySkipped(this.pitDescription); + } + + @Test + public void shouldReportStartedTests() throws Exception { + this.testee.testStarted(this.junitDesc); + verify(this.rc).notifyStart(this.pitDescription); + } + + @Test(expected = StoppedByUserException.class) + public void shouldRunStoppedByUserExceptionIfMoreTestsRunAfterAFailure() + throws Exception { + this.testee.testFailure(new Failure(this.junitDesc, this.throwable)); + this.testee.testStarted(this.junitDesc); + } + +} diff --git a/pitest/src/test/java/org/pitest/junit/adapter/CustomRunnerExecutorTest.java b/pitest/src/test/java/org/pitest/junit/adapter/CustomRunnerExecutorTest.java index 57a5cddb6..5a3a387fa 100644 --- a/pitest/src/test/java/org/pitest/junit/adapter/CustomRunnerExecutorTest.java +++ b/pitest/src/test/java/org/pitest/junit/adapter/CustomRunnerExecutorTest.java @@ -1,53 +1,53 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.junit.adapter; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.Runner; -import org.junit.runner.notification.RunNotifier; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.DescriptionMother; -import org.pitest.testapi.ResultCollector; - -public class CustomRunnerExecutorTest { - - private CustomRunnerExecutor testee; - - @Mock - private Runner runner; - - @Mock - private ResultCollector rc; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new CustomRunnerExecutor( - DescriptionMother.createEmptyDescription("foo"), this.runner, this.rc); - } - - @Test - public void shouldExecuteTheSuppliedRunner() { - this.testee.run(); - verify(this.runner).run(any(RunNotifier.class)); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.junit.adapter; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.Runner; +import org.junit.runner.notification.RunNotifier; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.DescriptionMother; +import org.pitest.testapi.ResultCollector; + +public class CustomRunnerExecutorTest { + + private CustomRunnerExecutor testee; + + @Mock + private Runner runner; + + @Mock + private ResultCollector rc; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new CustomRunnerExecutor( + DescriptionMother.createEmptyDescription("foo"), this.runner, this.rc); + } + + @Test + public void shouldExecuteTheSuppliedRunner() { + this.testee.run(); + verify(this.runner).run(any(RunNotifier.class)); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/DetectionStatusTest.java b/pitest/src/test/java/org/pitest/mutationtest/DetectionStatusTest.java index f6b55efa4..34b7f68a6 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/DetectionStatusTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/DetectionStatusTest.java @@ -1,89 +1,89 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.pitest.util.ExitCode; - -public class DetectionStatusTest { - - @Test - public void shouldConsiderKilledMutationsToBeDetected() { - assertTrue(DetectionStatus.KILLED.isDetected()); - } - - @Test - public void shouldConsiderSurvivingMutationsToBeUnDetected() { - assertFalse(DetectionStatus.SURVIVED.isDetected()); - } - - @Test - public void shouldConsiderTimedOutMutationsToBeDetected() { - assertTrue(DetectionStatus.TIMED_OUT.isDetected()); - } - - @Test - public void shouldConsiderNonViableMutationsToBeDetected() { - assertTrue(DetectionStatus.NON_VIABLE.isDetected()); - } - - @Test - public void shouldConsiderMemoryErrorsAsDetected() { - assertTrue(DetectionStatus.MEMORY_ERROR.isDetected()); - } - - @Test - public void shouldConsiderUnAnalysedMutationsAsUnDetected() { - assertFalse(DetectionStatus.NOT_STARTED.isDetected()); - } - - @Test - public void shouldConsiderUnfinishedAnalysAsUnDetected() { - assertFalse(DetectionStatus.STARTED.isDetected()); - } - - @Test - public void shouldConsiderRunErrorAsDetected() { - // really? dubious - assertTrue(DetectionStatus.RUN_ERROR.isDetected()); - } - - @Test - public void shouldConsiderUnCoveredKilledMutationsToBeUnDetected() { - assertFalse(DetectionStatus.NO_COVERAGE.isDetected()); - } - - @Test - public void shouldConverytutOfMemoryExitCode() { - assertEquals(DetectionStatus.MEMORY_ERROR, - DetectionStatus.getForErrorExitCode(ExitCode.OUT_OF_MEMORY)); - } - - @Test - public void shouldConvertTimeOutExitCode() { - assertEquals(DetectionStatus.TIMED_OUT, - DetectionStatus.getForErrorExitCode(ExitCode.TIMEOUT)); - } - - @Test - public void shouldConvertUnknownErrorExitCode() { - assertEquals(DetectionStatus.RUN_ERROR, - DetectionStatus.getForErrorExitCode(ExitCode.UNKNOWN_ERROR)); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.pitest.util.ExitCode; + +public class DetectionStatusTest { + + @Test + public void shouldConsiderKilledMutationsToBeDetected() { + assertTrue(DetectionStatus.KILLED.isDetected()); + } + + @Test + public void shouldConsiderSurvivingMutationsToBeUnDetected() { + assertFalse(DetectionStatus.SURVIVED.isDetected()); + } + + @Test + public void shouldConsiderTimedOutMutationsToBeDetected() { + assertTrue(DetectionStatus.TIMED_OUT.isDetected()); + } + + @Test + public void shouldConsiderNonViableMutationsToBeDetected() { + assertTrue(DetectionStatus.NON_VIABLE.isDetected()); + } + + @Test + public void shouldConsiderMemoryErrorsAsDetected() { + assertTrue(DetectionStatus.MEMORY_ERROR.isDetected()); + } + + @Test + public void shouldConsiderUnAnalysedMutationsAsUnDetected() { + assertFalse(DetectionStatus.NOT_STARTED.isDetected()); + } + + @Test + public void shouldConsiderUnfinishedAnalysAsUnDetected() { + assertFalse(DetectionStatus.STARTED.isDetected()); + } + + @Test + public void shouldConsiderRunErrorAsDetected() { + // really? dubious + assertTrue(DetectionStatus.RUN_ERROR.isDetected()); + } + + @Test + public void shouldConsiderUnCoveredKilledMutationsToBeUnDetected() { + assertFalse(DetectionStatus.NO_COVERAGE.isDetected()); + } + + @Test + public void shouldConverytutOfMemoryExitCode() { + assertEquals(DetectionStatus.MEMORY_ERROR, + DetectionStatus.getForErrorExitCode(ExitCode.OUT_OF_MEMORY)); + } + + @Test + public void shouldConvertTimeOutExitCode() { + assertEquals(DetectionStatus.TIMED_OUT, + DetectionStatus.getForErrorExitCode(ExitCode.TIMEOUT)); + } + + @Test + public void shouldConvertUnknownErrorExitCode() { + assertEquals(DetectionStatus.RUN_ERROR, + DetectionStatus.getForErrorExitCode(ExitCode.UNKNOWN_ERROR)); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/LocationMother.java b/pitest/src/test/java/org/pitest/mutationtest/LocationMother.java index 692ac1204..698ed9add 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/LocationMother.java +++ b/pitest/src/test/java/org/pitest/mutationtest/LocationMother.java @@ -1,71 +1,71 @@ -package org.pitest.mutationtest; - -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.Location; -import org.pitest.mutationtest.engine.MethodName; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.quickbuilder.Builder; -import org.pitest.quickbuilder.Generator; -import org.pitest.quickbuilder.SequenceBuilder; -import org.pitest.quickbuilder.builders.QB; - -public class LocationMother { - - public interface MutationIdentifierBuilder extends - SequenceBuilder { - - MutationIdentifierBuilder withLocation(Location location); - - MutationIdentifierBuilder withLocation(Builder location); - - MutationIdentifierBuilder withIndex(int index); - - MutationIdentifierBuilder withMutator(String mutator); - - Location _Location(); - - int _Index(); - - String _Mutator(); - - } - - public interface LocationBuilder extends SequenceBuilder { - LocationBuilder withClass(ClassName clazz); - - LocationBuilder withMethod(String method); - - LocationBuilder withMethodDescription(String methodDesc); - - ClassName _Class(); - - String _Method(); - - String _MethodDescription(); - - } - - public static LocationBuilder aLocation(String clazz) { - return aLocation().withClass(ClassName.fromString(clazz)); - } - - public static LocationBuilder aLocation() { - return QB.builder(LocationBuilder.class, locationSeed()) - .withClass(ClassName.fromString("clazz")).withMethod("method") - .withMethodDescription("()I"); - } - - private static Generator locationSeed() { - return b -> Location.location(b._Class(), - MethodName.fromString(b._Method()), b._MethodDescription()); - } - - public static MutationIdentifierBuilder aMutationId() { - return QB.builder(MutationIdentifierBuilder.class, idSeed()) - .withLocation(aLocation()).withIndex(1).withMutator("mutator"); - } - - private static Generator idSeed() { - return b -> new MutationIdentifier(b._Location(), b._Index(), b._Mutator()); - } -} +package org.pitest.mutationtest; + +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.Location; +import org.pitest.mutationtest.engine.MethodName; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.quickbuilder.Builder; +import org.pitest.quickbuilder.Generator; +import org.pitest.quickbuilder.SequenceBuilder; +import org.pitest.quickbuilder.builders.QB; + +public class LocationMother { + + public interface MutationIdentifierBuilder extends + SequenceBuilder { + + MutationIdentifierBuilder withLocation(Location location); + + MutationIdentifierBuilder withLocation(Builder location); + + MutationIdentifierBuilder withIndex(int index); + + MutationIdentifierBuilder withMutator(String mutator); + + Location _Location(); + + int _Index(); + + String _Mutator(); + + } + + public interface LocationBuilder extends SequenceBuilder { + LocationBuilder withClass(ClassName clazz); + + LocationBuilder withMethod(String method); + + LocationBuilder withMethodDescription(String methodDesc); + + ClassName _Class(); + + String _Method(); + + String _MethodDescription(); + + } + + public static LocationBuilder aLocation(String clazz) { + return aLocation().withClass(ClassName.fromString(clazz)); + } + + public static LocationBuilder aLocation() { + return QB.builder(LocationBuilder.class, locationSeed()) + .withClass(ClassName.fromString("clazz")).withMethod("method") + .withMethodDescription("()I"); + } + + private static Generator locationSeed() { + return b -> Location.location(b._Class(), + MethodName.fromString(b._Method()), b._MethodDescription()); + } + + public static MutationIdentifierBuilder aMutationId() { + return QB.builder(MutationIdentifierBuilder.class, idSeed()) + .withLocation(aLocation()).withIndex(1).withMutator("mutator"); + } + + private static Generator idSeed() { + return b -> new MutationIdentifier(b._Location(), b._Index(), b._Mutator()); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/Mutable.java b/pitest/src/test/java/org/pitest/mutationtest/Mutable.java index 50f359a11..79b962204 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/Mutable.java +++ b/pitest/src/test/java/org/pitest/mutationtest/Mutable.java @@ -1,36 +1,36 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -public class Mutable { - - public static int returnOne() { - return 1; - } - - public static int switchStatement(final int value) { - switch (value) { - case 1: - return 1; - case 2: - return 2; - case 3: - return 3; - default: - return 4; - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +public class Mutable { + + public static int returnOne() { + return 1; + } + + public static int switchStatement(final int value) { + switch (value) { + case 1: + return 1; + case 2: + return 2; + case 3: + return 3; + default: + return 4; + } + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/MutableIncrement.java b/pitest/src/test/java/org/pitest/mutationtest/MutableIncrement.java index 0d4634617..514d2d8da 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/MutableIncrement.java +++ b/pitest/src/test/java/org/pitest/mutationtest/MutableIncrement.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest; - -public class MutableIncrement { - - public static int increment() { - int i = 42; - i++; - return i; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest; + +public class MutableIncrement { + + public static int increment() { + int i = 42; + i++; + return i; + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/MutationStatusTestPairTest.java b/pitest/src/test/java/org/pitest/mutationtest/MutationStatusTestPairTest.java index 89c86b91c..2b7e3932f 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/MutationStatusTestPairTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/MutationStatusTestPairTest.java @@ -1,14 +1,14 @@ -package org.pitest.mutationtest; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class MutationStatusTestPairTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(MutationStatusTestPair.class).verify(); - } - -} +package org.pitest.mutationtest; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class MutationStatusTestPairTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(MutationStatusTestPair.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/build/PercentAndConstantTimeoutStrategyTest.java b/pitest/src/test/java/org/pitest/mutationtest/build/PercentAndConstantTimeoutStrategyTest.java index 3db28137a..f2b17da60 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/build/PercentAndConstantTimeoutStrategyTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/build/PercentAndConstantTimeoutStrategyTest.java @@ -1,34 +1,34 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.build; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class PercentAndConstantTimeoutStrategyTest { - - private PercentAndConstantTimeoutStrategy testee; - - @Test - public void shouldReturnProductOfFactorAnTestTimePlusConstant() { - final long time = 1; - this.testee = new PercentAndConstantTimeoutStrategy(1.2f, 666); - assertEquals((Math.round(1.2f * time) + 666), - this.testee.getAllowedTime(time)); - - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.build; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class PercentAndConstantTimeoutStrategyTest { + + private PercentAndConstantTimeoutStrategy testee; + + @Test + public void shouldReturnProductOfFactorAnTestTimePlusConstant() { + final long time = 1; + this.testee = new PercentAndConstantTimeoutStrategy(1.2f, 666); + assertEquals((Math.round(1.2f * time) + 666), + this.testee.getAllowedTime(time)); + + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/LocationTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/LocationTest.java index 38b26eeab..40db3bd0b 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/LocationTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/LocationTest.java @@ -1,37 +1,37 @@ -package org.pitest.mutationtest.engine; - -import static org.junit.Assert.assertEquals; -import static org.pitest.mutationtest.engine.Location.location; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; -import org.pitest.classinfo.ClassName; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class LocationTest { - - @Test - public void shouldSortInConsistantOrder() { - final Location a = location(ClassName.fromString("A"), - MethodName.fromString("A"), "A"); - final Location b = location(ClassName.fromString("AA"), - MethodName.fromString("A"), "A"); - final Location c = location(ClassName.fromString("A"), - MethodName.fromString("AA"), "A"); - final Location d = location(ClassName.fromString("A"), - MethodName.fromString("AA"), "AA"); - final List ls = Arrays.asList(a, b, c, d); - Collections.sort(ls); - assertEquals(Arrays.asList(a, c, d, b), ls); - } - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(Location.class).verify(); - } - -} +package org.pitest.mutationtest.engine; + +import static org.junit.Assert.assertEquals; +import static org.pitest.mutationtest.engine.Location.location; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; +import org.pitest.classinfo.ClassName; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class LocationTest { + + @Test + public void shouldSortInConsistantOrder() { + final Location a = location(ClassName.fromString("A"), + MethodName.fromString("A"), "A"); + final Location b = location(ClassName.fromString("AA"), + MethodName.fromString("A"), "A"); + final Location c = location(ClassName.fromString("A"), + MethodName.fromString("AA"), "A"); + final Location d = location(ClassName.fromString("A"), + MethodName.fromString("AA"), "AA"); + final List ls = Arrays.asList(a, b, c, d); + Collections.sort(ls); + assertEquals(Arrays.asList(a, c, d, b), ls); + } + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(Location.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/MutationDetailsMother.java b/pitest/src/test/java/org/pitest/mutationtest/engine/MutationDetailsMother.java index 384e6cddf..fdbcd522e 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/MutationDetailsMother.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/MutationDetailsMother.java @@ -1,81 +1,81 @@ -package org.pitest.mutationtest.engine; - -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.Collections; -import java.util.List; - -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.TestInfo; -import org.pitest.quickbuilder.Builder; -import org.pitest.quickbuilder.Generator; -import org.pitest.quickbuilder.SequenceBuilder; -import org.pitest.quickbuilder.builders.QB; - -public class MutationDetailsMother { - - public interface MutationDetailsBuilder extends - SequenceBuilder { - MutationDetailsBuilder withId(Builder id); - - MutationDetailsBuilder withId(MutationIdentifier id); - - MutationDetailsBuilder withFilename(String filename); - - MutationDetailsBuilder withBlock(int block); - - MutationDetailsBuilder withLineNumber(int lineNumber); - - MutationDetailsBuilder withDescription(String desc); - - MutationDetailsBuilder withTestsInOrder(List tests); - - MutationDetailsBuilder withIsInFinallyBlock(boolean b); - - MutationDetailsBuilder withPoison(PoisonStatus b); - - MutationIdentifier _Id(); - - String _Filename(); - - int _Block(); - - int _LineNumber(); - - String _Description(); - - boolean _IsInFinallyBlock(); - - PoisonStatus _Poison(); - - List _TestsInOrder(); - } - - public static MutationDetailsBuilder aMutationDetail() { - return QB.builder(MutationDetailsBuilder.class, seed()).withBlock(0) - .withDescription("A mutation").withFilename("foo.java") - .withId(aMutationId()).withLineNumber(42).withIsInFinallyBlock(false) - .withPoison(PoisonStatus.NORMAL).withTestsInOrder(Collections. emptyList()); - } - - private static Generator seed() { - return b -> { - final MutationDetails md = new MutationDetails(b._Id(), b._Filename(), - b._Description(), b._LineNumber(), b._Block(), - b._IsInFinallyBlock(), b._Poison()); - md.addTestsInOrder(b._TestsInOrder()); - return md; - }; - } - - public static MutationDetails makeMutation() { - return makeMutation(ClassName.fromString("foo")); - } - - public static MutationDetails makeMutation(final ClassName clazz) { - return new MutationDetails(new MutationIdentifier(Location.location(clazz, - new MethodName("aMethod"), "()V"), 1, "mutatorId"), "foo.java", - "A mutation", 0, 0); - } - -} +package org.pitest.mutationtest.engine; + +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.Collections; +import java.util.List; + +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.TestInfo; +import org.pitest.quickbuilder.Builder; +import org.pitest.quickbuilder.Generator; +import org.pitest.quickbuilder.SequenceBuilder; +import org.pitest.quickbuilder.builders.QB; + +public class MutationDetailsMother { + + public interface MutationDetailsBuilder extends + SequenceBuilder { + MutationDetailsBuilder withId(Builder id); + + MutationDetailsBuilder withId(MutationIdentifier id); + + MutationDetailsBuilder withFilename(String filename); + + MutationDetailsBuilder withBlock(int block); + + MutationDetailsBuilder withLineNumber(int lineNumber); + + MutationDetailsBuilder withDescription(String desc); + + MutationDetailsBuilder withTestsInOrder(List tests); + + MutationDetailsBuilder withIsInFinallyBlock(boolean b); + + MutationDetailsBuilder withPoison(PoisonStatus b); + + MutationIdentifier _Id(); + + String _Filename(); + + int _Block(); + + int _LineNumber(); + + String _Description(); + + boolean _IsInFinallyBlock(); + + PoisonStatus _Poison(); + + List _TestsInOrder(); + } + + public static MutationDetailsBuilder aMutationDetail() { + return QB.builder(MutationDetailsBuilder.class, seed()).withBlock(0) + .withDescription("A mutation").withFilename("foo.java") + .withId(aMutationId()).withLineNumber(42).withIsInFinallyBlock(false) + .withPoison(PoisonStatus.NORMAL).withTestsInOrder(Collections. emptyList()); + } + + private static Generator seed() { + return b -> { + final MutationDetails md = new MutationDetails(b._Id(), b._Filename(), + b._Description(), b._LineNumber(), b._Block(), + b._IsInFinallyBlock(), b._Poison()); + md.addTestsInOrder(b._TestsInOrder()); + return md; + }; + } + + public static MutationDetails makeMutation() { + return makeMutation(ClassName.fromString("foo")); + } + + public static MutationDetails makeMutation(final ClassName clazz) { + return new MutationDetails(new MutationIdentifier(Location.location(clazz, + new MethodName("aMethod"), "()V"), 1, "mutatorId"), "foo.java", + "A mutation", 0, 0); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/MutationDetailsTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/MutationDetailsTest.java index cc475aab8..c11d0d512 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/MutationDetailsTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/MutationDetailsTest.java @@ -1,35 +1,35 @@ -package org.pitest.mutationtest.engine; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class MutationDetailsTest { - - @Test - public void shouldCreateNewCopyWithUpdatedPoisonStatusForStaticInitializerMarking() { - final MutationDetails testee = MutationDetailsMother.aMutationDetail().build(); - - final MutationDetails actual = testee.withPoisonStatus(PoisonStatus.IS_STATIC_INITIALIZER_CODE); - assertThat(actual).isNotSameAs(testee); - assertThat(actual.mayPoisonJVM()).isTrue(); - assertThat(actual.isInStaticInitializer()).isTrue(); - } - - @Test - public void shouldCreateNewCopyWithUpdatedPoisonStatusForJVMPoisoningMarking() { - final MutationDetails testee = MutationDetailsMother.aMutationDetail().build(); - - final MutationDetails actual = testee.withPoisonStatus(PoisonStatus.MAY_POISON_JVM); - assertThat(actual).isNotSameAs(testee); - assertThat(actual.mayPoisonJVM()).isTrue(); - } - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(MutationDetails.class).verify(); - } - -} +package org.pitest.mutationtest.engine; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class MutationDetailsTest { + + @Test + public void shouldCreateNewCopyWithUpdatedPoisonStatusForStaticInitializerMarking() { + final MutationDetails testee = MutationDetailsMother.aMutationDetail().build(); + + final MutationDetails actual = testee.withPoisonStatus(PoisonStatus.IS_STATIC_INITIALIZER_CODE); + assertThat(actual).isNotSameAs(testee); + assertThat(actual.mayPoisonJVM()).isTrue(); + assertThat(actual.isInStaticInitializer()).isTrue(); + } + + @Test + public void shouldCreateNewCopyWithUpdatedPoisonStatusForJVMPoisoningMarking() { + final MutationDetails testee = MutationDetailsMother.aMutationDetail().build(); + + final MutationDetails actual = testee.withPoisonStatus(PoisonStatus.MAY_POISON_JVM); + assertThat(actual).isNotSameAs(testee); + assertThat(actual.mayPoisonJVM()).isTrue(); + } + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(MutationDetails.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/MutationIdentifierTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/MutationIdentifierTest.java index ec08e8480..25f3d28de 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/MutationIdentifierTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/MutationIdentifierTest.java @@ -1,131 +1,131 @@ -package org.pitest.mutationtest.engine; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.pitest.mutationtest.LocationMother.aLocation; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class MutationIdentifierTest { - - @Test - public void shouldEqualSelf() { - final MutationIdentifier a = aMutationId().withIndex(1).withMutator("M").build(); - assertTrue(a.equals(a)); - } - - @Test - public void shouldBeUnEqualWhenIndexDiffers() { - final MutationIdentifier a = aMutationId().withIndex(1).build(); - final MutationIdentifier b = aMutationId().withIndex(2).build(); - assertFalse(a.equals(b)); - assertFalse(b.equals(a)); - } - - @Test - public void shouldBeUnEqualWhenMutatorDiffers() { - final MutationIdentifier a = aMutationId().withMutator("FOO").build(); - final MutationIdentifier b = aMutationId().withMutator("BAR").build(); - assertFalse(a.equals(b)); - assertFalse(b.equals(a)); - } - - @Test - public void shouldBeUnEqualWhenLocationDiffers() { - final MutationIdentifier a = aMutationId().withLocation( - aLocation().withMethod("FOO")).build(); - final MutationIdentifier b = aMutationId().withLocation( - aLocation().withMethod("BAR")).build(); - assertFalse(a.equals(b)); - assertFalse(b.equals(a)); - } - - @Test - public void shouldHaveSymmetricEqulasImplementation() { - final MutationIdentifier a = aMutationId().withIndex(1).withMutator("M").build(); - final MutationIdentifier b = aMutationId().withIndex(1).withMutator("M").build(); - assertTrue(a.equals(b)); - assertTrue(b.equals(a)); - assertTrue(a.hashCode() == b.hashCode()); - } - - @Test - public void shouldMatchWhenObjectsAreEqual() { - final MutationIdentifier a = aMutationId().build(); - final MutationIdentifier b = aMutationId().build(); - assertTrue(a.matches(b)); - } - - @Test - public void shouldMatchWhenIndexesOverlap() { - final MutationIdentifier a = new MutationIdentifier(aLocation().build(), - new HashSet<>(Arrays.asList(1, 2)), "M"); - final MutationIdentifier b = new MutationIdentifier(aLocation().build(), 1, "M"); - assertTrue(a.matches(b)); - } - - @Test - public void shouldNotMatchWhenIndexesDoNotOverlap() { - final MutationIdentifier a = new MutationIdentifier(aLocation().build(), - new HashSet(100, 200), "M"); - final MutationIdentifier b = new MutationIdentifier(aLocation().build(), 1, "M"); - assertFalse(a.matches(b)); - } - - @Test - public void shouldNotMatchWhenMutatorsDiffer() { - final MutationIdentifier a = aMutationId().withMutator("A").build(); - final MutationIdentifier b = aMutationId().withMutator("XXXX").build(); - assertFalse(a.matches(b)); - } - - @Test - public void shouldNotMatchWhenIndexesDiffer() { - final MutationIdentifier a = aMutationId().withIndex(1).build(); - final MutationIdentifier b = aMutationId().withIndex(100).build(); - assertFalse(a.matches(b)); - } - - @Test - public void shouldNotMatchWhenLocationsDiffer() { - final MutationIdentifier a = new MutationIdentifier(aLocation() - .withMethodDescription("X").build(), 1, "M"); - final MutationIdentifier b = new MutationIdentifier(aLocation() - .withMethodDescription("Y").build(), 1, "M"); - assertFalse(a.matches(b)); - } - - @Test - public void shouldSortInConsistantOrder() { - final MutationIdentifier a = aMutationId().withIndex(1).withMutator("A").build(); - final MutationIdentifier b = aMutationId().withIndex(1).withMutator("Z").build(); - final MutationIdentifier c = aMutationId().withIndex(1).withMutator("AA").build(); - final MutationIdentifier d = aMutationId().withIndex(3).withMutator("AA").build(); - final MutationIdentifier e = aMutationId() - .withLocation(aLocation().withMethod("a")).withIndex(3) - .withMutator("AA").build(); - List mis = Arrays.asList(a, b, c, d, e); - Collections.sort(mis); - final List expectedOrder = Arrays.asList(e, a, c, d, b); - assertEquals(expectedOrder, mis); - mis = Arrays.asList(e, b, d, a, c); - Collections.sort(mis); - assertEquals(expectedOrder, mis); - - } - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(MutationIdentifier.class).verify(); - } - -} +package org.pitest.mutationtest.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.pitest.mutationtest.LocationMother.aLocation; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class MutationIdentifierTest { + + @Test + public void shouldEqualSelf() { + final MutationIdentifier a = aMutationId().withIndex(1).withMutator("M").build(); + assertTrue(a.equals(a)); + } + + @Test + public void shouldBeUnEqualWhenIndexDiffers() { + final MutationIdentifier a = aMutationId().withIndex(1).build(); + final MutationIdentifier b = aMutationId().withIndex(2).build(); + assertFalse(a.equals(b)); + assertFalse(b.equals(a)); + } + + @Test + public void shouldBeUnEqualWhenMutatorDiffers() { + final MutationIdentifier a = aMutationId().withMutator("FOO").build(); + final MutationIdentifier b = aMutationId().withMutator("BAR").build(); + assertFalse(a.equals(b)); + assertFalse(b.equals(a)); + } + + @Test + public void shouldBeUnEqualWhenLocationDiffers() { + final MutationIdentifier a = aMutationId().withLocation( + aLocation().withMethod("FOO")).build(); + final MutationIdentifier b = aMutationId().withLocation( + aLocation().withMethod("BAR")).build(); + assertFalse(a.equals(b)); + assertFalse(b.equals(a)); + } + + @Test + public void shouldHaveSymmetricEqulasImplementation() { + final MutationIdentifier a = aMutationId().withIndex(1).withMutator("M").build(); + final MutationIdentifier b = aMutationId().withIndex(1).withMutator("M").build(); + assertTrue(a.equals(b)); + assertTrue(b.equals(a)); + assertTrue(a.hashCode() == b.hashCode()); + } + + @Test + public void shouldMatchWhenObjectsAreEqual() { + final MutationIdentifier a = aMutationId().build(); + final MutationIdentifier b = aMutationId().build(); + assertTrue(a.matches(b)); + } + + @Test + public void shouldMatchWhenIndexesOverlap() { + final MutationIdentifier a = new MutationIdentifier(aLocation().build(), + new HashSet<>(Arrays.asList(1, 2)), "M"); + final MutationIdentifier b = new MutationIdentifier(aLocation().build(), 1, "M"); + assertTrue(a.matches(b)); + } + + @Test + public void shouldNotMatchWhenIndexesDoNotOverlap() { + final MutationIdentifier a = new MutationIdentifier(aLocation().build(), + new HashSet(100, 200), "M"); + final MutationIdentifier b = new MutationIdentifier(aLocation().build(), 1, "M"); + assertFalse(a.matches(b)); + } + + @Test + public void shouldNotMatchWhenMutatorsDiffer() { + final MutationIdentifier a = aMutationId().withMutator("A").build(); + final MutationIdentifier b = aMutationId().withMutator("XXXX").build(); + assertFalse(a.matches(b)); + } + + @Test + public void shouldNotMatchWhenIndexesDiffer() { + final MutationIdentifier a = aMutationId().withIndex(1).build(); + final MutationIdentifier b = aMutationId().withIndex(100).build(); + assertFalse(a.matches(b)); + } + + @Test + public void shouldNotMatchWhenLocationsDiffer() { + final MutationIdentifier a = new MutationIdentifier(aLocation() + .withMethodDescription("X").build(), 1, "M"); + final MutationIdentifier b = new MutationIdentifier(aLocation() + .withMethodDescription("Y").build(), 1, "M"); + assertFalse(a.matches(b)); + } + + @Test + public void shouldSortInConsistantOrder() { + final MutationIdentifier a = aMutationId().withIndex(1).withMutator("A").build(); + final MutationIdentifier b = aMutationId().withIndex(1).withMutator("Z").build(); + final MutationIdentifier c = aMutationId().withIndex(1).withMutator("AA").build(); + final MutationIdentifier d = aMutationId().withIndex(3).withMutator("AA").build(); + final MutationIdentifier e = aMutationId() + .withLocation(aLocation().withMethod("a")).withIndex(3) + .withMutator("AA").build(); + List mis = Arrays.asList(a, b, c, d, e); + Collections.sort(mis); + final List expectedOrder = Arrays.asList(e, a, c, d, b); + assertEquals(expectedOrder, mis); + mis = Arrays.asList(e, b, d, a, c); + Collections.sort(mis); + assertEquals(expectedOrder, mis); + + } + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(MutationIdentifier.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/AvoidAssertsMethodAdapterTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/AvoidAssertsMethodAdapterTest.java index 1c1cb564b..52e64e777 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/AvoidAssertsMethodAdapterTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/AvoidAssertsMethodAdapterTest.java @@ -1,122 +1,122 @@ -package org.pitest.mutationtest.engine.gregor; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.bytecode.MethodDecoratorTest; - -public class AvoidAssertsMethodAdapterTest extends MethodDecoratorTest { - - @Mock - private MethodMutationContext context; - - @Mock - private Label label; - - private AvoidAssertsMethodAdapter testee; - - @Override - @Before - public void setUp() { - super.setUp(); - this.testee = new AvoidAssertsMethodAdapter(this.context, this.mv); - } - - @Test - public void shouldDisableMutationsWhenAssertionDisabledFlagIsChecked() { - this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", - "Z"); - verify(this.context).disableMutations(anyString()); - } - - @Test - public void shouldEnableMutationsWhenReachLabelOfFirstIFNEAfterCheckingAssertionDisabledFlag() { - this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", - "Z"); - this.testee.visitJumpInsn(Opcodes.IFNE, this.label); - this.testee.visitLabel(this.label); - verify(this.context).enableMutatations(anyString()); - } - - @Test - public void shouldNotEnableMutationsWhenNonAssertionCheckLabelReached() { - final Label anotherLabel = Mockito.mock(Label.class); - this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", - "Z"); - this.testee.visitJumpInsn(Opcodes.IFNE, this.label); - this.testee.visitLabel(anotherLabel); - verify(this.context, never()).enableMutatations(anyString()); - } - - @Test - public void shouldNotTryToEnableMutationsWhenIFNEInstructionEncounteredWithoutCheckingAssertionDisabledFlag() { - this.testee.visitJumpInsn(Opcodes.IFNE, this.label); - this.testee.visitLabel(this.label); - verify(this.context, never()).enableMutatations(anyString()); - } - - @Test - public void shouldOnlyCaptureFirstIFNEEncountered() { - final Label anotherLabel = Mockito.mock(Label.class); - this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", - "Z"); - this.testee.visitJumpInsn(Opcodes.IFNE, this.label); - this.testee.visitJumpInsn(Opcodes.IFNE, anotherLabel); - this.testee.visitLabel(this.label); - verify(this.context).enableMutatations(anyString()); - } - - @Test - public void shouldDisableMutationsForCodeSettingWhenAssertionDisabledFlagIsSetInStaticInitializer() { - this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", - "desiredAssertionStatus", "()Z", true); - verify(this.context).disableMutations(anyString()); - this.testee - .visitFieldInsn( - Opcodes.PUTSTATIC, - "org/pitest/mutationtest/engine/gregor/TestGregorMutater$HasAssertStatement", - "$assertionsDisabled", "Z"); - verify(this.context).enableMutatations(anyString()); - } - - @Test - public void shouldForwardInterceptedFieldInstructionsToChild() { - this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", - "Z"); - verify(this.mv).visitFieldInsn(Opcodes.GETSTATIC, "foo", - "$assertionsDisabled", "Z"); - } - - @Test - public void shouldForwardInterceptedVisitLabelInstructionsToChild() { - this.testee.visitLabel(this.label); - verify(this.mv).visitLabel(this.label); - } - - @Test - public void shouldForwardInterceptedVisitJumpInstructionsToChild() { - this.testee.visitJumpInsn(Opcodes.IFEQ, this.label); - verify(this.mv).visitJumpInsn(Opcodes.IFEQ, this.label); - } - - @Override - @Test - public void shouldForwardVisitMethodInsnToChild() { - this.testee.visitMethodInsn(1, "foo", "bar", "far", true); - verify(this.mv).visitMethodInsn(1, "foo", "bar", "far", true); - } - - @Override - protected MethodVisitor getTesteeVisitor() { - return this.testee; - } - -} +package org.pitest.mutationtest.engine.gregor; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.bytecode.MethodDecoratorTest; + +public class AvoidAssertsMethodAdapterTest extends MethodDecoratorTest { + + @Mock + private MethodMutationContext context; + + @Mock + private Label label; + + private AvoidAssertsMethodAdapter testee; + + @Override + @Before + public void setUp() { + super.setUp(); + this.testee = new AvoidAssertsMethodAdapter(this.context, this.mv); + } + + @Test + public void shouldDisableMutationsWhenAssertionDisabledFlagIsChecked() { + this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", + "Z"); + verify(this.context).disableMutations(anyString()); + } + + @Test + public void shouldEnableMutationsWhenReachLabelOfFirstIFNEAfterCheckingAssertionDisabledFlag() { + this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", + "Z"); + this.testee.visitJumpInsn(Opcodes.IFNE, this.label); + this.testee.visitLabel(this.label); + verify(this.context).enableMutatations(anyString()); + } + + @Test + public void shouldNotEnableMutationsWhenNonAssertionCheckLabelReached() { + final Label anotherLabel = Mockito.mock(Label.class); + this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", + "Z"); + this.testee.visitJumpInsn(Opcodes.IFNE, this.label); + this.testee.visitLabel(anotherLabel); + verify(this.context, never()).enableMutatations(anyString()); + } + + @Test + public void shouldNotTryToEnableMutationsWhenIFNEInstructionEncounteredWithoutCheckingAssertionDisabledFlag() { + this.testee.visitJumpInsn(Opcodes.IFNE, this.label); + this.testee.visitLabel(this.label); + verify(this.context, never()).enableMutatations(anyString()); + } + + @Test + public void shouldOnlyCaptureFirstIFNEEncountered() { + final Label anotherLabel = Mockito.mock(Label.class); + this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", + "Z"); + this.testee.visitJumpInsn(Opcodes.IFNE, this.label); + this.testee.visitJumpInsn(Opcodes.IFNE, anotherLabel); + this.testee.visitLabel(this.label); + verify(this.context).enableMutatations(anyString()); + } + + @Test + public void shouldDisableMutationsForCodeSettingWhenAssertionDisabledFlagIsSetInStaticInitializer() { + this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", + "desiredAssertionStatus", "()Z", true); + verify(this.context).disableMutations(anyString()); + this.testee + .visitFieldInsn( + Opcodes.PUTSTATIC, + "org/pitest/mutationtest/engine/gregor/TestGregorMutater$HasAssertStatement", + "$assertionsDisabled", "Z"); + verify(this.context).enableMutatations(anyString()); + } + + @Test + public void shouldForwardInterceptedFieldInstructionsToChild() { + this.testee.visitFieldInsn(Opcodes.GETSTATIC, "foo", "$assertionsDisabled", + "Z"); + verify(this.mv).visitFieldInsn(Opcodes.GETSTATIC, "foo", + "$assertionsDisabled", "Z"); + } + + @Test + public void shouldForwardInterceptedVisitLabelInstructionsToChild() { + this.testee.visitLabel(this.label); + verify(this.mv).visitLabel(this.label); + } + + @Test + public void shouldForwardInterceptedVisitJumpInstructionsToChild() { + this.testee.visitJumpInsn(Opcodes.IFEQ, this.label); + verify(this.mv).visitJumpInsn(Opcodes.IFEQ, this.label); + } + + @Override + @Test + public void shouldForwardVisitMethodInsnToChild() { + this.testee.visitMethodInsn(1, "foo", "bar", "far", true); + verify(this.mv).visitMethodInsn(1, "foo", "bar", "far", true); + } + + @Override + protected MethodVisitor getTesteeVisitor() { + return this.testee; + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/AvoidStringSwitchedMethodAdapterTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/AvoidStringSwitchedMethodAdapterTest.java index 1589c0cf2..3ba6d5800 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/AvoidStringSwitchedMethodAdapterTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/AvoidStringSwitchedMethodAdapterTest.java @@ -1,99 +1,99 @@ -package org.pitest.mutationtest.engine.gregor; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.pitest.bytecode.MethodDecoratorTest; - -public class AvoidStringSwitchedMethodAdapterTest extends MethodDecoratorTest { - - @Mock - private MethodMutationContext context; - - @Mock - private Label label; - - private AvoidStringSwitchedMethodAdapter testee; - - @Override - @Before - public void setUp() { - super.setUp(); - this.testee = new AvoidStringSwitchedMethodAdapter(this.context, this.mv); - } - - @Test - public void shouldDisableMutationsWhenTableSwitchImmediatelyFollowsHashCode() { - this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); - this.testee.visitTableSwitchInsn(0, 1, this.label); - verify(this.context).disableMutations(anyString()); - } - - @Test - public void shouldDisableMutationsWhenLookupSwitchImmediatelyFollowsHashCode() { - this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); - this.testee.visitLookupSwitchInsn(this.label, new int[0], new Label[0]); - verify(this.context).disableMutations(anyString()); - } - - @Test - public void shouldNotDisableMutationsWhenJumpOccursBeforeSwitch() { - this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); - this.testee.visitJumpInsn(Opcodes.IFEQ, this.label); - this.testee.visitLookupSwitchInsn(this.label, new int[0], new Label[0]); - verify(this.context, never()).disableMutations(anyString()); - } - - @Test - public void shouldNotDisableMutationsWhenPushOccursBeforeSwitch() { - this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); - this.testee.visitIntInsn(Opcodes.BIPUSH, 0); - this.testee.visitLookupSwitchInsn(this.label, new int[0], new Label[0]); - verify(this.context, never()).disableMutations(anyString()); - } - - - @Test - public void shouldNotDisableMutationsWhenIConstOccursBeforeSwitch() { - this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); - this.testee.visitInsn(Opcodes.ICONST_0); - this.testee.visitLookupSwitchInsn(this.label, new int[0], new Label[0]); - verify(this.context, never()).disableMutations(anyString()); - } - - @Test - public void shouldRenableMutationWhenSwitchDefaultHit() { - this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); - this.testee.visitTableSwitchInsn(0, 1, this.label); - this.testee.visitLabel(this.label); - verify(this.context).enableMutatations(anyString()); - } - - @Test - public void shouldNotRenableMutationWhenDifferentLabelHit() { - this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); - this.testee.visitTableSwitchInsn(0, 1, this.label); - this.testee.visitLabel(Mockito.mock(Label.class)); - verify(this.context, never()).enableMutatations(anyString()); - } - - @Test - public void shouldRenableMutationsWhenMethodVisitEnds() { - this.testee.visitEnd(); - verify(this.context).enableMutatations(anyString()); - } - - @Override - protected MethodVisitor getTesteeVisitor() { - return this.testee; - } - -} +package org.pitest.mutationtest.engine.gregor; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.pitest.bytecode.MethodDecoratorTest; + +public class AvoidStringSwitchedMethodAdapterTest extends MethodDecoratorTest { + + @Mock + private MethodMutationContext context; + + @Mock + private Label label; + + private AvoidStringSwitchedMethodAdapter testee; + + @Override + @Before + public void setUp() { + super.setUp(); + this.testee = new AvoidStringSwitchedMethodAdapter(this.context, this.mv); + } + + @Test + public void shouldDisableMutationsWhenTableSwitchImmediatelyFollowsHashCode() { + this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); + this.testee.visitTableSwitchInsn(0, 1, this.label); + verify(this.context).disableMutations(anyString()); + } + + @Test + public void shouldDisableMutationsWhenLookupSwitchImmediatelyFollowsHashCode() { + this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); + this.testee.visitLookupSwitchInsn(this.label, new int[0], new Label[0]); + verify(this.context).disableMutations(anyString()); + } + + @Test + public void shouldNotDisableMutationsWhenJumpOccursBeforeSwitch() { + this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); + this.testee.visitJumpInsn(Opcodes.IFEQ, this.label); + this.testee.visitLookupSwitchInsn(this.label, new int[0], new Label[0]); + verify(this.context, never()).disableMutations(anyString()); + } + + @Test + public void shouldNotDisableMutationsWhenPushOccursBeforeSwitch() { + this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); + this.testee.visitIntInsn(Opcodes.BIPUSH, 0); + this.testee.visitLookupSwitchInsn(this.label, new int[0], new Label[0]); + verify(this.context, never()).disableMutations(anyString()); + } + + + @Test + public void shouldNotDisableMutationsWhenIConstOccursBeforeSwitch() { + this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); + this.testee.visitInsn(Opcodes.ICONST_0); + this.testee.visitLookupSwitchInsn(this.label, new int[0], new Label[0]); + verify(this.context, never()).disableMutations(anyString()); + } + + @Test + public void shouldRenableMutationWhenSwitchDefaultHit() { + this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); + this.testee.visitTableSwitchInsn(0, 1, this.label); + this.testee.visitLabel(this.label); + verify(this.context).enableMutatations(anyString()); + } + + @Test + public void shouldNotRenableMutationWhenDifferentLabelHit() { + this.testee.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "unused", false); + this.testee.visitTableSwitchInsn(0, 1, this.label); + this.testee.visitLabel(Mockito.mock(Label.class)); + verify(this.context, never()).enableMutatations(anyString()); + } + + @Test + public void shouldRenableMutationsWhenMethodVisitEnds() { + this.testee.visitEnd(); + verify(this.context).enableMutatations(anyString()); + } + + @Override + protected MethodVisitor getTesteeVisitor() { + return this.testee; + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/ClassInfoTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/ClassInfoTest.java index d4d7b0f00..5189fa083 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/ClassInfoTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/ClassInfoTest.java @@ -1,45 +1,45 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class ClassInfoTest { - - @Test - public void shouldIdentifyEnumsFromSuperClass() { - final ClassInfo testee = new ClassInfo(0, 0, "foo", "", "java/lang/Enum", - null); - assertTrue(testee.isEnum()); - } - - @Test - public void shouldIdentifyGroovyObjects() { - final ClassInfo testee = new ClassInfo(0, 0, "foo", "", "foo", - new String[] { "groovy/lang/GroovyObject" }); - assertTrue(testee.isGroovyClass()); - } - - @Test - public void shouldIdentifyGroovyClosures() { - final ClassInfo testee = new ClassInfo(0, 0, "foo", "", - "groovy.lang.Closure", - new String[] { "org/codehaus/groovy/runtime/GeneratedClosure" }); - assertTrue(testee.isGroovyClass()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ClassInfoTest { + + @Test + public void shouldIdentifyEnumsFromSuperClass() { + final ClassInfo testee = new ClassInfo(0, 0, "foo", "", "java/lang/Enum", + null); + assertTrue(testee.isEnum()); + } + + @Test + public void shouldIdentifyGroovyObjects() { + final ClassInfo testee = new ClassInfo(0, 0, "foo", "", "foo", + new String[] { "groovy/lang/GroovyObject" }); + assertTrue(testee.isGroovyClass()); + } + + @Test + public void shouldIdentifyGroovyClosures() { + final ClassInfo testee = new ClassInfo(0, 0, "foo", "", + "groovy.lang.Closure", + new String[] { "org/codehaus/groovy/runtime/GeneratedClosure" }); + assertTrue(testee.isGroovyClass()); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/CoverageIgnore.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/CoverageIgnore.java index 6eaf64593..5adb33c77 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/CoverageIgnore.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/CoverageIgnore.java @@ -1,9 +1,9 @@ -package org.pitest.mutationtest.engine.gregor; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(value=RetentionPolicy.CLASS) -public @interface CoverageIgnore { - -} +package org.pitest.mutationtest.engine.gregor; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(value=RetentionPolicy.CLASS) +public @interface CoverageIgnore { + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/DoNotMutate.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/DoNotMutate.java index 112f1c8ae..18208313a 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/DoNotMutate.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/DoNotMutate.java @@ -1,9 +1,9 @@ -package org.pitest.mutationtest.engine.gregor; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(value=RetentionPolicy.CLASS) -public @interface DoNotMutate { - -} +package org.pitest.mutationtest.engine.gregor; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(value=RetentionPolicy.CLASS) +public @interface DoNotMutate { + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/Generated.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/Generated.java index 2c5ad4f89..cacd2f838 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/Generated.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/Generated.java @@ -1,9 +1,9 @@ -package org.pitest.mutationtest.engine.gregor; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(value=RetentionPolicy.CLASS) -public @interface Generated { - -} +package org.pitest.mutationtest.engine.gregor; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(value=RetentionPolicy.CLASS) +public @interface Generated { + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/GregorMutationEngineTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/GregorMutationEngineTest.java index 872d51794..f39d2a7c2 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/GregorMutationEngineTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/GregorMutationEngineTest.java @@ -1,3 +1,4 @@ + /* * Copyright 2011 Henry Coles * @@ -22,24 +23,25 @@ import org.junit.Test; import org.pitest.mutationtest.engine.gregor.config.DefaultMutationEngineConfiguration; import org.pitest.mutationtest.engine.gregor.config.Mutator; +import org.pitest.mutationtest.engine.gregor.mutators.augmentation.ArithmeticOperatorReplacementMutator; import org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator; import org.pitest.mutationtest.engine.gregor.mutators.MathMutator; public class GregorMutationEngineTest { - private GregorMutationEngine testee; + private GregorMutationEngine testee; - @Test - public void shouldReportNamesOfSuppliedMutators() { - final Collection mutators = Mutator - .fromStrings(Arrays.asList("CONDITIONALS_BOUNDARY", "MATH")); - final DefaultMutationEngineConfiguration config = new DefaultMutationEngineConfiguration( - i -> true, mutators); - this.testee = new GregorMutationEngine(config); - assertEquals(Arrays.asList( - ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR.getName(), - MathMutator.MATH_MUTATOR.getName()), this.testee.getMutatorNames()); + @Test + public void shouldReportNamesOfSuppliedMutators() { + final Collection mutators = Mutator + .fromStrings(Arrays.asList("CONDITIONALS_BOUNDARY", "MATH", "ARITHMETIC_OPERATOR_REPLACEMENT_MUTATOR")); + final DefaultMutationEngineConfiguration config = new DefaultMutationEngineConfiguration(i -> true, mutators); + this.testee = new GregorMutationEngine(config); + assertEquals(Arrays.asList(ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR.getName(), + ArithmeticOperatorReplacementMutator.ARITHMETIC_OPERATOR_REPLACEMENT_MUTATOR.getName(), + MathMutator.MATH_MUTATOR.getName()), this.testee.getMutatorNames()); - } + } } + diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/MethodInfoTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/MethodInfoTest.java index f79a4f8d2..5e83af394 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/MethodInfoTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/MethodInfoTest.java @@ -1,177 +1,177 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - -public class MethodInfoTest { - - private static final int NON_STATIC_MODIFIER = 0; - private static final int NON_SYNTHETIC_MODIFIER = 0; - private static final String VOID_RETURN = "()V"; - private static final String STRING_RETURN = "()Ljava/lang/String;"; - private static final int STATIC_MODIFIER = Opcodes.ACC_STATIC; - private static final String NO_PARAMETERS = "()V"; - private static final String ONE_PARAMETER = "(Ljava/lang/String;)V"; - private static final int SYNTHETIC_MODIFIER = Opcodes.ACC_SYNTHETIC; - private static final ClassInfo ENUMERATION_CLASS = new ClassInfo(0, 0, - "", "", - "java/lang/Enum", - new String[0]); - private final MethodInfo methodInfo = new MethodInfo(); - - @Test - public void isVoidShouldReturnTrueWhenMethodIsVoid() { - final MethodInfo testee = this.methodInfo.withMethodDescriptor(VOID_RETURN); - assertThat(testee.isVoid(), is(true)); - } - - @Test - public void isVoidShouldReturnFalseWhenMethodIsNotVoid() { - final MethodInfo testee = this.methodInfo - .withMethodDescriptor(STRING_RETURN); - assertThat(testee.isVoid(), is(false)); - } - - @Test - public void isStaticShouldReturnTrueWhenMethodIsStatic() { - final MethodInfo testee = this.methodInfo.withAccess(STATIC_MODIFIER); - assertThat(testee.isStatic(), is(true)); - } - - @Test - public void isStaticShouldReturnFalseWhenMethodIsNotStatic() { - final MethodInfo testee = this.methodInfo.withAccess(NON_STATIC_MODIFIER); - assertThat(testee.isStatic(), is(false)); - } - - @Test - public void takesNoParametersShouldReturnTrueWhenMethodTakesNoParameters() { - final MethodInfo testee = this.methodInfo - .withMethodDescriptor(NO_PARAMETERS); - assertThat(testee.takesNoParameters(), is(true)); - } - - @Test - public void takesNoParametersShouldReturnFalseWhenMethodTakesOneParameter() { - final MethodInfo testee = this.methodInfo - .withMethodDescriptor(ONE_PARAMETER); - assertThat(testee.takesNoParameters(), is(false)); - } - - @Test - public void isConstructorShouldReturnTrueWhenMethodIsConstructor() { - final MethodInfo testee = this.methodInfo.withMethodName(""); - assertThat(testee.isConstructor(), is(true)); - } - - @Test - public void isConstructorShouldReturnTrueWhenMethodIsRegularMethod() { - final MethodInfo testee = this.methodInfo.withMethodName("toString"); - assertThat(testee.isConstructor(), is(false)); - } - - @Test - public void isSyntheticShouldReturnTrueWhenSyntheticAccessFlagSet() { - final MethodInfo testee = this.methodInfo.withAccess(SYNTHETIC_MODIFIER); - assertThat(testee.isSynthetic(), is(true)); - } - - @Test - public void isSyntheticShouldReturnFalseWhenNoSyntheticAccessFlagSet() { - final MethodInfo testee = this.methodInfo - .withAccess(NON_SYNTHETIC_MODIFIER); - assertThat(testee.isSynthetic(), is(false)); - } - - @Test - public void isStaticInitializerShouldReturnTrueWhenMethodIsStaticInitializer() { - final MethodInfo testee = this.methodInfo.withMethodName(""); - assertThat(testee.isStaticInitializer(), is(true)); - } - - @Test - public void getReturnTypeReturnsCorrectReturnType() { - final MethodInfo testee = this.methodInfo - .withMethodDescriptor(STRING_RETURN); - assertThat(testee.getReturnType(), is(Type.getType(String.class))); - } - - @Test - public void getDescriptionReturnsQualifiedMethodName() { - final String EXAMPLE_CLASS_NAME = "org.pitest.Example"; - final ClassInfo EXAMPLE_CLASS_INFO = new ClassInfo(0, 0, - EXAMPLE_CLASS_NAME, "", "", new String[0]); - final String EXAMPLE_METHOD_NAME = "myMethod"; - final String QUALIFIED_METHOD_NAME = EXAMPLE_CLASS_NAME + "::" - + EXAMPLE_METHOD_NAME; - - final MethodInfo testee = this.methodInfo.withOwner(EXAMPLE_CLASS_INFO) - .withMethodName(EXAMPLE_METHOD_NAME); - - assertThat(testee.getDescription(), is(QUALIFIED_METHOD_NAME)); - } - - @Test - public void isGeneratedEnumMethodReturnsTrueIfMethodIsEnumValuesMethod() { - final MethodInfo testee = this.methodInfo.withOwner(ENUMERATION_CLASS) - .withAccess(STATIC_MODIFIER).withMethodName("values") - .withMethodDescriptor(NO_PARAMETERS); - - assertThat(testee.isGeneratedEnumMethod(), is(true)); - } - - @Test - public void isGeneratedEnumMethodReturnsTrueIfMethodIsEnumValueOfMethod() { - final MethodInfo testee = this.methodInfo.withOwner(ENUMERATION_CLASS) - .withAccess(STATIC_MODIFIER).withMethodName("valueOf") - .withMethodDescriptor("(Ljava/lang/String;)Lorg/pitest/MyEnum;"); - - assertThat(testee.isGeneratedEnumMethod(), is(true)); - } - - @Test - public void isGeneratedEnumMethodReturnsTrueIfMethodIsStaticInitializerInEnum() { - final MethodInfo testee = this.methodInfo.withOwner(ENUMERATION_CLASS) - .withAccess(STATIC_MODIFIER).withMethodName(""); - - assertThat(testee.isGeneratedEnumMethod(), is(true)); - } - - @Test - public void isGeneratedEnumMethodReturnsFalseForRegularEnumMethod() { - final MethodInfo testee = this.methodInfo.withOwner(ENUMERATION_CLASS) - .withMethodName("getOwner"); - - assertThat(testee.isGeneratedEnumMethod(), is(false)); - } - - @Test - public void isGeneratedEnumMethodReturnsFalseForNonEnumClasses() { - final ClassInfo EXAMPLE_CLASS_INFO = new ClassInfo(0, 0, - "org/pitest/Example", "", "java/lang/Object", new String[0]); - final MethodInfo testee = this.methodInfo.withOwner(EXAMPLE_CLASS_INFO) - .withAccess(STATIC_MODIFIER).withMethodName("values") - .withMethodDescriptor(NO_PARAMETERS); - - assertThat(testee.isGeneratedEnumMethod(), is(false)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; + +public class MethodInfoTest { + + private static final int NON_STATIC_MODIFIER = 0; + private static final int NON_SYNTHETIC_MODIFIER = 0; + private static final String VOID_RETURN = "()V"; + private static final String STRING_RETURN = "()Ljava/lang/String;"; + private static final int STATIC_MODIFIER = Opcodes.ACC_STATIC; + private static final String NO_PARAMETERS = "()V"; + private static final String ONE_PARAMETER = "(Ljava/lang/String;)V"; + private static final int SYNTHETIC_MODIFIER = Opcodes.ACC_SYNTHETIC; + private static final ClassInfo ENUMERATION_CLASS = new ClassInfo(0, 0, + "", "", + "java/lang/Enum", + new String[0]); + private final MethodInfo methodInfo = new MethodInfo(); + + @Test + public void isVoidShouldReturnTrueWhenMethodIsVoid() { + final MethodInfo testee = this.methodInfo.withMethodDescriptor(VOID_RETURN); + assertThat(testee.isVoid(), is(true)); + } + + @Test + public void isVoidShouldReturnFalseWhenMethodIsNotVoid() { + final MethodInfo testee = this.methodInfo + .withMethodDescriptor(STRING_RETURN); + assertThat(testee.isVoid(), is(false)); + } + + @Test + public void isStaticShouldReturnTrueWhenMethodIsStatic() { + final MethodInfo testee = this.methodInfo.withAccess(STATIC_MODIFIER); + assertThat(testee.isStatic(), is(true)); + } + + @Test + public void isStaticShouldReturnFalseWhenMethodIsNotStatic() { + final MethodInfo testee = this.methodInfo.withAccess(NON_STATIC_MODIFIER); + assertThat(testee.isStatic(), is(false)); + } + + @Test + public void takesNoParametersShouldReturnTrueWhenMethodTakesNoParameters() { + final MethodInfo testee = this.methodInfo + .withMethodDescriptor(NO_PARAMETERS); + assertThat(testee.takesNoParameters(), is(true)); + } + + @Test + public void takesNoParametersShouldReturnFalseWhenMethodTakesOneParameter() { + final MethodInfo testee = this.methodInfo + .withMethodDescriptor(ONE_PARAMETER); + assertThat(testee.takesNoParameters(), is(false)); + } + + @Test + public void isConstructorShouldReturnTrueWhenMethodIsConstructor() { + final MethodInfo testee = this.methodInfo.withMethodName(""); + assertThat(testee.isConstructor(), is(true)); + } + + @Test + public void isConstructorShouldReturnTrueWhenMethodIsRegularMethod() { + final MethodInfo testee = this.methodInfo.withMethodName("toString"); + assertThat(testee.isConstructor(), is(false)); + } + + @Test + public void isSyntheticShouldReturnTrueWhenSyntheticAccessFlagSet() { + final MethodInfo testee = this.methodInfo.withAccess(SYNTHETIC_MODIFIER); + assertThat(testee.isSynthetic(), is(true)); + } + + @Test + public void isSyntheticShouldReturnFalseWhenNoSyntheticAccessFlagSet() { + final MethodInfo testee = this.methodInfo + .withAccess(NON_SYNTHETIC_MODIFIER); + assertThat(testee.isSynthetic(), is(false)); + } + + @Test + public void isStaticInitializerShouldReturnTrueWhenMethodIsStaticInitializer() { + final MethodInfo testee = this.methodInfo.withMethodName(""); + assertThat(testee.isStaticInitializer(), is(true)); + } + + @Test + public void getReturnTypeReturnsCorrectReturnType() { + final MethodInfo testee = this.methodInfo + .withMethodDescriptor(STRING_RETURN); + assertThat(testee.getReturnType(), is(Type.getType(String.class))); + } + + @Test + public void getDescriptionReturnsQualifiedMethodName() { + final String EXAMPLE_CLASS_NAME = "org.pitest.Example"; + final ClassInfo EXAMPLE_CLASS_INFO = new ClassInfo(0, 0, + EXAMPLE_CLASS_NAME, "", "", new String[0]); + final String EXAMPLE_METHOD_NAME = "myMethod"; + final String QUALIFIED_METHOD_NAME = EXAMPLE_CLASS_NAME + "::" + + EXAMPLE_METHOD_NAME; + + final MethodInfo testee = this.methodInfo.withOwner(EXAMPLE_CLASS_INFO) + .withMethodName(EXAMPLE_METHOD_NAME); + + assertThat(testee.getDescription(), is(QUALIFIED_METHOD_NAME)); + } + + @Test + public void isGeneratedEnumMethodReturnsTrueIfMethodIsEnumValuesMethod() { + final MethodInfo testee = this.methodInfo.withOwner(ENUMERATION_CLASS) + .withAccess(STATIC_MODIFIER).withMethodName("values") + .withMethodDescriptor(NO_PARAMETERS); + + assertThat(testee.isGeneratedEnumMethod(), is(true)); + } + + @Test + public void isGeneratedEnumMethodReturnsTrueIfMethodIsEnumValueOfMethod() { + final MethodInfo testee = this.methodInfo.withOwner(ENUMERATION_CLASS) + .withAccess(STATIC_MODIFIER).withMethodName("valueOf") + .withMethodDescriptor("(Ljava/lang/String;)Lorg/pitest/MyEnum;"); + + assertThat(testee.isGeneratedEnumMethod(), is(true)); + } + + @Test + public void isGeneratedEnumMethodReturnsTrueIfMethodIsStaticInitializerInEnum() { + final MethodInfo testee = this.methodInfo.withOwner(ENUMERATION_CLASS) + .withAccess(STATIC_MODIFIER).withMethodName(""); + + assertThat(testee.isGeneratedEnumMethod(), is(true)); + } + + @Test + public void isGeneratedEnumMethodReturnsFalseForRegularEnumMethod() { + final MethodInfo testee = this.methodInfo.withOwner(ENUMERATION_CLASS) + .withMethodName("getOwner"); + + assertThat(testee.isGeneratedEnumMethod(), is(false)); + } + + @Test + public void isGeneratedEnumMethodReturnsFalseForNonEnumClasses() { + final ClassInfo EXAMPLE_CLASS_INFO = new ClassInfo(0, 0, + "org/pitest/Example", "", "java/lang/Object", new String[0]); + final MethodInfo testee = this.methodInfo.withOwner(EXAMPLE_CLASS_INFO) + .withAccess(STATIC_MODIFIER).withMethodName("values") + .withMethodDescriptor(NO_PARAMETERS); + + assertThat(testee.isGeneratedEnumMethod(), is(false)); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/MutatorTestBase.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/MutatorTestBase.java index 4ed077869..0d43baa8c 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/MutatorTestBase.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/MutatorTestBase.java @@ -1,228 +1,228 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.util.ASMifier; -import org.objectweb.asm.util.CheckClassAdapter; -import org.objectweb.asm.util.TraceClassVisitor; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassPathByteArraySource; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.simpletest.ExcludedPrefixIsolationStrategy; -import org.pitest.simpletest.Transformation; -import org.pitest.simpletest.TransformingClassLoader; -import org.pitest.util.Unchecked; -import org.pitest.util.XStreamCloning; - -public abstract class MutatorTestBase { - - protected GregorMutater engine; - - protected List findMutationsFor( - final Class clazz) { - return this.engine.findMutations(ClassName.fromClass(clazz)); - } - - protected List findMutationsFor(final String clazz) { - return this.engine.findMutations(ClassName.fromString(clazz)); - } - - protected void createTesteeWith(final Predicate filter, - final MethodMutatorFactory... mutators) { - this.engine = new GregorMutater(new ClassPathByteArraySource(), filter, - Arrays.asList(mutators)); - } - - protected void createTesteeWith(final ClassByteArraySource source, - final Predicate filter, - final Collection mutators) { - this.engine = new GregorMutater(source, filter, mutators); - } - - protected void createTesteeWith(final Predicate filter, - final Collection mutators) { - createTesteeWith(new ClassPathByteArraySource(), filter, mutators); - } - - protected void createTesteeWith(final Predicate filter, - final Collection loggingClasses, - final Collection mutators) { - this.engine = new GregorMutater(new ClassPathByteArraySource(), filter, - mutators); - } - - protected void createTesteeWith( - final Collection mutators) { - createTesteeWith(i -> true, mutators); - } - - protected void createTesteeWith(final MethodMutatorFactory... mutators) { - createTesteeWith(i -> true, mutators); - } - - protected void assertMutantCallableReturns(final Callable unmutated, - final Mutant mutant, final T expected) throws Exception { - assertEquals(expected, mutateAndCall(unmutated, mutant)); - } - - protected void assertNoMutants(final Class mutee) { - final Collection actual = findMutationsFor(mutee); - assertThat(actual).isEmpty(); - } - - protected T mutateAndCall(final Callable unmutated, final Mutant mutant) { - try { - final ClassLoader loader = createClassLoader(mutant); - return runInClassLoader(loader, unmutated); - } catch (final RuntimeException ex) { - throw ex; - } catch (final Exception ex) { - throw Unchecked.translateCheckedException(ex); - } - } - - private ClassLoader createClassLoader(final Mutant mutant) throws Exception { - final TransformingClassLoader loader = new TransformingClassLoader( - createTransformation(mutant), new ExcludedPrefixIsolationStrategy()); - - return loader; - } - - private Transformation createTransformation(final Mutant mutant) { - return (name, bytes) -> { - if (name.equals(mutant.getDetails().getClassName().asJavaName())) { - return mutant.getBytes(); - } else { - return bytes; - } - }; - } - - @SuppressWarnings("unchecked") - private T runInClassLoader(final ClassLoader loader, - final Callable callable) throws Exception { - final Callable c = (Callable) XStreamCloning.cloneForLoader(callable, - loader); - return c.call(); - - } - - protected List getMutants( - final List details) { - return details.stream().map(createMutant()).collect(Collectors.toList()); - } - - private Function createMutant() { - return a -> MutatorTestBase.this.engine.getMutation(a.getId()); - } - - protected Mutant getFirstMutant(final Collection actual) { - assertFalse("No mutant found", actual.isEmpty()); - final Mutant mutant = this.engine.getMutation(actual.iterator().next() - .getId()); - verifyMutant(mutant); - return mutant; - } - - protected Mutant getFirstMutant(final Class mutee) { - final Collection actual = findMutationsFor(mutee); - return getFirstMutant(actual); - } - - private void verifyMutant(final Mutant mutant) { - // printMutant(mutant); - final StringWriter sw = new StringWriter(); - final PrintWriter pw = new PrintWriter(sw); - CheckClassAdapter.verify(new ClassReader(mutant.getBytes()), false, pw); - assertTrue(sw.toString(), sw.toString().length() == 0); - - } - - protected void printMutant(final Mutant mutant) { - final ClassReader reader = new ClassReader(mutant.getBytes()); - reader.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter( - System.out)), ClassReader.EXPAND_FRAMES); - } - - protected void assertMutantsReturn(final Callable mutee, - final List details, - final String... expectedResults) { - - final List mutants = this.getMutants(details); - assertEquals("Should return one mutant for each request", details.size(), - mutants.size()); - final List results = FCollection.map(mutants, - mutantToStringReults(mutee)); - - int i = 0; - for (final String actual : results) { - assertEquals(expectedResults[i], actual); - i++; - } - } - - private Function mutantToStringReults(final Callable mutee) { - return mutant -> mutateAndCall(mutee, mutant); - } - - protected void assertMutantsAreFrom( - final List actualDetails, - final Class... mutators) { - assertEquals(mutators.length, actualDetails.size()); - int i = 0; - for (final MutationDetails each : actualDetails) { - assertEquals(each.getId().getMutator(), mutators[i].getName()); - i++; - } - } - - protected Mutant createFirstMutant( - final Class> mutee) { - final Collection actual = findMutationsFor(mutee); - return getFirstMutant(actual); - } - - protected Predicate mutateOnlyCallMethod() { - return a -> a.getName().equals("call"); - } - - protected Predicate descriptionContaining(final String value) { - return a -> a.getDescription().contains(value); - } - - protected void assertMutantDescriptionIncludes(String string, Class clazz) { - final Collection actual = findMutationsFor(clazz); - assertThat(actual.iterator().next().getDescription()).contains(string); - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.util.ASMifier; +import org.objectweb.asm.util.CheckClassAdapter; +import org.objectweb.asm.util.TraceClassVisitor; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassPathByteArraySource; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.simpletest.ExcludedPrefixIsolationStrategy; +import org.pitest.simpletest.Transformation; +import org.pitest.simpletest.TransformingClassLoader; +import org.pitest.util.Unchecked; +import org.pitest.util.XStreamCloning; + +public abstract class MutatorTestBase { + + protected GregorMutater engine; + + protected List findMutationsFor( + final Class clazz) { + return this.engine.findMutations(ClassName.fromClass(clazz)); + } + + protected List findMutationsFor(final String clazz) { + return this.engine.findMutations(ClassName.fromString(clazz)); + } + + protected void createTesteeWith(final Predicate filter, + final MethodMutatorFactory... mutators) { + this.engine = new GregorMutater(new ClassPathByteArraySource(), filter, + Arrays.asList(mutators)); + } + + protected void createTesteeWith(final ClassByteArraySource source, + final Predicate filter, + final Collection mutators) { + this.engine = new GregorMutater(source, filter, mutators); + } + + protected void createTesteeWith(final Predicate filter, + final Collection mutators) { + createTesteeWith(new ClassPathByteArraySource(), filter, mutators); + } + + protected void createTesteeWith(final Predicate filter, + final Collection loggingClasses, + final Collection mutators) { + this.engine = new GregorMutater(new ClassPathByteArraySource(), filter, + mutators); + } + + protected void createTesteeWith( + final Collection mutators) { + createTesteeWith(i -> true, mutators); + } + + protected void createTesteeWith(final MethodMutatorFactory... mutators) { + createTesteeWith(i -> true, mutators); + } + + protected void assertMutantCallableReturns(final Callable unmutated, + final Mutant mutant, final T expected) throws Exception { + assertEquals(expected, mutateAndCall(unmutated, mutant)); + } + + protected void assertNoMutants(final Class mutee) { + final Collection actual = findMutationsFor(mutee); + assertThat(actual).isEmpty(); + } + + protected T mutateAndCall(final Callable unmutated, final Mutant mutant) { + try { + final ClassLoader loader = createClassLoader(mutant); + return runInClassLoader(loader, unmutated); + } catch (final RuntimeException ex) { + throw ex; + } catch (final Exception ex) { + throw Unchecked.translateCheckedException(ex); + } + } + + private ClassLoader createClassLoader(final Mutant mutant) throws Exception { + final TransformingClassLoader loader = new TransformingClassLoader( + createTransformation(mutant), new ExcludedPrefixIsolationStrategy()); + + return loader; + } + + private Transformation createTransformation(final Mutant mutant) { + return (name, bytes) -> { + if (name.equals(mutant.getDetails().getClassName().asJavaName())) { + return mutant.getBytes(); + } else { + return bytes; + } + }; + } + + @SuppressWarnings("unchecked") + private T runInClassLoader(final ClassLoader loader, + final Callable callable) throws Exception { + final Callable c = (Callable) XStreamCloning.cloneForLoader(callable, + loader); + return c.call(); + + } + + protected List getMutants( + final List details) { + return details.stream().map(createMutant()).collect(Collectors.toList()); + } + + private Function createMutant() { + return a -> MutatorTestBase.this.engine.getMutation(a.getId()); + } + + protected Mutant getFirstMutant(final Collection actual) { + assertFalse("No mutant found", actual.isEmpty()); + final Mutant mutant = this.engine.getMutation(actual.iterator().next() + .getId()); + verifyMutant(mutant); + return mutant; + } + + protected Mutant getFirstMutant(final Class mutee) { + final Collection actual = findMutationsFor(mutee); + return getFirstMutant(actual); + } + + private void verifyMutant(final Mutant mutant) { + // printMutant(mutant); + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + CheckClassAdapter.verify(new ClassReader(mutant.getBytes()), false, pw); + assertTrue(sw.toString(), sw.toString().length() == 0); + + } + + protected void printMutant(final Mutant mutant) { + final ClassReader reader = new ClassReader(mutant.getBytes()); + reader.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter( + System.out)), ClassReader.EXPAND_FRAMES); + } + + protected void assertMutantsReturn(final Callable mutee, + final List details, + final String... expectedResults) { + + final List mutants = this.getMutants(details); + assertEquals("Should return one mutant for each request", details.size(), + mutants.size()); + final List results = FCollection.map(mutants, + mutantToStringReults(mutee)); + + int i = 0; + for (final String actual : results) { + assertEquals(expectedResults[i], actual); + i++; + } + } + + private Function mutantToStringReults(final Callable mutee) { + return mutant -> mutateAndCall(mutee, mutant); + } + + protected void assertMutantsAreFrom( + final List actualDetails, + final Class... mutators) { + assertEquals(mutators.length, actualDetails.size()); + int i = 0; + for (final MutationDetails each : actualDetails) { + assertEquals(each.getId().getMutator(), mutators[i].getName()); + i++; + } + } + + protected Mutant createFirstMutant( + final Class> mutee) { + final Collection actual = findMutationsFor(mutee); + return getFirstMutant(actual); + } + + protected Predicate mutateOnlyCallMethod() { + return a -> a.getName().equals("call"); + } + + protected Predicate descriptionContaining(final String value) { + return a -> a.getDescription().contains(value); + } + + protected void assertMutantDescriptionIncludes(String string, Class clazz) { + final Collection actual = findMutationsFor(clazz); + assertThat(actual.iterator().next().getDescription()).contains(string); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/TestGregorMutater.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/TestGregorMutater.java index 360a8885f..5fb87272b 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/TestGregorMutater.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/TestGregorMutater.java @@ -1,369 +1,369 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; -import java.util.List; -import java.util.function.Predicate; - -import org.junit.Test; -import org.pitest.functional.FCollection; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.config.Mutator; -import org.pitest.mutationtest.engine.gregor.mutators.IncrementsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.InvertNegsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.MathMutator; -import org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator; -import org.pitest.util.ResourceFolderByteArraySource; - -public class TestGregorMutater extends MutatorTestBase { - - public static class HasMultipleMutations { - public int mutable() { - int j = 10; - for (int i = 0; i != 10; i++) { - j = j << 1; - } - - return -j; - } - - } - - @Test - public void shouldFindMutationsFromAllSuppliedMutators() throws Exception { - - createTesteeWith(MathMutator.MATH_MUTATOR, - ReturnValsMutator.RETURN_VALS_MUTATOR, - InvertNegsMutator.INVERT_NEGS_MUTATOR, - IncrementsMutator.INCREMENTS_MUTATOR); - - final List actualDetails = findMutationsFor(HasMultipleMutations.class); - - assertTrue(actualDetails.stream() - .filter(descriptionContaining("Replaced Shift Left with Shift Right")).findFirst().isPresent()); - assertTrue(actualDetails.stream() - .filter(descriptionContaining("replaced return of integer")).findFirst().isPresent()); - assertTrue(actualDetails.stream() - .filter(descriptionContaining("Changed increment")).findFirst().isPresent()); - assertTrue(actualDetails.stream() - .filter(descriptionContaining("removed negation")).findFirst().isPresent()); - } - - @Test - public void shouldFindNoMutationsWhenNoMutationOperatorsSupplied() - throws Exception { - class VeryMutable { - @SuppressWarnings("unused") - public int f(final int i) { - switch (i) { - case 0: - return 1; - } - return 0; - } - } - createTesteeWith(); - final List actualDetails = findMutationsFor(VeryMutable.class); - assertTrue(actualDetails.isEmpty()); - - } - - static enum AnEnum { - Foo, Bar; - } - - @Test - public void shouldNotMutateCodeGeneratedByCompilerToImplementEnums() { - createTesteeWith(Mutator.all()); - final Collection actualDetails = findMutationsFor(AnEnum.class); - assertTrue(actualDetails.isEmpty()); - } - - static enum EnumWithCustomConstructor { - Foo, Bar; - - int i; - - EnumWithCustomConstructor() { - this.i++; - } - - } - - @Test - public void shouldMutateCustomConstructorsAddedToEnums() { - createTesteeWith(Mutator.all()); - final Collection actualDetails = findMutationsFor(EnumWithCustomConstructor.class); - assertThat(actualDetails).isNotEmpty(); - } - - - - public static class HasAssertStatement { - public void foo(final int i) { - assert ((i + 20) > 10); - } - } - - @Test - public void shouldNotMutateAssertStatments() { - createTesteeWith(Mutator.byName("NEGATE_CONDITIONALS")); - final Collection actualDetails = findMutationsFor(HasAssertStatement.class); - assertEquals(0, actualDetails.size()); - } - - public static class HasAssertStatementAndOtherStatements { - public int state; - - public void foo(final int i) { - assert ((i + 20) > 10); - if (i > 1) { - this.state = 1; - } - } - } - - @Test - public void shouldMutateOtherStatementsWhenAssertIsPresent() { - createTesteeWith(Mutator.byName("NEGATE_CONDITIONALS")); - final Collection actualDetails = findMutationsFor(HasAssertStatementAndOtherStatements.class); - assertEquals(1, actualDetails.size()); - } - - @Test - public void shouldNotMutateGroovyClasses() { - createTesteeWith(new ResourceFolderByteArraySource(), - i -> true, Mutator.all()); - final Collection actualDetails = findMutationsFor("groovy/SomeGroovyCode"); - assertTrue(actualDetails.isEmpty()); - } - - @Test - public void shouldNotMutateGroovyClosures() { - createTesteeWith(new ResourceFolderByteArraySource(), - i -> true, Mutator.all()); - final Collection actualDetails = findMutationsFor("groovy/SomeGroovyCode$_mapToString_closure2"); - assertTrue(actualDetails.isEmpty()); - } - - public static class OneStraightThroughMethod { - public void straightThrough(int i) { - i++; - i++; - } - } - - @Test - public void shouldRecordMutationsAsInSameBlockWhenForAStraightThroughMethod() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(OneStraightThroughMethod.class); - assertEquals(2, actualDetails.size()); - final int firstMutationBlock = actualDetails.get(0).getBlock(); - assertEquals(firstMutationBlock, actualDetails.get(1).getBlock()); - } - - public static class SimpleBranch { - public void straightThrough(int i, final boolean b) { - if (b) { - i++; - } else { - i++; - } - } - } - - @Test - public void shouldRecordMutationsAsInDifferentBlocksWhenInDifferentBranchesOfIfStatement() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(SimpleBranch.class); - assertTwoMutationsInDifferentBlocks(actualDetails); - } - - public static class TwoMethods { - public void a(int i) { - i++; - } - - public void b(int i) { - i++; - } - } - - @Test - public void shouldRecordMutationsAsInDifferentBlocksWhenInDifferentMethods() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(TwoMethods.class); - assertTwoMutationsInDifferentBlocks(actualDetails); - } - - public static class SwitchStatement { - public void a(int i, final int b) { - switch (b) { - case 0: - i++; - break; - case 1: - i++; - break; - default: - i++; - } - } - - } - - @Test - public void shouldRecordMutationsAsInDifferentBlocksWhenInDifferentBranchesOfSwitchStatement() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(SwitchStatement.class); - assertEquals(3, actualDetails.size()); - final int firstMutationBlock = actualDetails.get(0).getBlock(); - assertEquals(firstMutationBlock + 1, actualDetails.get(1).getBlock()); - assertEquals(firstMutationBlock + 2, actualDetails.get(2).getBlock()); - } - - public static class FallThroughSwitch { - public void a(int i, final int b) { - switch (b) { - case 0: - i++; - case 1: - i++; - } - } - } - - @Test - public void shouldRecordMutationsAsInSameBlockWhenSwitchStatementFallsThrough() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(FallThroughSwitch.class); - assertEquals(2, actualDetails.size()); - final int firstMutationBlock = actualDetails.get(0).getBlock(); - assertEquals(firstMutationBlock, actualDetails.get(1).getBlock()); - } - - public static class HasExceptionBlock { - public void foo(int i) { - try { - i++; - } catch (final Exception ex) { - i++; - } - } - } - - @Test - public void shouldRecordMutationsAsInDifferentBlocksWhenInExceptionHandler() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(HasExceptionBlock.class); - assertTwoMutationsInDifferentBlocks(actualDetails); - } - - @Test - public void shouldNotRecordMutationsAsInFinallyBlockWhenTheyAreNot() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(HasExceptionBlock.class); - assertFalse(actualDetails.get(0).isInFinallyBlock()); - assertFalse(actualDetails.get(1).isInFinallyBlock()); - } - - public static class HasFinallyBlock { - public void foo(int i) { - try { - System.out.println("foo"); - } finally { - i++; - } - } - } - - @Test - public void shouldMarkMutationsWithinFinallyBlocks() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(HasFinallyBlock.class); - assertEquals(1, FCollection.filter(actualDetails, isInFinallyBlock()) - .size()); - } - - public static class HasFinallyBlockAndExceptionHandler { - public void foo(int i) { - try { - System.out.println("foo"); - } catch (final Exception x) { - System.out.println("bar"); - } finally { - i++; - } - } - } - - @Test - public void shouldMarkMutationsWithinFinallyBlocksWhenExceptionHandlerAlsoPresent() { - createTesteeWith(Mutator.byName("INCREMENTS")); - final List actualDetails = findMutationsFor(HasFinallyBlockAndExceptionHandler.class); - assertEquals(1, FCollection.filter(actualDetails, isInFinallyBlock()) - .size()); - } - - public static class HasTwoMutableMethods { - public int a() { - return 1; - } - - public int a(int i) { - if (i > 2) { - System.out.println(i); - } - return 1; - } - } - - @Test - public void shouldScopeMutationIndexesByInstructionCounter() { - createTesteeWith(Mutator.byName("RETURN_VALS")); - final List actualDetails = findMutationsFor(HasTwoMutableMethods.class); - assertEquals(2, actualDetails.size()); - assertEquals(4, actualDetails.get(0).getId().getFirstIndex()); - assertEquals(15, actualDetails.get(1).getId().getFirstIndex()); // differs - // by - // target? - } - - @Test - public void shouldNotMutateCompilerGeneratedConditionalsInStringSwitch() { - createTesteeWith(new ResourceFolderByteArraySource(), - i -> true, Mutator.byName("REMOVE_CONDITIONALS")); - final Collection actualDetails = findMutationsFor("Java7SwitchOnString"); - assertThat(actualDetails).isEmpty(); - } - - - private static Predicate isInFinallyBlock() { - return a -> a.isInFinallyBlock(); - } - - private void assertTwoMutationsInDifferentBlocks( - final List actualDetails) { - assertEquals(2, actualDetails.size()); - final int firstMutationBlock = actualDetails.get(0).getBlock(); - assertEquals(firstMutationBlock + 1, actualDetails.get(1).getBlock()); - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Collection; +import java.util.List; +import java.util.function.Predicate; + +import org.junit.Test; +import org.pitest.functional.FCollection; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.config.Mutator; +import org.pitest.mutationtest.engine.gregor.mutators.IncrementsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.InvertNegsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.MathMutator; +import org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator; +import org.pitest.util.ResourceFolderByteArraySource; + +public class TestGregorMutater extends MutatorTestBase { + + public static class HasMultipleMutations { + public int mutable() { + int j = 10; + for (int i = 0; i != 10; i++) { + j = j << 1; + } + + return -j; + } + + } + + @Test + public void shouldFindMutationsFromAllSuppliedMutators() throws Exception { + + createTesteeWith(MathMutator.MATH_MUTATOR, + ReturnValsMutator.RETURN_VALS_MUTATOR, + InvertNegsMutator.INVERT_NEGS_MUTATOR, + IncrementsMutator.INCREMENTS_MUTATOR); + + final List actualDetails = findMutationsFor(HasMultipleMutations.class); + + assertTrue(actualDetails.stream() + .filter(descriptionContaining("Replaced Shift Left with Shift Right")).findFirst().isPresent()); + assertTrue(actualDetails.stream() + .filter(descriptionContaining("replaced return of integer")).findFirst().isPresent()); + assertTrue(actualDetails.stream() + .filter(descriptionContaining("Changed increment")).findFirst().isPresent()); + assertTrue(actualDetails.stream() + .filter(descriptionContaining("removed negation")).findFirst().isPresent()); + } + + @Test + public void shouldFindNoMutationsWhenNoMutationOperatorsSupplied() + throws Exception { + class VeryMutable { + @SuppressWarnings("unused") + public int f(final int i) { + switch (i) { + case 0: + return 1; + } + return 0; + } + } + createTesteeWith(); + final List actualDetails = findMutationsFor(VeryMutable.class); + assertTrue(actualDetails.isEmpty()); + + } + + static enum AnEnum { + Foo, Bar; + } + + @Test + public void shouldNotMutateCodeGeneratedByCompilerToImplementEnums() { + createTesteeWith(Mutator.all()); + final Collection actualDetails = findMutationsFor(AnEnum.class); + assertTrue(actualDetails.isEmpty()); + } + + static enum EnumWithCustomConstructor { + Foo, Bar; + + int i; + + EnumWithCustomConstructor() { + this.i++; + } + + } + + @Test + public void shouldMutateCustomConstructorsAddedToEnums() { + createTesteeWith(Mutator.all()); + final Collection actualDetails = findMutationsFor(EnumWithCustomConstructor.class); + assertThat(actualDetails).isNotEmpty(); + } + + + + public static class HasAssertStatement { + public void foo(final int i) { + assert ((i + 20) > 10); + } + } + + @Test + public void shouldNotMutateAssertStatments() { + createTesteeWith(Mutator.byName("NEGATE_CONDITIONALS")); + final Collection actualDetails = findMutationsFor(HasAssertStatement.class); + assertEquals(0, actualDetails.size()); + } + + public static class HasAssertStatementAndOtherStatements { + public int state; + + public void foo(final int i) { + assert ((i + 20) > 10); + if (i > 1) { + this.state = 1; + } + } + } + + @Test + public void shouldMutateOtherStatementsWhenAssertIsPresent() { + createTesteeWith(Mutator.byName("NEGATE_CONDITIONALS")); + final Collection actualDetails = findMutationsFor(HasAssertStatementAndOtherStatements.class); + assertEquals(1, actualDetails.size()); + } + + @Test + public void shouldNotMutateGroovyClasses() { + createTesteeWith(new ResourceFolderByteArraySource(), + i -> true, Mutator.all()); + final Collection actualDetails = findMutationsFor("groovy/SomeGroovyCode"); + assertTrue(actualDetails.isEmpty()); + } + + @Test + public void shouldNotMutateGroovyClosures() { + createTesteeWith(new ResourceFolderByteArraySource(), + i -> true, Mutator.all()); + final Collection actualDetails = findMutationsFor("groovy/SomeGroovyCode$_mapToString_closure2"); + assertTrue(actualDetails.isEmpty()); + } + + public static class OneStraightThroughMethod { + public void straightThrough(int i) { + i++; + i++; + } + } + + @Test + public void shouldRecordMutationsAsInSameBlockWhenForAStraightThroughMethod() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(OneStraightThroughMethod.class); + assertEquals(2, actualDetails.size()); + final int firstMutationBlock = actualDetails.get(0).getBlock(); + assertEquals(firstMutationBlock, actualDetails.get(1).getBlock()); + } + + public static class SimpleBranch { + public void straightThrough(int i, final boolean b) { + if (b) { + i++; + } else { + i++; + } + } + } + + @Test + public void shouldRecordMutationsAsInDifferentBlocksWhenInDifferentBranchesOfIfStatement() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(SimpleBranch.class); + assertTwoMutationsInDifferentBlocks(actualDetails); + } + + public static class TwoMethods { + public void a(int i) { + i++; + } + + public void b(int i) { + i++; + } + } + + @Test + public void shouldRecordMutationsAsInDifferentBlocksWhenInDifferentMethods() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(TwoMethods.class); + assertTwoMutationsInDifferentBlocks(actualDetails); + } + + public static class SwitchStatement { + public void a(int i, final int b) { + switch (b) { + case 0: + i++; + break; + case 1: + i++; + break; + default: + i++; + } + } + + } + + @Test + public void shouldRecordMutationsAsInDifferentBlocksWhenInDifferentBranchesOfSwitchStatement() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(SwitchStatement.class); + assertEquals(3, actualDetails.size()); + final int firstMutationBlock = actualDetails.get(0).getBlock(); + assertEquals(firstMutationBlock + 1, actualDetails.get(1).getBlock()); + assertEquals(firstMutationBlock + 2, actualDetails.get(2).getBlock()); + } + + public static class FallThroughSwitch { + public void a(int i, final int b) { + switch (b) { + case 0: + i++; + case 1: + i++; + } + } + } + + @Test + public void shouldRecordMutationsAsInSameBlockWhenSwitchStatementFallsThrough() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(FallThroughSwitch.class); + assertEquals(2, actualDetails.size()); + final int firstMutationBlock = actualDetails.get(0).getBlock(); + assertEquals(firstMutationBlock, actualDetails.get(1).getBlock()); + } + + public static class HasExceptionBlock { + public void foo(int i) { + try { + i++; + } catch (final Exception ex) { + i++; + } + } + } + + @Test + public void shouldRecordMutationsAsInDifferentBlocksWhenInExceptionHandler() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(HasExceptionBlock.class); + assertTwoMutationsInDifferentBlocks(actualDetails); + } + + @Test + public void shouldNotRecordMutationsAsInFinallyBlockWhenTheyAreNot() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(HasExceptionBlock.class); + assertFalse(actualDetails.get(0).isInFinallyBlock()); + assertFalse(actualDetails.get(1).isInFinallyBlock()); + } + + public static class HasFinallyBlock { + public void foo(int i) { + try { + System.out.println("foo"); + } finally { + i++; + } + } + } + + @Test + public void shouldMarkMutationsWithinFinallyBlocks() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(HasFinallyBlock.class); + assertEquals(1, FCollection.filter(actualDetails, isInFinallyBlock()) + .size()); + } + + public static class HasFinallyBlockAndExceptionHandler { + public void foo(int i) { + try { + System.out.println("foo"); + } catch (final Exception x) { + System.out.println("bar"); + } finally { + i++; + } + } + } + + @Test + public void shouldMarkMutationsWithinFinallyBlocksWhenExceptionHandlerAlsoPresent() { + createTesteeWith(Mutator.byName("INCREMENTS")); + final List actualDetails = findMutationsFor(HasFinallyBlockAndExceptionHandler.class); + assertEquals(1, FCollection.filter(actualDetails, isInFinallyBlock()) + .size()); + } + + public static class HasTwoMutableMethods { + public int a() { + return 1; + } + + public int a(int i) { + if (i > 2) { + System.out.println(i); + } + return 1; + } + } + + @Test + public void shouldScopeMutationIndexesByInstructionCounter() { + createTesteeWith(Mutator.byName("RETURN_VALS")); + final List actualDetails = findMutationsFor(HasTwoMutableMethods.class); + assertEquals(2, actualDetails.size()); + assertEquals(4, actualDetails.get(0).getId().getFirstIndex()); + assertEquals(15, actualDetails.get(1).getId().getFirstIndex()); // differs + // by + // target? + } + + @Test + public void shouldNotMutateCompilerGeneratedConditionalsInStringSwitch() { + createTesteeWith(new ResourceFolderByteArraySource(), + i -> true, Mutator.byName("REMOVE_CONDITIONALS")); + final Collection actualDetails = findMutationsFor("Java7SwitchOnString"); + assertThat(actualDetails).isEmpty(); + } + + + private static Predicate isInFinallyBlock() { + return a -> a.isInFinallyBlock(); + } + + private void assertTwoMutationsInDifferentBlocks( + final List actualDetails) { + assertEquals(2, actualDetails.size()); + final int firstMutationBlock = actualDetails.get(0).getBlock(); + assertEquals(firstMutationBlock + 1, actualDetails.get(1).getBlock()); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionTrackingMethodVisitorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionTrackingMethodVisitorTest.java index f9565f35a..4f2d04a0f 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionTrackingMethodVisitorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/analysis/InstructionTrackingMethodVisitorTest.java @@ -1,130 +1,130 @@ -package org.pitest.mutationtest.engine.gregor.analysis; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.util.IsolationUtils; - -public class InstructionTrackingMethodVisitorTest { - - private final ClassByteArraySource byteSource = new ClassloaderByteArraySource( - IsolationUtils - .getContextClassLoader()); - - private final InstructionCounter counter = new DefaultInstructionCounter(); - - @Test - public void shouldGiveIndexConsistentWithTreeApiForStringEquals() { - analyse(String.class, "equals"); - final MethodNode tree = makeTree(String.class, "equals"); - assertEquals(tree.instructions.size(), - this.counter.currentInstructionCount()); - } - - class HasMethodCallsAndBranches { - public int foo(final long j) { - if (j > 64000) { - bar(); - } - return 32; - } - - private void bar() { - - } - } - - @Test - public void shouldGiveIndexConsistentWithTreeApiWhenMethodCallsPresent() { - analyse(HasMethodCallsAndBranches.class, "foo"); - final MethodNode tree = makeTree(HasMethodCallsAndBranches.class, "foo"); - assertEquals(tree.instructions.size(), - this.counter.currentInstructionCount()); - } - - class HasSwitchStatements { - public int foo(final int j) { - switch (j) { - case 1: - return 3; - case 2: - return 4; - } - - switch (j) { - case 34: - return 1; - case 9: - return 2; - default: - return 6; - } - } - - } - - @Test - public void shouldGiveIndexConsistentWithTreeApiWhenSwitchStatementsPresent() { - analyse(HasSwitchStatements.class, "foo"); - final MethodNode tree = makeTree(HasSwitchStatements.class, "foo"); - assertEquals(tree.instructions.size(), - this.counter.currentInstructionCount()); - } - - private InstructionTrackingMethodVisitor analyse(final Class clazz, - final String targetMethod) { - final ClassReader reader = new ClassReader(this.byteSource.getBytes( - clazz.getName()).get()); - final Analyser cv = new Analyser(targetMethod); - reader.accept(cv, 0); - return cv.testee; - } - - private MethodNode makeTree(final Class clazz, final String name) { - final ClassReader reader = new ClassReader(this.byteSource.getBytes( - ClassName.fromClass(clazz).asJavaName()).get()); - final ClassNode tree = new ClassNode(); - reader.accept(tree, 0); - for (final Object m : tree.methods) { - final MethodNode mn = (MethodNode) m; - if (mn.name.equals(name)) { - return mn; - } - } - throw new RuntimeException("Method " + name + " not found in " + clazz); - } - - private class Analyser extends ClassVisitor { - private final String targetMethod; - InstructionTrackingMethodVisitor testee; - - public Analyser(final String targetMethod) { - super(Opcodes.ASM6); - this.targetMethod = targetMethod; - } - - @Override - public MethodVisitor visitMethod(final int access, final String name, - final String desc, final String signature, final String[] exceptions) { - if (name.equals(this.targetMethod)) { - this.testee = new InstructionTrackingMethodVisitor(super.visitMethod( - access, name, desc, signature, exceptions), - InstructionTrackingMethodVisitorTest.this.counter); - return this.testee; - } else { - return null; - } - } - - } - -} +package org.pitest.mutationtest.engine.gregor.analysis; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.util.IsolationUtils; + +public class InstructionTrackingMethodVisitorTest { + + private final ClassByteArraySource byteSource = new ClassloaderByteArraySource( + IsolationUtils + .getContextClassLoader()); + + private final InstructionCounter counter = new DefaultInstructionCounter(); + + @Test + public void shouldGiveIndexConsistentWithTreeApiForStringEquals() { + analyse(String.class, "equals"); + final MethodNode tree = makeTree(String.class, "equals"); + assertEquals(tree.instructions.size(), + this.counter.currentInstructionCount()); + } + + class HasMethodCallsAndBranches { + public int foo(final long j) { + if (j > 64000) { + bar(); + } + return 32; + } + + private void bar() { + + } + } + + @Test + public void shouldGiveIndexConsistentWithTreeApiWhenMethodCallsPresent() { + analyse(HasMethodCallsAndBranches.class, "foo"); + final MethodNode tree = makeTree(HasMethodCallsAndBranches.class, "foo"); + assertEquals(tree.instructions.size(), + this.counter.currentInstructionCount()); + } + + class HasSwitchStatements { + public int foo(final int j) { + switch (j) { + case 1: + return 3; + case 2: + return 4; + } + + switch (j) { + case 34: + return 1; + case 9: + return 2; + default: + return 6; + } + } + + } + + @Test + public void shouldGiveIndexConsistentWithTreeApiWhenSwitchStatementsPresent() { + analyse(HasSwitchStatements.class, "foo"); + final MethodNode tree = makeTree(HasSwitchStatements.class, "foo"); + assertEquals(tree.instructions.size(), + this.counter.currentInstructionCount()); + } + + private InstructionTrackingMethodVisitor analyse(final Class clazz, + final String targetMethod) { + final ClassReader reader = new ClassReader(this.byteSource.getBytes( + clazz.getName()).get()); + final Analyser cv = new Analyser(targetMethod); + reader.accept(cv, 0); + return cv.testee; + } + + private MethodNode makeTree(final Class clazz, final String name) { + final ClassReader reader = new ClassReader(this.byteSource.getBytes( + ClassName.fromClass(clazz).asJavaName()).get()); + final ClassNode tree = new ClassNode(); + reader.accept(tree, 0); + for (final Object m : tree.methods) { + final MethodNode mn = (MethodNode) m; + if (mn.name.equals(name)) { + return mn; + } + } + throw new RuntimeException("Method " + name + " not found in " + clazz); + } + + private class Analyser extends ClassVisitor { + private final String targetMethod; + InstructionTrackingMethodVisitor testee; + + public Analyser(final String targetMethod) { + super(Opcodes.ASM6); + this.targetMethod = targetMethod; + } + + @Override + public MethodVisitor visitMethod(final int access, final String name, + final String desc, final String signature, final String[] exceptions) { + if (name.equals(this.targetMethod)) { + this.testee = new InstructionTrackingMethodVisitor(super.visitMethod( + access, name, desc, signature, exceptions), + InstructionTrackingMethodVisitorTest.this.counter); + return this.testee; + } else { + return null; + } + } + + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/blocks/BlockTrackingMethodDecoratorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/blocks/BlockTrackingMethodDecoratorTest.java index 5f51fa2c4..17401bc84 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/blocks/BlockTrackingMethodDecoratorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/blocks/BlockTrackingMethodDecoratorTest.java @@ -1,156 +1,156 @@ -package org.pitest.mutationtest.engine.gregor.blocks; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.objectweb.asm.Opcodes.ARETURN; -import static org.objectweb.asm.Opcodes.ATHROW; -import static org.objectweb.asm.Opcodes.FRETURN; -import static org.objectweb.asm.Opcodes.ICONST_0; -import static org.objectweb.asm.Opcodes.IRETURN; -import static org.objectweb.asm.Opcodes.LRETURN; -import static org.objectweb.asm.Opcodes.RETURN; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.pitest.bytecode.MethodDecoratorTest; - -public class BlockTrackingMethodDecoratorTest extends MethodDecoratorTest { - - private BlockTrackingMethodDecorator testee; - - @Mock - private BlockCounter tracker; - - @Override - @Before - public void setUp() { - super.setUp(); - this.testee = new BlockTrackingMethodDecorator(this.tracker, this.mv); - } - - @Test - public void shouldRegisterFinallyBlockStartWhenHitsLabelFromNullExceptionHandler() { - final Label end = new Label(); - final Label start = new Label(); - final Label handler = new Label(); - this.testee.visitTryCatchBlock(start, end, handler, null); - this.testee.visitLabel(handler); - verify(this.tracker).registerFinallyBlockStart(); - } - - @Test - public void shouldNotRegisterFinallyBlockStartWhenHitsLabelFromNonNullExceptionHandler() { - final Label end = new Label(); - final Label start = new Label(); - final Label handler = new Label(); - this.testee.visitTryCatchBlock(start, end, handler, "NotNull"); - this.testee.visitLabel(handler); - verify(this.tracker, never()).registerFinallyBlockStart(); - } - - @Test - public void shouldNotRegisterFinallyBlockStartWhenHitsOtherLabelsFromNonNullExceptionHandler() { - final Label label = new Label(); - this.testee.visitLabel(label); - verify(this.tracker, never()).registerFinallyBlockStart(); - } - - @Test - public void shouldRegisiterNewBlockForJumpInstructions() { - this.testee.visitJumpInsn(0, null); - verify(this.tracker).registerNewBlock(); - } - - @Test - public void shouldRegisterNewBlockForReturnInstructions() { - this.testee.visitInsn(RETURN); - verify(this.tracker).registerNewBlock(); - } - - @Test - public void shouldRegisterFinallyBlockEndForReturnInstructions() { - this.testee.visitInsn(RETURN); - verify(this.tracker).registerFinallyBlockEnd(); - } - - @Test - public void shouldRegisterNewBlockForAReturnInstructions() { - this.testee.visitInsn(ARETURN); - verify(this.tracker).registerNewBlock(); - } - - @Test - public void shouldRegisterFinallyBlockEndForAReturnInstructions() { - this.testee.visitInsn(ARETURN); - verify(this.tracker).registerFinallyBlockEnd(); - } - - @Test - public void shouldRegisterNewBlockForFReturnInstructions() { - this.testee.visitInsn(FRETURN); - verify(this.tracker).registerNewBlock(); - } - - @Test - public void shouldRegisterFinallyBlockEndForFReturnInstructions() { - this.testee.visitInsn(FRETURN); - verify(this.tracker).registerFinallyBlockEnd(); - } - - @Test - public void shouldRegisterNewBlockForIReturnInstructions() { - this.testee.visitInsn(IRETURN); - verify(this.tracker).registerNewBlock(); - } - - @Test - public void shouldRegisterFinallyBlockEndForIReturnInstructions() { - this.testee.visitInsn(IRETURN); - verify(this.tracker).registerFinallyBlockEnd(); - } - - @Test - public void shouldRegisterNewBlockForLReturnInstructions() { - this.testee.visitInsn(LRETURN); - verify(this.tracker).registerNewBlock(); - } - - @Test - public void shouldRegisterFinallyBlockEndForLReturnInstructions() { - this.testee.visitInsn(LRETURN); - verify(this.tracker).registerFinallyBlockEnd(); - } - - @Test - public void shouldRegisterNewBlockForAThrowInstructions() { - this.testee.visitInsn(ATHROW); // possible without also getting a jump?? - verify(this.tracker).registerNewBlock(); - } - - @Test - public void shouldRegisterFinallyBlockEndForAThrowInstructions() { - this.testee.visitInsn(ATHROW); - verify(this.tracker).registerFinallyBlockEnd(); - } - - @Test - public void shouldNotRegisterANewBlockForOtherInsn() { - this.testee.visitInsn(ICONST_0); - verify(this.tracker, never()).registerNewBlock(); - } - - @Test - public void shouldNotRegisterFinallyBlockEndForOtherInsn() { - this.testee.visitInsn(ICONST_0); - verify(this.tracker, never()).registerFinallyBlockEnd(); - } - - @Override - protected MethodVisitor getTesteeVisitor() { - return this.testee; - } - -} +package org.pitest.mutationtest.engine.gregor.blocks; + +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.objectweb.asm.Opcodes.ARETURN; +import static org.objectweb.asm.Opcodes.ATHROW; +import static org.objectweb.asm.Opcodes.FRETURN; +import static org.objectweb.asm.Opcodes.ICONST_0; +import static org.objectweb.asm.Opcodes.IRETURN; +import static org.objectweb.asm.Opcodes.LRETURN; +import static org.objectweb.asm.Opcodes.RETURN; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.pitest.bytecode.MethodDecoratorTest; + +public class BlockTrackingMethodDecoratorTest extends MethodDecoratorTest { + + private BlockTrackingMethodDecorator testee; + + @Mock + private BlockCounter tracker; + + @Override + @Before + public void setUp() { + super.setUp(); + this.testee = new BlockTrackingMethodDecorator(this.tracker, this.mv); + } + + @Test + public void shouldRegisterFinallyBlockStartWhenHitsLabelFromNullExceptionHandler() { + final Label end = new Label(); + final Label start = new Label(); + final Label handler = new Label(); + this.testee.visitTryCatchBlock(start, end, handler, null); + this.testee.visitLabel(handler); + verify(this.tracker).registerFinallyBlockStart(); + } + + @Test + public void shouldNotRegisterFinallyBlockStartWhenHitsLabelFromNonNullExceptionHandler() { + final Label end = new Label(); + final Label start = new Label(); + final Label handler = new Label(); + this.testee.visitTryCatchBlock(start, end, handler, "NotNull"); + this.testee.visitLabel(handler); + verify(this.tracker, never()).registerFinallyBlockStart(); + } + + @Test + public void shouldNotRegisterFinallyBlockStartWhenHitsOtherLabelsFromNonNullExceptionHandler() { + final Label label = new Label(); + this.testee.visitLabel(label); + verify(this.tracker, never()).registerFinallyBlockStart(); + } + + @Test + public void shouldRegisiterNewBlockForJumpInstructions() { + this.testee.visitJumpInsn(0, null); + verify(this.tracker).registerNewBlock(); + } + + @Test + public void shouldRegisterNewBlockForReturnInstructions() { + this.testee.visitInsn(RETURN); + verify(this.tracker).registerNewBlock(); + } + + @Test + public void shouldRegisterFinallyBlockEndForReturnInstructions() { + this.testee.visitInsn(RETURN); + verify(this.tracker).registerFinallyBlockEnd(); + } + + @Test + public void shouldRegisterNewBlockForAReturnInstructions() { + this.testee.visitInsn(ARETURN); + verify(this.tracker).registerNewBlock(); + } + + @Test + public void shouldRegisterFinallyBlockEndForAReturnInstructions() { + this.testee.visitInsn(ARETURN); + verify(this.tracker).registerFinallyBlockEnd(); + } + + @Test + public void shouldRegisterNewBlockForFReturnInstructions() { + this.testee.visitInsn(FRETURN); + verify(this.tracker).registerNewBlock(); + } + + @Test + public void shouldRegisterFinallyBlockEndForFReturnInstructions() { + this.testee.visitInsn(FRETURN); + verify(this.tracker).registerFinallyBlockEnd(); + } + + @Test + public void shouldRegisterNewBlockForIReturnInstructions() { + this.testee.visitInsn(IRETURN); + verify(this.tracker).registerNewBlock(); + } + + @Test + public void shouldRegisterFinallyBlockEndForIReturnInstructions() { + this.testee.visitInsn(IRETURN); + verify(this.tracker).registerFinallyBlockEnd(); + } + + @Test + public void shouldRegisterNewBlockForLReturnInstructions() { + this.testee.visitInsn(LRETURN); + verify(this.tracker).registerNewBlock(); + } + + @Test + public void shouldRegisterFinallyBlockEndForLReturnInstructions() { + this.testee.visitInsn(LRETURN); + verify(this.tracker).registerFinallyBlockEnd(); + } + + @Test + public void shouldRegisterNewBlockForAThrowInstructions() { + this.testee.visitInsn(ATHROW); // possible without also getting a jump?? + verify(this.tracker).registerNewBlock(); + } + + @Test + public void shouldRegisterFinallyBlockEndForAThrowInstructions() { + this.testee.visitInsn(ATHROW); + verify(this.tracker).registerFinallyBlockEnd(); + } + + @Test + public void shouldNotRegisterANewBlockForOtherInsn() { + this.testee.visitInsn(ICONST_0); + verify(this.tracker, never()).registerNewBlock(); + } + + @Test + public void shouldNotRegisterFinallyBlockEndForOtherInsn() { + this.testee.visitInsn(ICONST_0); + verify(this.tracker, never()).registerFinallyBlockEnd(); + } + + @Override + protected MethodVisitor getTesteeVisitor() { + return this.testee; + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/blocks/ConcreteBlockCounterTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/blocks/ConcreteBlockCounterTest.java index e1cce8cac..a173e4b12 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/blocks/ConcreteBlockCounterTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/blocks/ConcreteBlockCounterTest.java @@ -1,36 +1,36 @@ -package org.pitest.mutationtest.engine.gregor.blocks; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; - -public class ConcreteBlockCounterTest { - - private ConcreteBlockCounter testee; - - @Before - public void setUp() { - this.testee = new ConcreteBlockCounter(); - } - - @Test - public void shouldTrackBlocks() { - this.testee.registerNewBlock(); - assertEquals(1, this.testee.getCurrentBlock()); - this.testee.registerNewBlock(); - assertEquals(2, this.testee.getCurrentBlock()); - } - - @Test - public void shouldTrackWhenCodeIsWithinFinallyBlocks() { - assertFalse(this.testee.isWithinFinallyBlock()); - this.testee.registerFinallyBlockStart(); - assertTrue(this.testee.isWithinFinallyBlock()); - this.testee.registerFinallyBlockEnd(); - assertFalse(this.testee.isWithinFinallyBlock()); - } - -} +package org.pitest.mutationtest.engine.gregor.blocks; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +public class ConcreteBlockCounterTest { + + private ConcreteBlockCounter testee; + + @Before + public void setUp() { + this.testee = new ConcreteBlockCounter(); + } + + @Test + public void shouldTrackBlocks() { + this.testee.registerNewBlock(); + assertEquals(1, this.testee.getCurrentBlock()); + this.testee.registerNewBlock(); + assertEquals(2, this.testee.getCurrentBlock()); + } + + @Test + public void shouldTrackWhenCodeIsWithinFinallyBlocks() { + assertFalse(this.testee.isWithinFinallyBlock()); + this.testee.registerFinallyBlockStart(); + assertTrue(this.testee.isWithinFinallyBlock()); + this.testee.registerFinallyBlockEnd(); + assertFalse(this.testee.isWithinFinallyBlock()); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/config/MutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/config/MutatorTest.java index cabedd697..b2dbf974f 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/config/MutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/config/MutatorTest.java @@ -1,57 +1,57 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.config; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Test; -import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; -import org.pitest.mutationtest.engine.gregor.mutators.ArgumentPropagationMutator; -import org.pitest.mutationtest.engine.gregor.mutators.InvertNegsMutator; -import org.pitest.mutationtest.engine.gregor.mutators.MathMutator; - -public class MutatorTest { - - @Test - public void shouldReturnRequestedMutators() { - assertThat(parseStrings("MATH", "INVERT_NEGS")).containsAll( - Arrays.asList(MathMutator.MATH_MUTATOR, - InvertNegsMutator.INVERT_NEGS_MUTATOR)); - } - - @Test - public void shouldNotCreateDuplicatesWhenRequestedDirectly() { - assertThat(parseStrings("MATH", "MATH")).hasSize(1); - } - - @Test - public void shouldNotCreateDuplicatesWhenRequestedViaGroup() { - assertThat(parseStrings("MATH", "DEFAULTS")).hasSameSizeAs( - parseStrings("DEFAULTS")); - } - - private Collection parseStrings(final String... s) { - return Mutator.fromStrings(Arrays.asList(s)); - } - - @Test - public void allContainsReplaceMethodMutator() throws Exception { - assertThat(Mutator.all()).contains( - ArgumentPropagationMutator.ARGUMENT_PROPAGATION_MUTATOR); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Test; +import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; +import org.pitest.mutationtest.engine.gregor.mutators.ArgumentPropagationMutator; +import org.pitest.mutationtest.engine.gregor.mutators.InvertNegsMutator; +import org.pitest.mutationtest.engine.gregor.mutators.MathMutator; + +public class MutatorTest { + + @Test + public void shouldReturnRequestedMutators() { + assertThat(parseStrings("MATH", "INVERT_NEGS")).containsAll( + Arrays.asList(MathMutator.MATH_MUTATOR, + InvertNegsMutator.INVERT_NEGS_MUTATOR)); + } + + @Test + public void shouldNotCreateDuplicatesWhenRequestedDirectly() { + assertThat(parseStrings("MATH", "MATH")).hasSize(1); + } + + @Test + public void shouldNotCreateDuplicatesWhenRequestedViaGroup() { + assertThat(parseStrings("MATH", "DEFAULTS")).hasSameSizeAs( + parseStrings("DEFAULTS")); + } + + private Collection parseStrings(final String... s) { + return Mutator.fromStrings(Arrays.asList(s)); + } + + @Test + public void allContainsReplaceMethodMutator() throws Exception { + assertThat(Mutator.all()).contains( + ArgumentPropagationMutator.ARGUMENT_PROPAGATION_MUTATOR); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ArgumentPropagationMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ArgumentPropagationMutatorTest.java index 66a7e8f10..2332b059f 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ArgumentPropagationMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ArgumentPropagationMutatorTest.java @@ -1,370 +1,370 @@ -/* - * Copyright 2014 Stefan Mandel, Urs Metz - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.engine.gregor.mutators; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.pitest.mutationtest.engine.gregor.mutators.ArgumentPropagationMutator.ARGUMENT_PROPAGATION_MUTATOR; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class ArgumentPropagationMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToUseReplaceMethodWithArgumentOfSameTypeAsReturnValueMutator() { - createTesteeWith(mutateOnlyCallMethod(), ARGUMENT_PROPAGATION_MUTATOR); - } - - @Test - public void shouldReplaceMethodCallWithStringArgument() throws Exception { - final Mutant mutant = getFirstMutant(HasStringMethodCall.class); - assertMutantCallableReturns(new HasStringMethodCall("example"), mutant, - "example"); - } - - private static class HasStringMethodCall implements Callable { - private final String arg; - - public HasStringMethodCall(String arg) { - this.arg = arg; - } - - public String delegate(final String aString) { - return "abc" + aString; - } - - @Override - public String call() throws Exception { - return delegate(this.arg); - } - } - - @Test - public void shouldReplaceMethodCallWithIntArgument() throws Exception { - final Mutant mutant = getFirstMutant(HasIntMethodCall.class); - assertMutantCallableReturns(new HasIntMethodCall(20), mutant, "20"); - } - - private static class HasIntMethodCall implements Callable { - private final int arg; - - public HasIntMethodCall(int arg) { - this.arg = arg; - } - - public int delegate(int aInt) { - return 22 + aInt; - } - - @Override - public String call() throws Exception { - return String.valueOf(delegate(this.arg)); - } - } - - @Test - public void shouldReplaceMethodCallWithLongArgument() throws Exception { - final Mutant mutant = getFirstMutant(HasLongMethodCall.class); - assertMutantCallableReturns(new HasLongMethodCall(20L), mutant, "20"); - } - - private static class HasLongMethodCall implements Callable { - private final long arg; - - public HasLongMethodCall(long arg) { - this.arg = arg; - } - - public long delegate(long argument) { - return 22L + argument; - } - - @Override - public String call() throws Exception { - return String.valueOf(delegate(this.arg)); - } - } - - @Test - public void shouldNotMutateMethodThatReturnsDifferentType() throws Exception { - assertNoMutants(ReturnsDifferentType.class); - } - - class ReturnsDifferentType implements Callable { - @Override - public String call() { - return addThreeAndConvertToString(3); - } - - private String addThreeAndConvertToString(int argument) { - return String.valueOf(3 + argument); - } - } - - @Test - public void continuesUntilMatchingArgumentTypeIsFound() throws Exception { - final Mutant mutant = getFirstMutant(OnlyFirstArgumentHasMatchingType.class); - assertMutantCallableReturns(new OnlyFirstArgumentHasMatchingType("abc", - new Object(), 3), mutant, "abc"); - } - - private class OnlyFirstArgumentHasMatchingType implements Callable { - private final String aString; - private final Object anObject; - private final long aLong; - - public OnlyFirstArgumentHasMatchingType(String aString, Object anObject, - long aLong) { - this.aString = aString; - this.anObject = anObject; - this.aLong = aLong; - } - - @Override - public String call() throws Exception { - return aMethod(this.aString, this.anObject, this.aLong); - } - - private String aMethod(String aString, Object anObject, long aLong) { - return String.valueOf(anObject) + aString + String.valueOf(aLong); - } - } - - @Test - public void usesLastArgumentOfMatchingTypeToReplaceMethod() throws Exception { - final Mutant mutant = getFirstMutant(HasSeveralArgumentWithMatchingType.class); - assertMutantCallableReturns(new HasSeveralArgumentWithMatchingType(11, 22), - mutant, "22"); - } - - private class HasSeveralArgumentWithMatchingType implements Callable { - private final int int1; - private final int int2; - - public HasSeveralArgumentWithMatchingType(int i, int j) { - this.int1 = i; - this.int2 = j; - } - - @Override - public String call() throws Exception { - final String anInt = "3"; - return String.valueOf(aMethod(this.int1, anInt, this.int2)); - } - - private int aMethod(int int1, String aString, int int2) { - return int1 + int2; - } - } - - @Test - public void alsoReplaceCallToMethodWhenReturnValueIsNotUsed() - throws Exception { - final Mutant mutant = getFirstMutant(ReturnValueNotUsed.class); - assertMutantCallableReturns(new ReturnValueNotUsed(), mutant, false); - } - - private class ReturnValueNotUsed implements Callable { - private final List aList = asList("xyz"); - - @Override - public Boolean call() throws Exception { - this.aList.set(0, "will not be present in list in mutated version"); - return this.aList - .contains("will not be present in list in mutated version"); - } - } - - @Test - public void shouldReplaceMethodsReturningArraysMatchingArgumentType() - throws Exception { - final Mutant mutant = getFirstMutant(HasArrayMethod.class); - final String[] expected = { "1", "2" }; - final String[] actual = mutateAndCall(new HasArrayMethod(), mutant); - assertThat(actual).containsExactly(expected); - } - - private static class HasArrayMethod implements Callable { - - public String[] delegate(final String[] ss) { - return new String[] {}; - } - - @Override - public String[] call() throws Exception { - final String[] s = { "1", "2" }; - return delegate(s); - } - } - - @Test - public void shouldNotReplaceMethodsReturningArraysOfUnmatchedType() - throws Exception { - assertNoMutants(HasArrayMethodOfDifferentType.class); - } - - private static class HasArrayMethodOfDifferentType implements - Callable { - - public String[] delegate(final Integer[] ss) { - return new String[] {}; - } - - @Override - public String[] call() throws Exception { - final Integer[] s = { 1, 2 }; - return delegate(s); - } - } - - @Test - public void willSubstituteCollectionsOfDifferentTypesDueToTypeErasure() - throws Exception { - final Mutant mutant = getFirstMutant(HasListMethod.class); - final List expected = Collections.emptyList(); - final List actual = mutateAndCall(new HasListMethod(), mutant); - assertThat(actual).isEqualTo(expected); - } - - private static class HasListMethod implements Callable> { - - public List delegate(final List is) { - return Arrays.asList(new String[] { "foo", "bar" }); - } - - @Override - public List call() throws Exception { - final List s = Collections.emptyList(); - return delegate(s); - } - } - - @Test - public void shouldReplaceInstanceMethodCallThatIsUsedAsArgumentForCallToOtherObject() - throws Exception { - final Mutant mutant = getFirstMutant(CallsOtherObjectWithResultOfInstanceMethod.class); - final MyListener listener = new MyListener(); - assertMutantCallableReturns(new CallsOtherObjectWithResultOfInstanceMethod( - "lowercase", listener), mutant, "lowercase"); - } - - private class CallsOtherObjectWithResultOfInstanceMethod implements - Callable { - private final String arg; - private final MyListener listener; - - public CallsOtherObjectWithResultOfInstanceMethod(String arg, - MyListener listener) { - this.arg = arg; - this.listener = listener; - } - - private String delegate(String aString) { - return aString.toUpperCase(); - } - - @Override - public String call() throws Exception { - this.listener.call(delegate(this.arg)); - return this.listener.getCalledWith(); - } - } - - @Test - public void shouldReplaceStaticMethodCallThatIsUsedAsArgumentForCallToOtherObject() - throws Exception { - final Mutant mutant = getFirstMutant(CallsOtherObjectWithResultOfStaticMethod.class); - final MyListener listener = new MyListener(); - assertMutantCallableReturns(new CallsOtherObjectWithResultOfStaticMethod( - "lowercase", listener), mutant, "lowercase"); - } - - private static class CallsOtherObjectWithResultOfStaticMethod implements - Callable { - private final String arg; - private final MyListener listener; - - public CallsOtherObjectWithResultOfStaticMethod(String arg, - MyListener listener) { - this.arg = arg; - this.listener = listener; - } - - private static String delegate(int i, String aString, long l) { - return aString.toUpperCase(); - } - - @Override - public String call() throws Exception { - this.listener.call(delegate(3, this.arg, 5L)); - return this.listener.getCalledWith(); - } - } - - @Test - public void shouldReplaceInstanceMethodCallWithSeveralArgumentsThatIsUsedAsArgumentForCallToOtherObject() - throws Exception { - final Mutant mutant = getFirstMutant(CallsOtherObjectWithResultOfInstanceMethodHavingSeveralArguments.class); - final MyListener listener = new MyListener(); - assertMutantCallableReturns( - new CallsOtherObjectWithResultOfInstanceMethodHavingSeveralArguments( - "lowercase", listener), mutant, "lowercase"); - - } - - private static class CallsOtherObjectWithResultOfInstanceMethodHavingSeveralArguments - implements Callable { - private final String arg; - private final MyListener listener; - - public CallsOtherObjectWithResultOfInstanceMethodHavingSeveralArguments( - String arg, MyListener listener) { - this.arg = arg; - this.listener = listener; - } - - private String delegate(int i, double aDouble, Object object, - String aString, long l) { - return aString.toUpperCase(); - } - - @Override - public String call() throws Exception { - this.listener.call(delegate(3, 4.2D, new Object(), this.arg, 5L)); - return this.listener.getCalledWith(); - } - } - - private static class MyListener { - private String calledWith = "not called"; - - public void call(String text) { - this.calledWith = text; - } - - public String getCalledWith() { - return this.calledWith; - } - } -} +/* + * Copyright 2014 Stefan Mandel, Urs Metz + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.engine.gregor.mutators; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.pitest.mutationtest.engine.gregor.mutators.ArgumentPropagationMutator.ARGUMENT_PROPAGATION_MUTATOR; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class ArgumentPropagationMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToUseReplaceMethodWithArgumentOfSameTypeAsReturnValueMutator() { + createTesteeWith(mutateOnlyCallMethod(), ARGUMENT_PROPAGATION_MUTATOR); + } + + @Test + public void shouldReplaceMethodCallWithStringArgument() throws Exception { + final Mutant mutant = getFirstMutant(HasStringMethodCall.class); + assertMutantCallableReturns(new HasStringMethodCall("example"), mutant, + "example"); + } + + private static class HasStringMethodCall implements Callable { + private final String arg; + + public HasStringMethodCall(String arg) { + this.arg = arg; + } + + public String delegate(final String aString) { + return "abc" + aString; + } + + @Override + public String call() throws Exception { + return delegate(this.arg); + } + } + + @Test + public void shouldReplaceMethodCallWithIntArgument() throws Exception { + final Mutant mutant = getFirstMutant(HasIntMethodCall.class); + assertMutantCallableReturns(new HasIntMethodCall(20), mutant, "20"); + } + + private static class HasIntMethodCall implements Callable { + private final int arg; + + public HasIntMethodCall(int arg) { + this.arg = arg; + } + + public int delegate(int aInt) { + return 22 + aInt; + } + + @Override + public String call() throws Exception { + return String.valueOf(delegate(this.arg)); + } + } + + @Test + public void shouldReplaceMethodCallWithLongArgument() throws Exception { + final Mutant mutant = getFirstMutant(HasLongMethodCall.class); + assertMutantCallableReturns(new HasLongMethodCall(20L), mutant, "20"); + } + + private static class HasLongMethodCall implements Callable { + private final long arg; + + public HasLongMethodCall(long arg) { + this.arg = arg; + } + + public long delegate(long argument) { + return 22L + argument; + } + + @Override + public String call() throws Exception { + return String.valueOf(delegate(this.arg)); + } + } + + @Test + public void shouldNotMutateMethodThatReturnsDifferentType() throws Exception { + assertNoMutants(ReturnsDifferentType.class); + } + + class ReturnsDifferentType implements Callable { + @Override + public String call() { + return addThreeAndConvertToString(3); + } + + private String addThreeAndConvertToString(int argument) { + return String.valueOf(3 + argument); + } + } + + @Test + public void continuesUntilMatchingArgumentTypeIsFound() throws Exception { + final Mutant mutant = getFirstMutant(OnlyFirstArgumentHasMatchingType.class); + assertMutantCallableReturns(new OnlyFirstArgumentHasMatchingType("abc", + new Object(), 3), mutant, "abc"); + } + + private class OnlyFirstArgumentHasMatchingType implements Callable { + private final String aString; + private final Object anObject; + private final long aLong; + + public OnlyFirstArgumentHasMatchingType(String aString, Object anObject, + long aLong) { + this.aString = aString; + this.anObject = anObject; + this.aLong = aLong; + } + + @Override + public String call() throws Exception { + return aMethod(this.aString, this.anObject, this.aLong); + } + + private String aMethod(String aString, Object anObject, long aLong) { + return String.valueOf(anObject) + aString + String.valueOf(aLong); + } + } + + @Test + public void usesLastArgumentOfMatchingTypeToReplaceMethod() throws Exception { + final Mutant mutant = getFirstMutant(HasSeveralArgumentWithMatchingType.class); + assertMutantCallableReturns(new HasSeveralArgumentWithMatchingType(11, 22), + mutant, "22"); + } + + private class HasSeveralArgumentWithMatchingType implements Callable { + private final int int1; + private final int int2; + + public HasSeveralArgumentWithMatchingType(int i, int j) { + this.int1 = i; + this.int2 = j; + } + + @Override + public String call() throws Exception { + final String anInt = "3"; + return String.valueOf(aMethod(this.int1, anInt, this.int2)); + } + + private int aMethod(int int1, String aString, int int2) { + return int1 + int2; + } + } + + @Test + public void alsoReplaceCallToMethodWhenReturnValueIsNotUsed() + throws Exception { + final Mutant mutant = getFirstMutant(ReturnValueNotUsed.class); + assertMutantCallableReturns(new ReturnValueNotUsed(), mutant, false); + } + + private class ReturnValueNotUsed implements Callable { + private final List aList = asList("xyz"); + + @Override + public Boolean call() throws Exception { + this.aList.set(0, "will not be present in list in mutated version"); + return this.aList + .contains("will not be present in list in mutated version"); + } + } + + @Test + public void shouldReplaceMethodsReturningArraysMatchingArgumentType() + throws Exception { + final Mutant mutant = getFirstMutant(HasArrayMethod.class); + final String[] expected = { "1", "2" }; + final String[] actual = mutateAndCall(new HasArrayMethod(), mutant); + assertThat(actual).containsExactly(expected); + } + + private static class HasArrayMethod implements Callable { + + public String[] delegate(final String[] ss) { + return new String[] {}; + } + + @Override + public String[] call() throws Exception { + final String[] s = { "1", "2" }; + return delegate(s); + } + } + + @Test + public void shouldNotReplaceMethodsReturningArraysOfUnmatchedType() + throws Exception { + assertNoMutants(HasArrayMethodOfDifferentType.class); + } + + private static class HasArrayMethodOfDifferentType implements + Callable { + + public String[] delegate(final Integer[] ss) { + return new String[] {}; + } + + @Override + public String[] call() throws Exception { + final Integer[] s = { 1, 2 }; + return delegate(s); + } + } + + @Test + public void willSubstituteCollectionsOfDifferentTypesDueToTypeErasure() + throws Exception { + final Mutant mutant = getFirstMutant(HasListMethod.class); + final List expected = Collections.emptyList(); + final List actual = mutateAndCall(new HasListMethod(), mutant); + assertThat(actual).isEqualTo(expected); + } + + private static class HasListMethod implements Callable> { + + public List delegate(final List is) { + return Arrays.asList(new String[] { "foo", "bar" }); + } + + @Override + public List call() throws Exception { + final List s = Collections.emptyList(); + return delegate(s); + } + } + + @Test + public void shouldReplaceInstanceMethodCallThatIsUsedAsArgumentForCallToOtherObject() + throws Exception { + final Mutant mutant = getFirstMutant(CallsOtherObjectWithResultOfInstanceMethod.class); + final MyListener listener = new MyListener(); + assertMutantCallableReturns(new CallsOtherObjectWithResultOfInstanceMethod( + "lowercase", listener), mutant, "lowercase"); + } + + private class CallsOtherObjectWithResultOfInstanceMethod implements + Callable { + private final String arg; + private final MyListener listener; + + public CallsOtherObjectWithResultOfInstanceMethod(String arg, + MyListener listener) { + this.arg = arg; + this.listener = listener; + } + + private String delegate(String aString) { + return aString.toUpperCase(); + } + + @Override + public String call() throws Exception { + this.listener.call(delegate(this.arg)); + return this.listener.getCalledWith(); + } + } + + @Test + public void shouldReplaceStaticMethodCallThatIsUsedAsArgumentForCallToOtherObject() + throws Exception { + final Mutant mutant = getFirstMutant(CallsOtherObjectWithResultOfStaticMethod.class); + final MyListener listener = new MyListener(); + assertMutantCallableReturns(new CallsOtherObjectWithResultOfStaticMethod( + "lowercase", listener), mutant, "lowercase"); + } + + private static class CallsOtherObjectWithResultOfStaticMethod implements + Callable { + private final String arg; + private final MyListener listener; + + public CallsOtherObjectWithResultOfStaticMethod(String arg, + MyListener listener) { + this.arg = arg; + this.listener = listener; + } + + private static String delegate(int i, String aString, long l) { + return aString.toUpperCase(); + } + + @Override + public String call() throws Exception { + this.listener.call(delegate(3, this.arg, 5L)); + return this.listener.getCalledWith(); + } + } + + @Test + public void shouldReplaceInstanceMethodCallWithSeveralArgumentsThatIsUsedAsArgumentForCallToOtherObject() + throws Exception { + final Mutant mutant = getFirstMutant(CallsOtherObjectWithResultOfInstanceMethodHavingSeveralArguments.class); + final MyListener listener = new MyListener(); + assertMutantCallableReturns( + new CallsOtherObjectWithResultOfInstanceMethodHavingSeveralArguments( + "lowercase", listener), mutant, "lowercase"); + + } + + private static class CallsOtherObjectWithResultOfInstanceMethodHavingSeveralArguments + implements Callable { + private final String arg; + private final MyListener listener; + + public CallsOtherObjectWithResultOfInstanceMethodHavingSeveralArguments( + String arg, MyListener listener) { + this.arg = arg; + this.listener = listener; + } + + private String delegate(int i, double aDouble, Object object, + String aString, long l) { + return aString.toUpperCase(); + } + + @Override + public String call() throws Exception { + this.listener.call(delegate(3, 4.2D, new Object(), this.arg, 5L)); + return this.listener.getCalledWith(); + } + } + + private static class MyListener { + private String calledWith = "not called"; + + public void call(String text) { + this.calledWith = text; + } + + public String getCalledWith() { + return this.calledWith; + } + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ArithmeticOperatorReplacementMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ArithmeticOperatorReplacementMutatorTest.java new file mode 100644 index 000000000..e31caabfa --- /dev/null +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ArithmeticOperatorReplacementMutatorTest.java @@ -0,0 +1,878 @@ +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.mutators; + +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; +import org.pitest.mutationtest.engine.gregor.mutators.augmentation.ArithmeticOperatorReplacementMutator; +public class ArithmeticOperatorReplacementMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyMathFunctions() { + createTesteeWith(ArithmeticOperatorReplacementMutator.ARITHMETIC_OPERATOR_REPLACEMENT_MUTATOR); + } + + private static class HasIAdd implements Callable { + private int i; + + HasIAdd(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i++; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerAdditionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasIAdd.class); + assertMutantCallableReturns(new HasIAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasIAdd(20), mutant, "19"); + } + + @Test + public void shouldReplaceIntegerAdditionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasIAdd.class); + assertMutantCallableReturns(new HasIAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasIAdd(20), mutant, "19"); + } + + @Test + public void shouldReplaceIntegerAdditionWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasIAdd.class); + assertMutantCallableReturns(new HasIAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasIAdd(20), mutant, "19"); + } + + @Test + public void shouldReplaceIntegerAdditionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasIAdd.class); + assertMutantCallableReturns(new HasIAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasIAdd(20), mutant, "19"); + } + + private static class HasISub implements Callable { + private int i; + + HasISub(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i--; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerSubtractionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasISub.class); + assertMutantCallableReturns(new HasISub(2), mutant, "3"); + assertMutantCallableReturns(new HasISub(20), mutant, "21"); + } + + @Test + public void shouldReplaceIntegerSubtractionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasISub.class); + assertMutantCallableReturns(new HasISub(2), mutant, "3"); + assertMutantCallableReturns(new HasISub(20), mutant, "21"); + } + + @Test + public void shouldReplaceIntegerSubtractionWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasISub.class); + assertMutantCallableReturns(new HasISub(2), mutant, "3"); + assertMutantCallableReturns(new HasISub(20), mutant, "21"); + } + + @Test + public void shouldReplaceIntegerSubtractionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasISub.class); + assertMutantCallableReturns(new HasISub(2), mutant, "3"); + assertMutantCallableReturns(new HasISub(20), mutant, "21"); + } + + private static class HasIMul implements Callable { + private int i; + + HasIMul(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i * 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerMultiplicationWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasIMul.class); + assertMutantCallableReturns(new HasIMul(2), mutant, "1"); + assertMutantCallableReturns(new HasIMul(20), mutant, "10"); + } + + @Test + public void shouldReplaceIntegerMultiplicationWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasIMul.class); + assertMutantCallableReturns(new HasIMul(2), mutant, "1"); + assertMutantCallableReturns(new HasIMul(20), mutant, "10"); + } + + @Test + public void shouldReplaceIntegerMultiplicationWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasIMul.class); + assertMutantCallableReturns(new HasIMul(2), mutant, "1"); + assertMutantCallableReturns(new HasIMul(20), mutant, "10"); + } + + @Test + public void shouldReplaceIntegerMultiplicationWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasIMul.class); + assertMutantCallableReturns(new HasIMul(2), mutant, "1"); + assertMutantCallableReturns(new HasIMul(20), mutant, "10"); + } + + private static class HasIDiv implements Callable { + private int i; + + HasIDiv(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i / 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerDivisionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasIDiv.class); + assertMutantCallableReturns(new HasIDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasIDiv(20), mutant, "40"); + } + + @Test + public void shouldReplaceIntegerDivisionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasIDiv.class); + assertMutantCallableReturns(new HasIDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasIDiv(20), mutant, "40"); + } + + @Test + public void shouldReplaceIntegerDivisionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasIDiv.class); + assertMutantCallableReturns(new HasIDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasIDiv(20), mutant, "40"); + } + + @Test + public void shouldReplaceIntegerDivisionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasIDiv.class); + assertMutantCallableReturns(new HasIDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasIDiv(20), mutant, "40"); + } + + private static class HasIRem implements Callable { + private int i; + + HasIRem(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i % 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerModulusWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasIRem.class); + assertMutantCallableReturns(new HasIRem(2), mutant, "4"); + assertMutantCallableReturns(new HasIRem(3), mutant, "6"); + } + + @Test + public void shouldReplaceIntegerModulusWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasIRem.class); + assertMutantCallableReturns(new HasIRem(2), mutant, "4"); + assertMutantCallableReturns(new HasIRem(3), mutant, "6"); + } + + @Test + public void shouldReplaceIntegerModulusWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasIRem.class); + assertMutantCallableReturns(new HasIRem(2), mutant, "4"); + assertMutantCallableReturns(new HasIRem(3), mutant, "6"); + } + + @Test + public void shouldReplaceIntegerModulusWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasIRem.class); + assertMutantCallableReturns(new HasIRem(2), mutant, "4"); + assertMutantCallableReturns(new HasIRem(3), mutant, "6"); + } + + + // LONGS + + private static class HasLAdd implements Callable { + private long i; + + HasLAdd(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i++; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongAdditionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasLAdd.class); + assertMutantCallableReturns(new HasLAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasLAdd(20), mutant, "19"); + } + + @Test + public void shouldReplaceLongAdditionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasLAdd.class); + assertMutantCallableReturns(new HasLAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasLAdd(20), mutant, "19"); + } + + @Test + public void shouldReplaceLongAdditionWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasLAdd.class); + assertMutantCallableReturns(new HasLAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasLAdd(20), mutant, "19"); + } + + @Test + public void shouldReplaceLongAdditionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasLAdd.class); + assertMutantCallableReturns(new HasLAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasLAdd(20), mutant, "19"); + } + + private static class HasLSub implements Callable { + private long i; + + HasLSub(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i--; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongSubtractionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasLSub.class); + assertMutantCallableReturns(new HasLSub(2), mutant, "3"); + assertMutantCallableReturns(new HasLSub(20), mutant, "21"); + } + + @Test + public void shouldReplaceLongSubtractionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasLSub.class); + assertMutantCallableReturns(new HasLSub(2), mutant, "3"); + assertMutantCallableReturns(new HasLSub(20), mutant, "21"); + } + + @Test + public void shouldReplaceLongSubtractionWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasLSub.class); + assertMutantCallableReturns(new HasLSub(2), mutant, "3"); + assertMutantCallableReturns(new HasLSub(20), mutant, "21"); + } + + @Test + public void shouldReplaceLongSubtractionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasLSub.class); + assertMutantCallableReturns(new HasLSub(2), mutant, "3"); + assertMutantCallableReturns(new HasLSub(20), mutant, "21"); + } + + private static class HasLMul implements Callable { + private long i; + + HasLMul(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i * 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongMultiplicationWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasLMul.class); + assertMutantCallableReturns(new HasLMul(2), mutant, "1"); + assertMutantCallableReturns(new HasLMul(20), mutant, "10"); + } + + @Test + public void shouldReplaceLongMultiplicationWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasLMul.class); + assertMutantCallableReturns(new HasLMul(2), mutant, "1"); + assertMutantCallableReturns(new HasLMul(20), mutant, "10"); + } + + @Test + public void shouldReplaceLongMultiplicationWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasLMul.class); + assertMutantCallableReturns(new HasLMul(2), mutant, "1"); + assertMutantCallableReturns(new HasLMul(20), mutant, "10"); + } + + @Test + public void shouldReplaceLongMultiplicationWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasLMul.class); + assertMutantCallableReturns(new HasLMul(2), mutant, "1"); + assertMutantCallableReturns(new HasLMul(20), mutant, "10"); + } + + private static class HasLDiv implements Callable { + private long i; + + HasLDiv(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i / 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongDivisionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasLDiv.class); + assertMutantCallableReturns(new HasLDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasLDiv(20), mutant, "40"); + } + + @Test + public void shouldReplaceLongDivisionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasLDiv.class); + assertMutantCallableReturns(new HasLDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasLDiv(20), mutant, "40"); + } + + @Test + public void shouldReplaceLongDivisionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasLDiv.class); + assertMutantCallableReturns(new HasLDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasLDiv(20), mutant, "40"); + } + + @Test + public void shouldReplaceLongDivisionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasLDiv.class); + assertMutantCallableReturns(new HasLDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasLDiv(20), mutant, "40"); + } + + private static class HasLRem implements Callable { + private long i; + + HasLRem(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i % 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongModulusWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasLRem.class); + assertMutantCallableReturns(new HasLRem(2), mutant, "4"); + assertMutantCallableReturns(new HasLRem(3), mutant, "6"); + } + + @Test + public void shouldReplaceLongModulusWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasLRem.class); + assertMutantCallableReturns(new HasLRem(2), mutant, "4"); + assertMutantCallableReturns(new HasLRem(3), mutant, "6"); + } + + @Test + public void shouldReplaceLongModulusWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasLRem.class); + assertMutantCallableReturns(new HasLRem(2), mutant, "4"); + assertMutantCallableReturns(new HasLRem(3), mutant, "6"); + } + + @Test + public void shouldReplaceLongModulusWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasLRem.class); + assertMutantCallableReturns(new HasLRem(2), mutant, "4"); + assertMutantCallableReturns(new HasLRem(3), mutant, "6"); + } + + // FLOATS + + private static class HasFADD implements Callable { + private float i; + + HasFADD(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i++; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatAdditionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasFADD.class); + assertMutantCallableReturns(new HasFADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFADD(20), mutant, "19.0"); + } + + @Test + public void shouldReplaceFloatAdditionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasFADD.class); + assertMutantCallableReturns(new HasFADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFADD(20), mutant, "19.0"); + } + + @Test + public void shouldReplaceFloatAdditionWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasFADD.class); + assertMutantCallableReturns(new HasFADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFADD(20), mutant, "19.0"); + } + + @Test + public void shouldReplaceFloatAdditionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasFADD.class); + assertMutantCallableReturns(new HasFADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFADD(20), mutant, "19.0"); + } + + private static class HasFSUB implements Callable { + private float i; + + HasFSUB(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i--; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatSubtractionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasFSUB.class); + assertMutantCallableReturns(new HasFSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasFSUB(20), mutant, "21.0"); + } + + @Test + public void shouldReplaceFloatSubtractionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasFSUB.class); + assertMutantCallableReturns(new HasFSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasFSUB(20), mutant, "21.0"); + } + + @Test + public void shouldReplaceFloatSubtractionWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasFSUB.class); + assertMutantCallableReturns(new HasFSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasFSUB(20), mutant, "21.0"); + } + + @Test + public void shouldReplaceFloatSubtractionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasFSUB.class); + assertMutantCallableReturns(new HasFSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasFSUB(20), mutant, "21.0"); + } + + private static class HasFMUL implements Callable { + private float i; + + HasFMUL(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i * 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatMultiplicationWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasFMUL.class); + assertMutantCallableReturns(new HasFMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFMUL(20), mutant, "10.0"); + } + + @Test + public void shouldReplaceFloatMultiplicationWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasFMUL.class); + assertMutantCallableReturns(new HasFMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFMUL(20), mutant, "10.0"); + } + + @Test + public void shouldReplaceFloatMultiplicationWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasFMUL.class); + assertMutantCallableReturns(new HasFMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFMUL(20), mutant, "10.0"); + } + + @Test + public void shouldReplaceFloatMultiplicationWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasFMUL.class); + assertMutantCallableReturns(new HasFMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFMUL(20), mutant, "10.0"); + } + + private static class HasFDIV implements Callable { + private float i; + + HasFDIV(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i / 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatDivisionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasFDIV.class); + assertMutantCallableReturns(new HasFDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFDIV(20), mutant, "40.0"); + } + + @Test + public void shouldReplaceFloatDivisionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasFDIV.class); + assertMutantCallableReturns(new HasFDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFDIV(20), mutant, "40.0"); + } + + @Test + public void shouldReplaceFloatDivisionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasFDIV.class); + assertMutantCallableReturns(new HasFDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFDIV(20), mutant, "40.0"); + } + + @Test + public void shouldReplaceFloatDivisionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasFDIV.class); + assertMutantCallableReturns(new HasFDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFDIV(20), mutant, "40.0"); + } + + private static class HasFREM implements Callable { + private float i; + + HasFREM(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i % 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatModulusWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasFREM.class); + assertMutantCallableReturns(new HasFREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFREM(3), mutant, "6.0"); + } + + @Test + public void shouldReplaceFloatModulusWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasFREM.class); + assertMutantCallableReturns(new HasFREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFREM(3), mutant, "6.0"); + } + + @Test + public void shouldReplaceFloatModulusWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasFREM.class); + assertMutantCallableReturns(new HasFREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFREM(3), mutant, "6.0"); + } + + @Test + public void shouldReplaceFloatModulusWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasFREM.class); + assertMutantCallableReturns(new HasFREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFREM(3), mutant, "6.0"); + } + + // double + + private static class HasDADD implements Callable { + private double i; + + HasDADD(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i++; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoubleAdditionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasDADD.class); + assertMutantCallableReturns(new HasDADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDADD(20), mutant, "19.0"); + } + + @Test + public void shouldReplaceDoubleAdditionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasDADD.class); + assertMutantCallableReturns(new HasDADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDADD(20), mutant, "19.0"); + } + + @Test + public void shouldReplaceDoubleAdditionWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasDADD.class); + assertMutantCallableReturns(new HasDADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDADD(20), mutant, "19.0"); + } + + @Test + public void shouldReplaceDoubleAdditionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasDADD.class); + assertMutantCallableReturns(new HasDADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDADD(20), mutant, "19.0"); + } + + private static class HasDSUB implements Callable { + private double i; + + HasDSUB(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i--; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoubleSubtractionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasDSUB.class); + assertMutantCallableReturns(new HasDSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasDSUB(20), mutant, "21.0"); + } + + @Test + public void shouldReplaceDoubleSubtractionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasDSUB.class); + assertMutantCallableReturns(new HasDSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasDSUB(20), mutant, "21.0"); + } + + @Test + public void shouldReplaceDoubleSubtractionWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasDSUB.class); + assertMutantCallableReturns(new HasDSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasDSUB(20), mutant, "21.0"); + } + + @Test + public void shouldReplaceDoubleSubtractionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasDSUB.class); + assertMutantCallableReturns(new HasDSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasDSUB(20), mutant, "21.0"); + } + + private static class HasDMUL implements Callable { + private double i; + + HasDMUL(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i * 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoubleMultiplicationWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasDMUL.class); + assertMutantCallableReturns(new HasDMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDMUL(20), mutant, "10.0"); + } + + @Test + public void shouldReplaceDoubleMultiplicationWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasDMUL.class); + assertMutantCallableReturns(new HasDMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDMUL(20), mutant, "10.0"); + } + + @Test + public void shouldReplaceDoubleMultiplicationWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasDMUL.class); + assertMutantCallableReturns(new HasDMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDMUL(20), mutant, "10.0"); + } + + @Test + public void shouldReplaceDoubleMultiplicationWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasDMUL.class); + assertMutantCallableReturns(new HasDMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDMUL(20), mutant, "10.0"); + } + + private static class HasDDIV implements Callable { + private double i; + + HasDDIV(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i / 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoubleDivisionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasDDIV.class); + assertMutantCallableReturns(new HasDDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDDIV(20), mutant, "40.0"); + } + + @Test + public void shouldReplaceDoubleDivisionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasDDIV.class); + assertMutantCallableReturns(new HasDDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDDIV(20), mutant, "40.0"); + } + + @Test + public void shouldReplaceDoubleDivisionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasDDIV.class); + assertMutantCallableReturns(new HasDDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDDIV(20), mutant, "40.0"); + } + + @Test + public void shouldReplaceDoubleDivisionWithModulus() throws Exception { + final Mutant mutant = getFirstMutant(HasDDIV.class); + assertMutantCallableReturns(new HasDDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDDIV(20), mutant, "40.0"); + } + + private static class HasDREM implements Callable { + private double i; + + HasDREM(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i % 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoublerModulusWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasDREM.class); + assertMutantCallableReturns(new HasDREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDREM(3), mutant, "6.0"); + } + + @Test + public void shouldReplaceDoublerModulusWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasDREM.class); + assertMutantCallableReturns(new HasDREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDREM(3), mutant, "6.0"); + } + + @Test + public void shouldReplaceDoublerModulusWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasDREM.class); + assertMutantCallableReturns(new HasDREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDREM(3), mutant, "6.0"); + } + + @Test + public void shouldReplaceDoublerModulusWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasDREM.class); + assertMutantCallableReturns(new HasDREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDREM(3), mutant, "6.0"); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/BooleanFalseReturnValsMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/BooleanFalseReturnValsMutatorTest.java index 5e8ef367c..fc861cea4 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/BooleanFalseReturnValsMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/BooleanFalseReturnValsMutatorTest.java @@ -1,88 +1,88 @@ -package org.pitest.mutationtest.engine.gregor.mutators; - -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class BooleanFalseReturnValsMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyReturnVals() { - createTesteeWith(BooleanFalseReturnValsMutator.BOOLEAN_FALSE_RETURN); - } - - @Test - public void mutatesReturnTrueToReturnFalse() throws Exception { - assertMutantCallableReturns(new BooleanReturn(), - createFirstMutant(BooleanReturn.class), "false"); - } - - @Test - public void describesMutationsToPrimitiveBooleans() { - assertMutantDescriptionIncludes("replaced boolean return with false", BooleanReturn.class); - assertMutantDescriptionIncludes("BooleanReturn::mutable", BooleanReturn.class); - } - - @Test - public void doesNotMutatePrimitiveIntReturns() throws Exception { - this.assertNoMutants(IntegerReturn.class); - } - - @Test - public void mutatesBoxedTrueToFalse() throws Exception { - assertMutantCallableReturns(new BoxedTrue(), - createFirstMutant(BoxedTrue.class), false); - } - - @Test - public void describesMutationsToBoxedBooleans() { - assertMutantDescriptionIncludes("replaced Boolean return with False", BoxedTrue.class); - assertMutantDescriptionIncludes("BoxedTrue::call", BoxedTrue.class); - } - - @Test - public void doesNotMutateBoxedIntegerReturns() throws Exception { - this.assertNoMutants(BoxedInteger.class); - } - - private static class BooleanReturn implements Callable { - public boolean mutable() { - return true; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - private static class IntegerReturn implements Callable { - public int mutable() { - return 42; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - - private static class BoxedTrue implements Callable { - @Override - public Boolean call() { - return Boolean.TRUE; - } - } - - private static class BoxedInteger implements Callable { - @Override - public Integer call() { - return 42; - } - } - - -} +package org.pitest.mutationtest.engine.gregor.mutators; + +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class BooleanFalseReturnValsMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyReturnVals() { + createTesteeWith(BooleanFalseReturnValsMutator.BOOLEAN_FALSE_RETURN); + } + + @Test + public void mutatesReturnTrueToReturnFalse() throws Exception { + assertMutantCallableReturns(new BooleanReturn(), + createFirstMutant(BooleanReturn.class), "false"); + } + + @Test + public void describesMutationsToPrimitiveBooleans() { + assertMutantDescriptionIncludes("replaced boolean return with false", BooleanReturn.class); + assertMutantDescriptionIncludes("BooleanReturn::mutable", BooleanReturn.class); + } + + @Test + public void doesNotMutatePrimitiveIntReturns() throws Exception { + this.assertNoMutants(IntegerReturn.class); + } + + @Test + public void mutatesBoxedTrueToFalse() throws Exception { + assertMutantCallableReturns(new BoxedTrue(), + createFirstMutant(BoxedTrue.class), false); + } + + @Test + public void describesMutationsToBoxedBooleans() { + assertMutantDescriptionIncludes("replaced Boolean return with False", BoxedTrue.class); + assertMutantDescriptionIncludes("BoxedTrue::call", BoxedTrue.class); + } + + @Test + public void doesNotMutateBoxedIntegerReturns() throws Exception { + this.assertNoMutants(BoxedInteger.class); + } + + private static class BooleanReturn implements Callable { + public boolean mutable() { + return true; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + private static class IntegerReturn implements Callable { + public int mutable() { + return 42; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + + private static class BoxedTrue implements Callable { + @Override + public Boolean call() { + return Boolean.TRUE; + } + } + + private static class BoxedInteger implements Callable { + @Override + public Integer call() { + return 42; + } + } + + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/BooleanTrueReturnValsMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/BooleanTrueReturnValsMutatorTest.java index 9464f7b39..daa6474fc 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/BooleanTrueReturnValsMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/BooleanTrueReturnValsMutatorTest.java @@ -1,88 +1,88 @@ -package org.pitest.mutationtest.engine.gregor.mutators; - -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class BooleanTrueReturnValsMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyReturnVals() { - createTesteeWith(BooleanTrueReturnValsMutator.BOOLEAN_TRUE_RETURN); - } - - @Test - public void mutatesReturnFalseToReturnTrue() throws Exception { - assertMutantCallableReturns(new BooleanReturn(), - createFirstMutant(BooleanReturn.class), "true"); - } - - @Test - public void describesMutationsToPrimitiveBooleans() { - assertMutantDescriptionIncludes("replaced boolean return with true", BooleanReturn.class); - assertMutantDescriptionIncludes("BooleanReturn::mutable", BooleanReturn.class); - } - - @Test - public void doesNotMutatePrimitiveIntReturns() throws Exception { - this.assertNoMutants(IntegerReturn.class); - } - - @Test - public void mutatesBoxedFalseToTrue() throws Exception { - assertMutantCallableReturns(new BoxedFalse(), - createFirstMutant(BoxedFalse.class), true); - } - - @Test - public void describesMutationsToBoxedBooleans() { - assertMutantDescriptionIncludes("replaced Boolean return with True", BoxedFalse.class); - assertMutantDescriptionIncludes("BoxedFalse::call", BoxedFalse.class); - } - - @Test - public void doesNotMutateBoxedIntegerReturns() throws Exception { - this.assertNoMutants(BoxedInteger.class); - } - - private static class BooleanReturn implements Callable { - public boolean mutable() { - return false; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - private static class IntegerReturn implements Callable { - public int mutable() { - return 42; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - - private static class BoxedFalse implements Callable { - @Override - public Boolean call() { - return false; - } - } - - private static class BoxedInteger implements Callable { - @Override - public Integer call() { - return 42; - } - } - - -} +package org.pitest.mutationtest.engine.gregor.mutators; + +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class BooleanTrueReturnValsMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyReturnVals() { + createTesteeWith(BooleanTrueReturnValsMutator.BOOLEAN_TRUE_RETURN); + } + + @Test + public void mutatesReturnFalseToReturnTrue() throws Exception { + assertMutantCallableReturns(new BooleanReturn(), + createFirstMutant(BooleanReturn.class), "true"); + } + + @Test + public void describesMutationsToPrimitiveBooleans() { + assertMutantDescriptionIncludes("replaced boolean return with true", BooleanReturn.class); + assertMutantDescriptionIncludes("BooleanReturn::mutable", BooleanReturn.class); + } + + @Test + public void doesNotMutatePrimitiveIntReturns() throws Exception { + this.assertNoMutants(IntegerReturn.class); + } + + @Test + public void mutatesBoxedFalseToTrue() throws Exception { + assertMutantCallableReturns(new BoxedFalse(), + createFirstMutant(BoxedFalse.class), true); + } + + @Test + public void describesMutationsToBoxedBooleans() { + assertMutantDescriptionIncludes("replaced Boolean return with True", BoxedFalse.class); + assertMutantDescriptionIncludes("BoxedFalse::call", BoxedFalse.class); + } + + @Test + public void doesNotMutateBoxedIntegerReturns() throws Exception { + this.assertNoMutants(BoxedInteger.class); + } + + private static class BooleanReturn implements Callable { + public boolean mutable() { + return false; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + private static class IntegerReturn implements Callable { + public int mutable() { + return 42; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + + private static class BoxedFalse implements Callable { + @Override + public Boolean call() { + return false; + } + } + + private static class BoxedInteger implements Callable { + @Override + public Integer call() { + return 42; + } + } + + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ConditionalsBoundaryMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ConditionalsBoundaryMutatorTest.java index 8d5300464..7ae9ed897 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ConditionalsBoundaryMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ConditionalsBoundaryMutatorTest.java @@ -1,247 +1,247 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.junit.Assert.assertEquals; - -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class ConditionalsBoundaryMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyConditionals() { - createTesteeWith(ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR); - } - - @Test - public void shouldProvideAMeaningfulName() { - assertEquals("CONDITIONALS_BOUNDARY_MUTATOR", - ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR.getName()); - } - - private static int getZeroButPreventInlining() { - return 0; - } - - private static class HasIFLE implements Callable { - private final int i; - - HasIFLE(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i > 0) { - return "was > zero"; - } else { - return "was <= zero"; - } - } - } - - @Test - public void shouldReplaceIFLEwithILT() throws Exception { - final Mutant mutant = getFirstMutant(HasIFLE.class); - assertMutantCallableReturns(new HasIFLE(1), mutant, "was > zero"); - assertMutantCallableReturns(new HasIFLE(-1), mutant, "was <= zero"); - assertMutantCallableReturns(new HasIFLE(0), mutant, "was > zero"); - } - - private static class HasIFGE implements Callable { - private final int i; - - HasIFGE(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i < 0) { - return "was < zero"; - } else { - return "was >= zero"; - } - } - } - - @Test - public void shouldReplaceIFGEwithIFGT() throws Exception { - final Mutant mutant = getFirstMutant(HasIFGE.class); - assertMutantCallableReturns(new HasIFGE(-1), mutant, "was < zero"); - assertMutantCallableReturns(new HasIFGE(1), mutant, "was >= zero"); - assertMutantCallableReturns(new HasIFGE(0), mutant, "was < zero"); - } - - private static class HasIFGT implements Callable { - private final int i; - - HasIFGT(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i <= 0) { - return "was <= zero"; - } else { - return "was > zero"; - } - } - } - - @Test - public void shouldReplaceIFGTwithIFGE() throws Exception { - final Mutant mutant = getFirstMutant(HasIFGT.class); - assertMutantCallableReturns(new HasIFGT(-1), mutant, "was <= zero"); - assertMutantCallableReturns(new HasIFGT(1), mutant, "was > zero"); - assertMutantCallableReturns(new HasIFGT(0), mutant, "was > zero"); - } - - private static class HasIFLT implements Callable { - private final int i; - - HasIFLT(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i >= 0) { - return "was >= zero"; - } else { - return "was < zero"; - } - } - } - - @Test - public void shouldReplaceIFLTwithIFLE() throws Exception { - final Mutant mutant = getFirstMutant(HasIFLT.class); - assertMutantCallableReturns(new HasIFLT(-1), mutant, "was < zero"); - assertMutantCallableReturns(new HasIFLT(1), mutant, "was >= zero"); - assertMutantCallableReturns(new HasIFLT(0), mutant, "was < zero"); - } - - private static class HasIF_ICMPLE implements Callable { - private final int i; - - HasIF_ICMPLE(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i > j) { - return "was > zero"; - } else { - return "was <= zero"; - } - } - } - - @Test - public void shouldReplaceICMPLEwithIF_ICMPLT() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPLE.class); - assertMutantCallableReturns(new HasIF_ICMPLE(1), mutant, "was > zero"); - assertMutantCallableReturns(new HasIF_ICMPLE(-1), mutant, "was <= zero"); - assertMutantCallableReturns(new HasIF_ICMPLE(0), mutant, "was > zero"); - } - - private static class HasIF_ICMPGE implements Callable { - private final int i; - - HasIF_ICMPGE(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i < j) { - return "was < zero"; - } else { - return "was >= zero"; - } - } - } - - @Test - public void shouldReplaceIF_ICMPGEwithIF_ICMPGT() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPGE.class); - assertMutantCallableReturns(new HasIF_ICMPGE(-1), mutant, "was < zero"); - assertMutantCallableReturns(new HasIF_ICMPGE(1), mutant, "was >= zero"); - assertMutantCallableReturns(new HasIF_ICMPGE(0), mutant, "was < zero"); - } - - private static class HasIF_ICMPGT implements Callable { - private final int i; - - HasIF_ICMPGT(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i <= j) { - return "was <= zero"; - } else { - return "was > zero"; - } - } - } - - @Test - public void shouldReplaceIF_ICMPGTwithIF_ICMPGE() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPGT.class); - assertMutantCallableReturns(new HasIF_ICMPGT(-1), mutant, "was <= zero"); - assertMutantCallableReturns(new HasIF_ICMPGT(1), mutant, "was > zero"); - assertMutantCallableReturns(new HasIF_ICMPGT(0), mutant, "was > zero"); - } - - private static class HasIF_ICMPLT implements Callable { - private final int i; - - HasIF_ICMPLT(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i >= j) { - return "was >= zero"; - } else { - return "was < zero"; - } - } - } - - @Test - public void shouldReplaceIF_ICMPLTwithIF_ICMPGT() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPLT.class); - assertMutantCallableReturns(new HasIF_ICMPLT(-1), mutant, "was < zero"); - assertMutantCallableReturns(new HasIF_ICMPLT(1), mutant, "was >= zero"); - assertMutantCallableReturns(new HasIF_ICMPLT(0), mutant, "was < zero"); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class ConditionalsBoundaryMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyConditionals() { + createTesteeWith(ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR); + } + + @Test + public void shouldProvideAMeaningfulName() { + assertEquals("CONDITIONALS_BOUNDARY_MUTATOR", + ConditionalsBoundaryMutator.CONDITIONALS_BOUNDARY_MUTATOR.getName()); + } + + private static int getZeroButPreventInlining() { + return 0; + } + + private static class HasIFLE implements Callable { + private final int i; + + HasIFLE(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i > 0) { + return "was > zero"; + } else { + return "was <= zero"; + } + } + } + + @Test + public void shouldReplaceIFLEwithILT() throws Exception { + final Mutant mutant = getFirstMutant(HasIFLE.class); + assertMutantCallableReturns(new HasIFLE(1), mutant, "was > zero"); + assertMutantCallableReturns(new HasIFLE(-1), mutant, "was <= zero"); + assertMutantCallableReturns(new HasIFLE(0), mutant, "was > zero"); + } + + private static class HasIFGE implements Callable { + private final int i; + + HasIFGE(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i < 0) { + return "was < zero"; + } else { + return "was >= zero"; + } + } + } + + @Test + public void shouldReplaceIFGEwithIFGT() throws Exception { + final Mutant mutant = getFirstMutant(HasIFGE.class); + assertMutantCallableReturns(new HasIFGE(-1), mutant, "was < zero"); + assertMutantCallableReturns(new HasIFGE(1), mutant, "was >= zero"); + assertMutantCallableReturns(new HasIFGE(0), mutant, "was < zero"); + } + + private static class HasIFGT implements Callable { + private final int i; + + HasIFGT(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i <= 0) { + return "was <= zero"; + } else { + return "was > zero"; + } + } + } + + @Test + public void shouldReplaceIFGTwithIFGE() throws Exception { + final Mutant mutant = getFirstMutant(HasIFGT.class); + assertMutantCallableReturns(new HasIFGT(-1), mutant, "was <= zero"); + assertMutantCallableReturns(new HasIFGT(1), mutant, "was > zero"); + assertMutantCallableReturns(new HasIFGT(0), mutant, "was > zero"); + } + + private static class HasIFLT implements Callable { + private final int i; + + HasIFLT(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i >= 0) { + return "was >= zero"; + } else { + return "was < zero"; + } + } + } + + @Test + public void shouldReplaceIFLTwithIFLE() throws Exception { + final Mutant mutant = getFirstMutant(HasIFLT.class); + assertMutantCallableReturns(new HasIFLT(-1), mutant, "was < zero"); + assertMutantCallableReturns(new HasIFLT(1), mutant, "was >= zero"); + assertMutantCallableReturns(new HasIFLT(0), mutant, "was < zero"); + } + + private static class HasIF_ICMPLE implements Callable { + private final int i; + + HasIF_ICMPLE(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i > j) { + return "was > zero"; + } else { + return "was <= zero"; + } + } + } + + @Test + public void shouldReplaceICMPLEwithIF_ICMPLT() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPLE.class); + assertMutantCallableReturns(new HasIF_ICMPLE(1), mutant, "was > zero"); + assertMutantCallableReturns(new HasIF_ICMPLE(-1), mutant, "was <= zero"); + assertMutantCallableReturns(new HasIF_ICMPLE(0), mutant, "was > zero"); + } + + private static class HasIF_ICMPGE implements Callable { + private final int i; + + HasIF_ICMPGE(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i < j) { + return "was < zero"; + } else { + return "was >= zero"; + } + } + } + + @Test + public void shouldReplaceIF_ICMPGEwithIF_ICMPGT() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPGE.class); + assertMutantCallableReturns(new HasIF_ICMPGE(-1), mutant, "was < zero"); + assertMutantCallableReturns(new HasIF_ICMPGE(1), mutant, "was >= zero"); + assertMutantCallableReturns(new HasIF_ICMPGE(0), mutant, "was < zero"); + } + + private static class HasIF_ICMPGT implements Callable { + private final int i; + + HasIF_ICMPGT(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i <= j) { + return "was <= zero"; + } else { + return "was > zero"; + } + } + } + + @Test + public void shouldReplaceIF_ICMPGTwithIF_ICMPGE() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPGT.class); + assertMutantCallableReturns(new HasIF_ICMPGT(-1), mutant, "was <= zero"); + assertMutantCallableReturns(new HasIF_ICMPGT(1), mutant, "was > zero"); + assertMutantCallableReturns(new HasIF_ICMPGT(0), mutant, "was > zero"); + } + + private static class HasIF_ICMPLT implements Callable { + private final int i; + + HasIF_ICMPLT(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i >= j) { + return "was >= zero"; + } else { + return "was < zero"; + } + } + } + + @Test + public void shouldReplaceIF_ICMPLTwithIF_ICMPGT() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPLT.class); + assertMutantCallableReturns(new HasIF_ICMPLT(-1), mutant, "was < zero"); + assertMutantCallableReturns(new HasIF_ICMPLT(1), mutant, "was >= zero"); + assertMutantCallableReturns(new HasIF_ICMPLT(0), mutant, "was < zero"); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ConstructorCallMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ConstructorCallMutatorTest.java index 915ad3b82..da7c29256 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ConstructorCallMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ConstructorCallMutatorTest.java @@ -1,127 +1,127 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; -import org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutatorTest.HasIntMethodCall; -import org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutatorTest.HasVoidMethodCall; - -public class ConstructorCallMutatorTest extends MutatorTestBase { - - static class HasConstructorCall implements Callable { - @Override - public String call() throws Exception { - final Integer i = new Integer(12); - return "" + (i == null); - } - } - - @Before - public void setupEngineToRemoveVoidMethods() { - createTesteeWith(mutateOnlyCallMethod(), - ConstructorCallMutator.CONSTRUCTOR_CALL_MUTATOR); - } - - @Test - public void shouldReplaceConstructorCallsWithNullValue() throws Exception { - final Mutant mutant = getFirstMutant(HasConstructorCall.class); - assertMutantCallableReturns(new HasConstructorCall(), mutant, "true"); - } - - @Test - public void shouldNotRemoveVoidMethodCalls() throws Exception { - assertDoesNotContain(findMutationsFor(HasVoidMethodCall.class), descriptionContaining("set")); - } - - @Test - public void shouldNotRemoveNonVoidMethods() throws Exception { - assertDoesNotContain(findMutationsFor(HasIntMethodCall.class), - descriptionContaining("set")); - } - - @Test - public void shouldNotRemoveCallsToSuper() throws Exception { - createTesteeWith(i -> true, - ConstructorCallMutator.CONSTRUCTOR_CALL_MUTATOR); - assertDoesNotContain(findMutationsFor(HasConstructorCall.class), - descriptionContaining("java/lang/Object::")); - } - - private static class HasDelegateConstructorCall implements Callable { - - private final int i; - - @SuppressWarnings("unused") - HasDelegateConstructorCall() { - this(1); - } - - HasDelegateConstructorCall(final int i) { - this.i = i; - } - - @Override - public String call() throws Exception { - return "" + this.i; - } - - } - - @Test - public void shouldNotRemoveCallsToDelegateContructor() throws Exception { - createTesteeWith(i -> true, - ConstructorCallMutator.CONSTRUCTOR_CALL_MUTATOR); - assertDoesNotContain(findMutationsFor(HasDelegateConstructorCall.class), - descriptionContaining("HasDelegateConstructorCall::")); - } - - private static class HasArrayListConstructor implements Callable { - - private List list; - - @Override - public String call() throws Exception { - - this.list = new ArrayList<>(); - - return "" + this.list; - } - } - - @Test - public void shouldCreateViableClassWhenMutatingArrayListConstructor() - throws Exception { - final Mutant mutant = getFirstMutant(HasArrayListConstructor.class); - assertMutantCallableReturns(new HasArrayListConstructor(), mutant, "null"); - } - - - private static void assertDoesNotContain(Collection c, Predicate p) { - assertThat(c.stream().filter(p).findFirst().isPresent()).isFalse(); - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; +import org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutatorTest.HasIntMethodCall; +import org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutatorTest.HasVoidMethodCall; + +public class ConstructorCallMutatorTest extends MutatorTestBase { + + static class HasConstructorCall implements Callable { + @Override + public String call() throws Exception { + final Integer i = new Integer(12); + return "" + (i == null); + } + } + + @Before + public void setupEngineToRemoveVoidMethods() { + createTesteeWith(mutateOnlyCallMethod(), + ConstructorCallMutator.CONSTRUCTOR_CALL_MUTATOR); + } + + @Test + public void shouldReplaceConstructorCallsWithNullValue() throws Exception { + final Mutant mutant = getFirstMutant(HasConstructorCall.class); + assertMutantCallableReturns(new HasConstructorCall(), mutant, "true"); + } + + @Test + public void shouldNotRemoveVoidMethodCalls() throws Exception { + assertDoesNotContain(findMutationsFor(HasVoidMethodCall.class), descriptionContaining("set")); + } + + @Test + public void shouldNotRemoveNonVoidMethods() throws Exception { + assertDoesNotContain(findMutationsFor(HasIntMethodCall.class), + descriptionContaining("set")); + } + + @Test + public void shouldNotRemoveCallsToSuper() throws Exception { + createTesteeWith(i -> true, + ConstructorCallMutator.CONSTRUCTOR_CALL_MUTATOR); + assertDoesNotContain(findMutationsFor(HasConstructorCall.class), + descriptionContaining("java/lang/Object::")); + } + + private static class HasDelegateConstructorCall implements Callable { + + private final int i; + + @SuppressWarnings("unused") + HasDelegateConstructorCall() { + this(1); + } + + HasDelegateConstructorCall(final int i) { + this.i = i; + } + + @Override + public String call() throws Exception { + return "" + this.i; + } + + } + + @Test + public void shouldNotRemoveCallsToDelegateContructor() throws Exception { + createTesteeWith(i -> true, + ConstructorCallMutator.CONSTRUCTOR_CALL_MUTATOR); + assertDoesNotContain(findMutationsFor(HasDelegateConstructorCall.class), + descriptionContaining("HasDelegateConstructorCall::")); + } + + private static class HasArrayListConstructor implements Callable { + + private List list; + + @Override + public String call() throws Exception { + + this.list = new ArrayList<>(); + + return "" + this.list; + } + } + + @Test + public void shouldCreateViableClassWhenMutatingArrayListConstructor() + throws Exception { + final Mutant mutant = getFirstMutant(HasArrayListConstructor.class); + assertMutantCallableReturns(new HasArrayListConstructor(), mutant, "null"); + } + + + private static void assertDoesNotContain(Collection c, Predicate p) { + assertThat(c.stream().filter(p).findFirst().isPresent()).isFalse(); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/EmptyObjectReturnValsTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/EmptyObjectReturnValsTest.java index bc6c2e72a..e3a9367a0 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/EmptyObjectReturnValsTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/EmptyObjectReturnValsTest.java @@ -1,250 +1,250 @@ -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class EmptyObjectReturnValsTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyReturnVals() { - createTesteeWith(EmptyObjectReturnValsMutator.EMPTY_RETURN_VALUES); - } - - @Test - public void doesNotMutateObjectReturnValuesWithNoEmptyValueOption() throws Exception { - final Collection actual = findMutationsFor( - ObjectReturn.class); - assertThat(actual).isEmpty(); - } - - @Test - public void mutatesBoxedIntegersToZero() throws Exception { - assertMutantCallableReturns(new BoxedInteger(), - createFirstMutant(BoxedInteger.class), 0); - } - - @Test - public void describesMutationsToIntegers() { - assertMutantDescriptionIncludes("replaced Integer return value with 0", BoxedInteger.class); - assertMutantDescriptionIncludes("BoxedInteger::call", BoxedInteger.class); - } - - @Test - public void doesNotMutateBoolean() throws Exception { - assertNoMutants(BoxedBoolean.class); - } - - @Test - public void mutatesBoxedShortsToZero() throws Exception { - assertMutantCallableReturns(new BoxedShort(), - createFirstMutant(BoxedShort.class), (short)0); - } - - @Test - public void describesMutationsToShorts() { - assertMutantDescriptionIncludes("replaced Short return value with 0", BoxedShort.class); - assertMutantDescriptionIncludes("BoxedShort::call", BoxedShort.class); - } - - @Test - public void mutatesBoxedCharsToZero() throws Exception { - assertMutantCallableReturns(new BoxedChar(), - createFirstMutant(BoxedChar.class), (char)0); - } - - @Test - public void describesMutationsToChars() { - assertMutantDescriptionIncludes("replaced Character return value with 0", BoxedChar.class); - assertMutantDescriptionIncludes("BoxedChar::call", BoxedChar.class); - } - - @Test - public void mutatesBoxedLongsToZero() throws Exception { - assertMutantCallableReturns(new BoxedLong(), - createFirstMutant(BoxedLong.class), 0l); - } - - @Test - public void describesMutationsToLongs() { - assertMutantDescriptionIncludes("replaced Long return value with 0", BoxedLong.class); - assertMutantDescriptionIncludes("BoxedLong::call", BoxedLong.class); - } - - @Test - public void mutatesBoxedFloatsToZero() throws Exception { - assertMutantCallableReturns(new BoxedFloat(), - createFirstMutant(BoxedFloat.class), 0f); - } - - @Test - public void describesMutationsToFloats() { - assertMutantDescriptionIncludes("replaced Float return value with 0", BoxedFloat.class); - assertMutantDescriptionIncludes("BoxedFloat::call", BoxedFloat.class); - } - - @Test - public void mutatesBoxedDoublesToZero() throws Exception { - assertMutantCallableReturns(new BoxedDouble(), - createFirstMutant(BoxedDouble.class), 0d); - } - - @Test - public void describesMutationsToDoubles() { - assertMutantDescriptionIncludes("replaced Double return value with 0", BoxedDouble.class); - assertMutantDescriptionIncludes("BoxedDouble::call", BoxedDouble.class); - } - - @Test - public void mutatesBoxedIntegersToZeroWhenAnnotatedNotNull() throws Exception { - assertMutantCallableReturns(new BoxedIntegerWithNoNullAnnotation(), - createFirstMutant(BoxedIntegerWithNoNullAnnotation.class), 0); - } - - @Test - public void mutatesToEmptyString() throws Exception { - assertMutantCallableReturns(new AString(), - createFirstMutant(AString.class), ""); - } - - @Test - public void describesMutationsToString() { - assertMutantDescriptionIncludes("replaced return value with \"\"", AString.class); - assertMutantDescriptionIncludes("AString::call", AString.class); - } - - @Test - public void mutatesListToEmptyList() throws Exception { - assertMutantCallableReturns(new AList(), - createFirstMutant(AList.class), Collections.emptyList()); - } - - @Test - public void mutatesSetToEmptySet() throws Exception { - assertMutantCallableReturns(new ASet(), - createFirstMutant(ASet.class), Collections.emptySet()); - } - - @Test - public void mutatesCollectionsToEmptyList() throws Exception { - assertMutantCallableReturns(new ACollection(), - createFirstMutant(ACollection.class), Collections.emptyList()); - } - -// must build on java 7 -// @Test -// public void mutatesToOptionalEmpty() throws Exception { -// assertMutantCallableReturns(new AnOptional(), -// createFirstMutant(AnOptional.class), Optional.empty()); -// } - - private static class ObjectReturn implements Callable { - @Override - public Object call() throws Exception { - return ""; - } - } - - private static class BoxedInteger implements Callable { - @Override - public Integer call() throws Exception { - return 1; - } - } - - private static class BoxedIntegerWithNoNullAnnotation implements Callable { - @Override - @NotNull - public Integer call() throws Exception { - return 1; - } - } - - private static class BoxedBoolean implements Callable { - @Override - public Boolean call() throws Exception { - return true; - } - } - - private static class BoxedShort implements Callable { - @Override - public Short call() throws Exception { - return 1; - } - } - - private static class BoxedChar implements Callable { - @Override - public Character call() throws Exception { - return 1; - } - } - - private static class BoxedLong implements Callable { - @Override - public Long call() throws Exception { - return 1l; - } - } - - private static class BoxedFloat implements Callable { - @Override - public Float call() throws Exception { - return 1f; - } - } - - private static class BoxedDouble implements Callable { - @Override - public Double call() throws Exception { - return 1d; - } - } - - private static class AString implements Callable { - @Override - public String call() throws Exception { - return "hello"; - } - } - - private static class AList implements Callable> { - @Override - public List call() throws Exception { - return Collections.singletonList(""); - } - } - - private static class ASet implements Callable> { - @Override - public Set call() throws Exception { - return Collections.singleton(""); - } - } - - private static class ACollection implements Callable> { - @Override - public Collection call() throws Exception { - return Collections.singleton(""); - } - } - -// private static class AnOptional implements Callable> { -// @Override -// public Optional call() throws Exception { -// return Optional.of("hello"); -// } -// } - - +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class EmptyObjectReturnValsTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyReturnVals() { + createTesteeWith(EmptyObjectReturnValsMutator.EMPTY_RETURN_VALUES); + } + + @Test + public void doesNotMutateObjectReturnValuesWithNoEmptyValueOption() throws Exception { + final Collection actual = findMutationsFor( + ObjectReturn.class); + assertThat(actual).isEmpty(); + } + + @Test + public void mutatesBoxedIntegersToZero() throws Exception { + assertMutantCallableReturns(new BoxedInteger(), + createFirstMutant(BoxedInteger.class), 0); + } + + @Test + public void describesMutationsToIntegers() { + assertMutantDescriptionIncludes("replaced Integer return value with 0", BoxedInteger.class); + assertMutantDescriptionIncludes("BoxedInteger::call", BoxedInteger.class); + } + + @Test + public void doesNotMutateBoolean() throws Exception { + assertNoMutants(BoxedBoolean.class); + } + + @Test + public void mutatesBoxedShortsToZero() throws Exception { + assertMutantCallableReturns(new BoxedShort(), + createFirstMutant(BoxedShort.class), (short)0); + } + + @Test + public void describesMutationsToShorts() { + assertMutantDescriptionIncludes("replaced Short return value with 0", BoxedShort.class); + assertMutantDescriptionIncludes("BoxedShort::call", BoxedShort.class); + } + + @Test + public void mutatesBoxedCharsToZero() throws Exception { + assertMutantCallableReturns(new BoxedChar(), + createFirstMutant(BoxedChar.class), (char)0); + } + + @Test + public void describesMutationsToChars() { + assertMutantDescriptionIncludes("replaced Character return value with 0", BoxedChar.class); + assertMutantDescriptionIncludes("BoxedChar::call", BoxedChar.class); + } + + @Test + public void mutatesBoxedLongsToZero() throws Exception { + assertMutantCallableReturns(new BoxedLong(), + createFirstMutant(BoxedLong.class), 0l); + } + + @Test + public void describesMutationsToLongs() { + assertMutantDescriptionIncludes("replaced Long return value with 0", BoxedLong.class); + assertMutantDescriptionIncludes("BoxedLong::call", BoxedLong.class); + } + + @Test + public void mutatesBoxedFloatsToZero() throws Exception { + assertMutantCallableReturns(new BoxedFloat(), + createFirstMutant(BoxedFloat.class), 0f); + } + + @Test + public void describesMutationsToFloats() { + assertMutantDescriptionIncludes("replaced Float return value with 0", BoxedFloat.class); + assertMutantDescriptionIncludes("BoxedFloat::call", BoxedFloat.class); + } + + @Test + public void mutatesBoxedDoublesToZero() throws Exception { + assertMutantCallableReturns(new BoxedDouble(), + createFirstMutant(BoxedDouble.class), 0d); + } + + @Test + public void describesMutationsToDoubles() { + assertMutantDescriptionIncludes("replaced Double return value with 0", BoxedDouble.class); + assertMutantDescriptionIncludes("BoxedDouble::call", BoxedDouble.class); + } + + @Test + public void mutatesBoxedIntegersToZeroWhenAnnotatedNotNull() throws Exception { + assertMutantCallableReturns(new BoxedIntegerWithNoNullAnnotation(), + createFirstMutant(BoxedIntegerWithNoNullAnnotation.class), 0); + } + + @Test + public void mutatesToEmptyString() throws Exception { + assertMutantCallableReturns(new AString(), + createFirstMutant(AString.class), ""); + } + + @Test + public void describesMutationsToString() { + assertMutantDescriptionIncludes("replaced return value with \"\"", AString.class); + assertMutantDescriptionIncludes("AString::call", AString.class); + } + + @Test + public void mutatesListToEmptyList() throws Exception { + assertMutantCallableReturns(new AList(), + createFirstMutant(AList.class), Collections.emptyList()); + } + + @Test + public void mutatesSetToEmptySet() throws Exception { + assertMutantCallableReturns(new ASet(), + createFirstMutant(ASet.class), Collections.emptySet()); + } + + @Test + public void mutatesCollectionsToEmptyList() throws Exception { + assertMutantCallableReturns(new ACollection(), + createFirstMutant(ACollection.class), Collections.emptyList()); + } + +// must build on java 7 +// @Test +// public void mutatesToOptionalEmpty() throws Exception { +// assertMutantCallableReturns(new AnOptional(), +// createFirstMutant(AnOptional.class), Optional.empty()); +// } + + private static class ObjectReturn implements Callable { + @Override + public Object call() throws Exception { + return ""; + } + } + + private static class BoxedInteger implements Callable { + @Override + public Integer call() throws Exception { + return 1; + } + } + + private static class BoxedIntegerWithNoNullAnnotation implements Callable { + @Override + @NotNull + public Integer call() throws Exception { + return 1; + } + } + + private static class BoxedBoolean implements Callable { + @Override + public Boolean call() throws Exception { + return true; + } + } + + private static class BoxedShort implements Callable { + @Override + public Short call() throws Exception { + return 1; + } + } + + private static class BoxedChar implements Callable { + @Override + public Character call() throws Exception { + return 1; + } + } + + private static class BoxedLong implements Callable { + @Override + public Long call() throws Exception { + return 1l; + } + } + + private static class BoxedFloat implements Callable { + @Override + public Float call() throws Exception { + return 1f; + } + } + + private static class BoxedDouble implements Callable { + @Override + public Double call() throws Exception { + return 1d; + } + } + + private static class AString implements Callable { + @Override + public String call() throws Exception { + return "hello"; + } + } + + private static class AList implements Callable> { + @Override + public List call() throws Exception { + return Collections.singletonList(""); + } + } + + private static class ASet implements Callable> { + @Override + public Set call() throws Exception { + return Collections.singleton(""); + } + } + + private static class ACollection implements Callable> { + @Override + public Collection call() throws Exception { + return Collections.singleton(""); + } + } + +// private static class AnOptional implements Callable> { +// @Override +// public Optional call() throws Exception { +// return Optional.of("hello"); +// } +// } + + } \ No newline at end of file diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/IncrementsMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/IncrementsMutatorTest.java index d013723fc..6b2deb585 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/IncrementsMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/IncrementsMutatorTest.java @@ -1,63 +1,63 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.junit.Assert.assertEquals; - -import java.util.Collection; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class IncrementsMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyIncrements() { - createTesteeWith(IncrementsMutator.INCREMENTS_MUTATOR); - } - - private static class HasIncrement implements Callable { - public int containsIincInstructions(int i) { - return ++i; - } - - @Override - public String call() throws Exception { - return "" + containsIincInstructions(1); - } - - } - - @Test - public void shouldNegateArgumentsToIInc() throws Exception { - final Collection actual = findMutationsFor(HasIncrement.class); - assertEquals(1, actual.size()); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new HasIncrement(), mutant, "0"); - } - - @Test - public void shouldRecordCorrectLineNumberForMutations() { - final Collection actual = findMutationsFor(HasIncrement.class); - assertEquals(1, actual.size()); - final MutationDetails first = actual.iterator().next(); - assertEquals(37, first.getLineNumber()); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.junit.Assert.assertEquals; + +import java.util.Collection; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class IncrementsMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyIncrements() { + createTesteeWith(IncrementsMutator.INCREMENTS_MUTATOR); + } + + private static class HasIncrement implements Callable { + public int containsIincInstructions(int i) { + return ++i; + } + + @Override + public String call() throws Exception { + return "" + containsIincInstructions(1); + } + + } + + @Test + public void shouldNegateArgumentsToIInc() throws Exception { + final Collection actual = findMutationsFor(HasIncrement.class); + assertEquals(1, actual.size()); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new HasIncrement(), mutant, "0"); + } + + @Test + public void shouldRecordCorrectLineNumberForMutations() { + final Collection actual = findMutationsFor(HasIncrement.class); + assertEquals(1, actual.size()); + final MutationDetails first = actual.iterator().next(); + assertEquals(37, first.getLineNumber()); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/InvertNegsMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/InvertNegsMutatorTest.java index 293f25d37..057cd1778 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/InvertNegsMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/InvertNegsMutatorTest.java @@ -1,106 +1,106 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.junit.Assert.assertEquals; - -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class InvertNegsMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyNegs() { - createTesteeWith(InvertNegsMutator.INVERT_NEGS_MUTATOR); - } - - private static class NothingToMutate { - - } - - @Test - public void shouldFindNoMutationsWhenNonePossible() { - final Collection actual = findMutationsFor(NothingToMutate.class); - assertEquals(Collections.emptyList(), actual); - } - - private static class HasINeg implements Callable { - public int containsINeg(final int i) { - return -i; - } - - @Override - public String call() throws Exception { - return "" + containsINeg(1); - } - - } - - @Test - public void shouldInvertINegs() throws Exception { - final Collection actual = findMutationsFor(HasINeg.class); - assertEquals(1, actual.size()); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new HasINeg(), mutant, "1"); - } - - private static class HasFNeg implements Callable { - public float containsFNeg(final float i) { - return -i; - } - - @Override - public String call() throws Exception { - return "" + containsFNeg(1f); - } - - } - - @Test - public void shouldInvertFNegs() throws Exception { - final Collection actual = findMutationsFor(HasFNeg.class); - assertEquals(1, actual.size()); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new HasFNeg(), mutant, "1.0"); - } - - private static class HasLNeg implements Callable { - public int containsLNeg(final int i) { - return -i; - } - - @Override - public String call() throws Exception { - return "" + containsLNeg(1); - } - - } - - @Test - public void shouldInvertLNegs() throws Exception { - final Collection actual = findMutationsFor(HasLNeg.class); - assertEquals(1, actual.size()); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new HasLNeg(), mutant, "1"); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.junit.Assert.assertEquals; + +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class InvertNegsMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyNegs() { + createTesteeWith(InvertNegsMutator.INVERT_NEGS_MUTATOR); + } + + private static class NothingToMutate { + + } + + @Test + public void shouldFindNoMutationsWhenNonePossible() { + final Collection actual = findMutationsFor(NothingToMutate.class); + assertEquals(Collections.emptyList(), actual); + } + + private static class HasINeg implements Callable { + public int containsINeg(final int i) { + return -i; + } + + @Override + public String call() throws Exception { + return "" + containsINeg(1); + } + + } + + @Test + public void shouldInvertINegs() throws Exception { + final Collection actual = findMutationsFor(HasINeg.class); + assertEquals(1, actual.size()); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new HasINeg(), mutant, "1"); + } + + private static class HasFNeg implements Callable { + public float containsFNeg(final float i) { + return -i; + } + + @Override + public String call() throws Exception { + return "" + containsFNeg(1f); + } + + } + + @Test + public void shouldInvertFNegs() throws Exception { + final Collection actual = findMutationsFor(HasFNeg.class); + assertEquals(1, actual.size()); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new HasFNeg(), mutant, "1.0"); + } + + private static class HasLNeg implements Callable { + public int containsLNeg(final int i) { + return -i; + } + + @Override + public String call() throws Exception { + return "" + containsLNeg(1); + } + + } + + @Test + public void shouldInvertLNegs() throws Exception { + final Collection actual = findMutationsFor(HasLNeg.class); + assertEquals(1, actual.size()); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new HasLNeg(), mutant, "1"); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/MathMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/MathMutatorTest.java index 8617b3564..c4db42a3b 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/MathMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/MathMutatorTest.java @@ -1,711 +1,711 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.mutators; - -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class MathMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyMathFunctions() { - createTesteeWith(MathMutator.MATH_MUTATOR); - } - - private static class HasIAdd implements Callable { - private int i; - - HasIAdd(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i++; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerAdditionWithSubtraction() throws Exception { - final Mutant mutant = getFirstMutant(HasIAdd.class); - assertMutantCallableReturns(new HasIAdd(2), mutant, "1"); - assertMutantCallableReturns(new HasIAdd(20), mutant, "19"); - } - - private static class HasISub implements Callable { - private int i; - - HasISub(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i--; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerSubtractionWithAddition() throws Exception { - final Mutant mutant = getFirstMutant(HasISub.class); - assertMutantCallableReturns(new HasISub(2), mutant, "3"); - assertMutantCallableReturns(new HasISub(20), mutant, "21"); - } - - private static class HasIMul implements Callable { - private int i; - - HasIMul(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i * 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerMultiplicationWithDivision() throws Exception { - final Mutant mutant = getFirstMutant(HasIMul.class); - assertMutantCallableReturns(new HasIMul(2), mutant, "1"); - assertMutantCallableReturns(new HasIMul(20), mutant, "10"); - } - - private static class HasIDiv implements Callable { - private int i; - - HasIDiv(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i / 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerDivisionWithMultiplication() throws Exception { - final Mutant mutant = getFirstMutant(HasIDiv.class); - assertMutantCallableReturns(new HasIDiv(2), mutant, "4"); - assertMutantCallableReturns(new HasIDiv(20), mutant, "40"); - } - - private static class HasIOr implements Callable { - private int i; - - HasIOr(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i | 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerBitwiseOrsWithAnds() throws Exception { - final Mutant mutant = getFirstMutant(HasIOr.class); - assertMutantCallableReturns(new HasIDiv(2), mutant, "1"); - assertMutantCallableReturns(new HasIOr(4), mutant, "0"); - } - - private static class HasIAnd implements Callable { - private int i; - - HasIAnd(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i & 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerBitwiseAndsWithOrs() throws Exception { - final Mutant mutant = getFirstMutant(HasIAnd.class); - assertMutantCallableReturns(new HasIAnd(2), mutant, "2"); - assertMutantCallableReturns(new HasIAnd(4), mutant, "6"); - } - - private static class HasIRem implements Callable { - private int i; - - HasIRem(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i % 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerModulusWithMultiplication() throws Exception { - final Mutant mutant = getFirstMutant(HasIRem.class); - assertMutantCallableReturns(new HasIRem(2), mutant, "4"); - assertMutantCallableReturns(new HasIRem(3), mutant, "6"); - } - - private static class HasIXor implements Callable { - private int i; - - HasIXor(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i ^ 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerXORWithAND() throws Exception { - final Mutant mutant = getFirstMutant(HasIXor.class); - assertMutantCallableReturns(new HasIXor(2), mutant, "2"); - assertMutantCallableReturns(new HasIXor(1), mutant, "0"); - } - - private static class HasISHL implements Callable { - private int i; - - HasISHL(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i << 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerShiftLeftWithShiftRight() throws Exception { - final Mutant mutant = getFirstMutant(HasISHL.class); - assertMutantCallableReturns(new HasISHL(100), mutant, "25"); - assertMutantCallableReturns(new HasISHL(20), mutant, "5"); - } - - private static class HasISHR implements Callable { - private int i; - - HasISHR(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i >> 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerShiftRightWithShiftLeft() throws Exception { - final Mutant mutant = getFirstMutant(HasISHR.class); - assertMutantCallableReturns(new HasISHR(100), mutant, "400"); - assertMutantCallableReturns(new HasISHR(20), mutant, "80"); - } - - private static class HasIUSHR implements Callable { - private int i; - - HasIUSHR(final int i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i >>> 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceIntegerUnsignedShiftRightWithShiftLeft() - throws Exception { - final Mutant mutant = getFirstMutant(HasIUSHR.class); - assertMutantCallableReturns(new HasIUSHR(100), mutant, "400"); - assertMutantCallableReturns(new HasIUSHR(20), mutant, "80"); - } - - // LONGS - - private static class HasLAdd implements Callable { - private long i; - - HasLAdd(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i++; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongAdditionWithSubtraction() throws Exception { - final Mutant mutant = getFirstMutant(HasLAdd.class); - assertMutantCallableReturns(new HasLAdd(2), mutant, "1"); - assertMutantCallableReturns(new HasLAdd(20), mutant, "19"); - } - - private static class HasLSub implements Callable { - private long i; - - HasLSub(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i--; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongSubtractionWithAddition() throws Exception { - final Mutant mutant = getFirstMutant(HasLSub.class); - assertMutantCallableReturns(new HasLSub(2), mutant, "3"); - assertMutantCallableReturns(new HasLSub(20), mutant, "21"); - } - - private static class HasLMul implements Callable { - private long i; - - HasLMul(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i * 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongMultiplicationWithDivision() throws Exception { - final Mutant mutant = getFirstMutant(HasLMul.class); - assertMutantCallableReturns(new HasLMul(2), mutant, "1"); - assertMutantCallableReturns(new HasLMul(20), mutant, "10"); - } - - private static class HasLDiv implements Callable { - private long i; - - HasLDiv(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i / 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongDivisionWithMultiplication() throws Exception { - final Mutant mutant = getFirstMutant(HasLDiv.class); - assertMutantCallableReturns(new HasLDiv(2), mutant, "4"); - assertMutantCallableReturns(new HasLDiv(20), mutant, "40"); - } - - private static class HasLOr implements Callable { - private long i; - - HasLOr(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i | 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongBitwiseOrsWithAnds() throws Exception { - final Mutant mutant = getFirstMutant(HasLOr.class); - assertMutantCallableReturns(new HasLDiv(2), mutant, "1"); - assertMutantCallableReturns(new HasLOr(4), mutant, "0"); - } - - private static class HasLAnd implements Callable { - private long i; - - HasLAnd(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i & 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongBitwiseAndsWithOrs() throws Exception { - final Mutant mutant = getFirstMutant(HasLAnd.class); - assertMutantCallableReturns(new HasLAnd(2), mutant, "2"); - assertMutantCallableReturns(new HasLAnd(4), mutant, "6"); - } - - private static class HasLRem implements Callable { - private long i; - - HasLRem(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i % 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongModulusWithMultiplication() throws Exception { - final Mutant mutant = getFirstMutant(HasLRem.class); - assertMutantCallableReturns(new HasLRem(2), mutant, "4"); - assertMutantCallableReturns(new HasLRem(3), mutant, "6"); - } - - private static class HasLXor implements Callable { - private long i; - - HasLXor(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i ^ 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongXORWithAND() throws Exception { - final Mutant mutant = getFirstMutant(HasLXor.class); - assertMutantCallableReturns(new HasLXor(2), mutant, "2"); - assertMutantCallableReturns(new HasLXor(1), mutant, "0"); - } - - private static class HasLSHL implements Callable { - private long i; - - HasLSHL(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i << 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongShiftLeftWithShiftRight() throws Exception { - final Mutant mutant = getFirstMutant(HasLSHL.class); - assertMutantCallableReturns(new HasLSHL(100), mutant, "25"); - assertMutantCallableReturns(new HasLSHL(20), mutant, "5"); - } - - private static class HasLSHR implements Callable { - private long i; - - HasLSHR(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i >> 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongShiftRightWithShiftLeft() throws Exception { - final Mutant mutant = getFirstMutant(HasLSHR.class); - assertMutantCallableReturns(new HasLSHR(100), mutant, "400"); - assertMutantCallableReturns(new HasLSHR(20), mutant, "80"); - } - - private static class HasLUSHR implements Callable { - private long i; - - HasLUSHR(final long i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i >>> 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceLongUnsignedShiftRightWithShiftLeft() - throws Exception { - final Mutant mutant = getFirstMutant(HasLUSHR.class); - assertMutantCallableReturns(new HasLUSHR(100), mutant, "400"); - assertMutantCallableReturns(new HasLUSHR(20), mutant, "80"); - } - - // FLOATS - - private static class HasFADD implements Callable { - private float i; - - HasFADD(final float i) { - this.i = i; - } - - @Override - public String call() { - this.i++; - return "" + this.i; - } - } - - @Test - public void shouldReplaceFloatAdditionWithSubtraction() throws Exception { - final Mutant mutant = getFirstMutant(HasFADD.class); - assertMutantCallableReturns(new HasFADD(2), mutant, "1.0"); - assertMutantCallableReturns(new HasFADD(20), mutant, "19.0"); - } - - private static class HasFSUB implements Callable { - private float i; - - HasFSUB(final float i) { - this.i = i; - } - - @Override - public String call() { - this.i--; - return "" + this.i; - } - } - - @Test - public void shouldReplaceFloatSubtractionWithAddition() throws Exception { - final Mutant mutant = getFirstMutant(HasFSUB.class); - assertMutantCallableReturns(new HasFSUB(2), mutant, "3.0"); - assertMutantCallableReturns(new HasFSUB(20), mutant, "21.0"); - } - - private static class HasFMUL implements Callable { - private float i; - - HasFMUL(final float i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i * 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceFloatMultiplicationWithDivision() throws Exception { - final Mutant mutant = getFirstMutant(HasFMUL.class); - assertMutantCallableReturns(new HasFMUL(2), mutant, "1.0"); - assertMutantCallableReturns(new HasFMUL(20), mutant, "10.0"); - } - - private static class HasFDIV implements Callable { - private float i; - - HasFDIV(final float i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i / 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceFloatDivisionWithMultiplication() throws Exception { - final Mutant mutant = getFirstMutant(HasFDIV.class); - assertMutantCallableReturns(new HasFDIV(2), mutant, "4.0"); - assertMutantCallableReturns(new HasFDIV(20), mutant, "40.0"); - } - - private static class HasFREM implements Callable { - private float i; - - HasFREM(final float i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i % 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceFloatModulusWithMultiplication() throws Exception { - final Mutant mutant = getFirstMutant(HasFREM.class); - assertMutantCallableReturns(new HasFREM(2), mutant, "4.0"); - assertMutantCallableReturns(new HasFREM(3), mutant, "6.0"); - } - - // double - - private static class HasDADD implements Callable { - private double i; - - HasDADD(final double i) { - this.i = i; - } - - @Override - public String call() { - this.i++; - return "" + this.i; - } - } - - @Test - public void shouldReplaceDoubleAdditionWithSubtraction() throws Exception { - final Mutant mutant = getFirstMutant(HasDADD.class); - assertMutantCallableReturns(new HasDADD(2), mutant, "1.0"); - assertMutantCallableReturns(new HasDADD(20), mutant, "19.0"); - } - - private static class HasDSUB implements Callable { - private double i; - - HasDSUB(final double i) { - this.i = i; - } - - @Override - public String call() { - this.i--; - return "" + this.i; - } - } - - @Test - public void shouldReplaceDoubleSubtractionWithAddition() throws Exception { - final Mutant mutant = getFirstMutant(HasDSUB.class); - assertMutantCallableReturns(new HasDSUB(2), mutant, "3.0"); - assertMutantCallableReturns(new HasDSUB(20), mutant, "21.0"); - } - - private static class HasDMUL implements Callable { - private double i; - - HasDMUL(final double i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i * 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceDoubleMultiplicationWithDivision() throws Exception { - final Mutant mutant = getFirstMutant(HasDMUL.class); - assertMutantCallableReturns(new HasDMUL(2), mutant, "1.0"); - assertMutantCallableReturns(new HasDMUL(20), mutant, "10.0"); - } - - private static class HasDDIV implements Callable { - private double i; - - HasDDIV(final double i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i / 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceDoubleDivisionWithMultiplication() throws Exception { - final Mutant mutant = getFirstMutant(HasDDIV.class); - assertMutantCallableReturns(new HasDDIV(2), mutant, "4.0"); - assertMutantCallableReturns(new HasDDIV(20), mutant, "40.0"); - } - - private static class HasDREM implements Callable { - private double i; - - HasDREM(final double i) { - this.i = i; - } - - @Override - public String call() { - this.i = this.i % 2; - return "" + this.i; - } - } - - @Test - public void shouldReplaceDoublerModulusWithMultiplication() throws Exception { - final Mutant mutant = getFirstMutant(HasDREM.class); - assertMutantCallableReturns(new HasDREM(2), mutant, "4.0"); - assertMutantCallableReturns(new HasDREM(3), mutant, "6.0"); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.mutators; + +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class MathMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyMathFunctions() { + createTesteeWith(MathMutator.MATH_MUTATOR); + } + + private static class HasIAdd implements Callable { + private int i; + + HasIAdd(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i++; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerAdditionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasIAdd.class); + assertMutantCallableReturns(new HasIAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasIAdd(20), mutant, "19"); + } + + private static class HasISub implements Callable { + private int i; + + HasISub(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i--; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerSubtractionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasISub.class); + assertMutantCallableReturns(new HasISub(2), mutant, "3"); + assertMutantCallableReturns(new HasISub(20), mutant, "21"); + } + + private static class HasIMul implements Callable { + private int i; + + HasIMul(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i * 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerMultiplicationWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasIMul.class); + assertMutantCallableReturns(new HasIMul(2), mutant, "1"); + assertMutantCallableReturns(new HasIMul(20), mutant, "10"); + } + + private static class HasIDiv implements Callable { + private int i; + + HasIDiv(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i / 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerDivisionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasIDiv.class); + assertMutantCallableReturns(new HasIDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasIDiv(20), mutant, "40"); + } + + private static class HasIOr implements Callable { + private int i; + + HasIOr(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i | 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerBitwiseOrsWithAnds() throws Exception { + final Mutant mutant = getFirstMutant(HasIOr.class); + assertMutantCallableReturns(new HasIDiv(2), mutant, "1"); + assertMutantCallableReturns(new HasIOr(4), mutant, "0"); + } + + private static class HasIAnd implements Callable { + private int i; + + HasIAnd(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i & 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerBitwiseAndsWithOrs() throws Exception { + final Mutant mutant = getFirstMutant(HasIAnd.class); + assertMutantCallableReturns(new HasIAnd(2), mutant, "2"); + assertMutantCallableReturns(new HasIAnd(4), mutant, "6"); + } + + private static class HasIRem implements Callable { + private int i; + + HasIRem(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i % 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerModulusWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasIRem.class); + assertMutantCallableReturns(new HasIRem(2), mutant, "4"); + assertMutantCallableReturns(new HasIRem(3), mutant, "6"); + } + + private static class HasIXor implements Callable { + private int i; + + HasIXor(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i ^ 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerXORWithAND() throws Exception { + final Mutant mutant = getFirstMutant(HasIXor.class); + assertMutantCallableReturns(new HasIXor(2), mutant, "2"); + assertMutantCallableReturns(new HasIXor(1), mutant, "0"); + } + + private static class HasISHL implements Callable { + private int i; + + HasISHL(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i << 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerShiftLeftWithShiftRight() throws Exception { + final Mutant mutant = getFirstMutant(HasISHL.class); + assertMutantCallableReturns(new HasISHL(100), mutant, "25"); + assertMutantCallableReturns(new HasISHL(20), mutant, "5"); + } + + private static class HasISHR implements Callable { + private int i; + + HasISHR(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i >> 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerShiftRightWithShiftLeft() throws Exception { + final Mutant mutant = getFirstMutant(HasISHR.class); + assertMutantCallableReturns(new HasISHR(100), mutant, "400"); + assertMutantCallableReturns(new HasISHR(20), mutant, "80"); + } + + private static class HasIUSHR implements Callable { + private int i; + + HasIUSHR(final int i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i >>> 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceIntegerUnsignedShiftRightWithShiftLeft() + throws Exception { + final Mutant mutant = getFirstMutant(HasIUSHR.class); + assertMutantCallableReturns(new HasIUSHR(100), mutant, "400"); + assertMutantCallableReturns(new HasIUSHR(20), mutant, "80"); + } + + // LONGS + + private static class HasLAdd implements Callable { + private long i; + + HasLAdd(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i++; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongAdditionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasLAdd.class); + assertMutantCallableReturns(new HasLAdd(2), mutant, "1"); + assertMutantCallableReturns(new HasLAdd(20), mutant, "19"); + } + + private static class HasLSub implements Callable { + private long i; + + HasLSub(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i--; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongSubtractionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasLSub.class); + assertMutantCallableReturns(new HasLSub(2), mutant, "3"); + assertMutantCallableReturns(new HasLSub(20), mutant, "21"); + } + + private static class HasLMul implements Callable { + private long i; + + HasLMul(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i * 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongMultiplicationWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasLMul.class); + assertMutantCallableReturns(new HasLMul(2), mutant, "1"); + assertMutantCallableReturns(new HasLMul(20), mutant, "10"); + } + + private static class HasLDiv implements Callable { + private long i; + + HasLDiv(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i / 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongDivisionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasLDiv.class); + assertMutantCallableReturns(new HasLDiv(2), mutant, "4"); + assertMutantCallableReturns(new HasLDiv(20), mutant, "40"); + } + + private static class HasLOr implements Callable { + private long i; + + HasLOr(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i | 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongBitwiseOrsWithAnds() throws Exception { + final Mutant mutant = getFirstMutant(HasLOr.class); + assertMutantCallableReturns(new HasLDiv(2), mutant, "1"); + assertMutantCallableReturns(new HasLOr(4), mutant, "0"); + } + + private static class HasLAnd implements Callable { + private long i; + + HasLAnd(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i & 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongBitwiseAndsWithOrs() throws Exception { + final Mutant mutant = getFirstMutant(HasLAnd.class); + assertMutantCallableReturns(new HasLAnd(2), mutant, "2"); + assertMutantCallableReturns(new HasLAnd(4), mutant, "6"); + } + + private static class HasLRem implements Callable { + private long i; + + HasLRem(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i % 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongModulusWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasLRem.class); + assertMutantCallableReturns(new HasLRem(2), mutant, "4"); + assertMutantCallableReturns(new HasLRem(3), mutant, "6"); + } + + private static class HasLXor implements Callable { + private long i; + + HasLXor(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i ^ 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongXORWithAND() throws Exception { + final Mutant mutant = getFirstMutant(HasLXor.class); + assertMutantCallableReturns(new HasLXor(2), mutant, "2"); + assertMutantCallableReturns(new HasLXor(1), mutant, "0"); + } + + private static class HasLSHL implements Callable { + private long i; + + HasLSHL(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i << 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongShiftLeftWithShiftRight() throws Exception { + final Mutant mutant = getFirstMutant(HasLSHL.class); + assertMutantCallableReturns(new HasLSHL(100), mutant, "25"); + assertMutantCallableReturns(new HasLSHL(20), mutant, "5"); + } + + private static class HasLSHR implements Callable { + private long i; + + HasLSHR(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i >> 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongShiftRightWithShiftLeft() throws Exception { + final Mutant mutant = getFirstMutant(HasLSHR.class); + assertMutantCallableReturns(new HasLSHR(100), mutant, "400"); + assertMutantCallableReturns(new HasLSHR(20), mutant, "80"); + } + + private static class HasLUSHR implements Callable { + private long i; + + HasLUSHR(final long i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i >>> 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceLongUnsignedShiftRightWithShiftLeft() + throws Exception { + final Mutant mutant = getFirstMutant(HasLUSHR.class); + assertMutantCallableReturns(new HasLUSHR(100), mutant, "400"); + assertMutantCallableReturns(new HasLUSHR(20), mutant, "80"); + } + + // FLOATS + + private static class HasFADD implements Callable { + private float i; + + HasFADD(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i++; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatAdditionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasFADD.class); + assertMutantCallableReturns(new HasFADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFADD(20), mutant, "19.0"); + } + + private static class HasFSUB implements Callable { + private float i; + + HasFSUB(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i--; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatSubtractionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasFSUB.class); + assertMutantCallableReturns(new HasFSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasFSUB(20), mutant, "21.0"); + } + + private static class HasFMUL implements Callable { + private float i; + + HasFMUL(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i * 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatMultiplicationWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasFMUL.class); + assertMutantCallableReturns(new HasFMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasFMUL(20), mutant, "10.0"); + } + + private static class HasFDIV implements Callable { + private float i; + + HasFDIV(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i / 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatDivisionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasFDIV.class); + assertMutantCallableReturns(new HasFDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFDIV(20), mutant, "40.0"); + } + + private static class HasFREM implements Callable { + private float i; + + HasFREM(final float i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i % 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceFloatModulusWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasFREM.class); + assertMutantCallableReturns(new HasFREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasFREM(3), mutant, "6.0"); + } + + // double + + private static class HasDADD implements Callable { + private double i; + + HasDADD(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i++; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoubleAdditionWithSubtraction() throws Exception { + final Mutant mutant = getFirstMutant(HasDADD.class); + assertMutantCallableReturns(new HasDADD(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDADD(20), mutant, "19.0"); + } + + private static class HasDSUB implements Callable { + private double i; + + HasDSUB(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i--; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoubleSubtractionWithAddition() throws Exception { + final Mutant mutant = getFirstMutant(HasDSUB.class); + assertMutantCallableReturns(new HasDSUB(2), mutant, "3.0"); + assertMutantCallableReturns(new HasDSUB(20), mutant, "21.0"); + } + + private static class HasDMUL implements Callable { + private double i; + + HasDMUL(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i * 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoubleMultiplicationWithDivision() throws Exception { + final Mutant mutant = getFirstMutant(HasDMUL.class); + assertMutantCallableReturns(new HasDMUL(2), mutant, "1.0"); + assertMutantCallableReturns(new HasDMUL(20), mutant, "10.0"); + } + + private static class HasDDIV implements Callable { + private double i; + + HasDDIV(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i / 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoubleDivisionWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasDDIV.class); + assertMutantCallableReturns(new HasDDIV(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDDIV(20), mutant, "40.0"); + } + + private static class HasDREM implements Callable { + private double i; + + HasDREM(final double i) { + this.i = i; + } + + @Override + public String call() { + this.i = this.i % 2; + return "" + this.i; + } + } + + @Test + public void shouldReplaceDoublerModulusWithMultiplication() throws Exception { + final Mutant mutant = getFirstMutant(HasDREM.class); + assertMutantCallableReturns(new HasDREM(2), mutant, "4.0"); + assertMutantCallableReturns(new HasDREM(3), mutant, "6.0"); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NegateConditionalsMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NegateConditionalsMutatorTest.java index 37e01af7d..1a6778c90 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NegateConditionalsMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NegateConditionalsMutatorTest.java @@ -1,440 +1,440 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.mutators; - -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class NegateConditionalsMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyConditionals() { - createTesteeWith(NegateConditionalsMutator.NEGATE_CONDITIONALS_MUTATOR); - } - - private static int getZeroButPreventInlining() { - return 0; - } - - private static class HasIFEQ implements Callable { - private final int i; - - HasIFEQ(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i != 0) { - return "was not zero"; - } else { - return "was zero"; - } - } - } - - @Test - public void shouldReplaceIFEQWithIFNE() throws Exception { - final Mutant mutant = getFirstMutant(HasIFEQ.class); - assertMutantCallableReturns(new HasIFEQ(1), mutant, "was zero"); - assertMutantCallableReturns(new HasIFEQ(0), mutant, "was not zero"); - } - - private static class HasIFNE implements Callable { - private final int i; - - HasIFNE(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i == 0) { - return "was zero"; - } else { - return "was not zero"; - } - } - } - - @Test - public void shouldReplaceIFNEWithIFEQ() throws Exception { - final Mutant mutant = getFirstMutant(HasIFNE.class); - assertMutantCallableReturns(new HasIFNE(1), mutant, "was zero"); - assertMutantCallableReturns(new HasIFNE(0), mutant, "was not zero"); - } - - private static class HasIFLE implements Callable { - private final int i; - - HasIFLE(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i > 0) { - return "was > zero"; - } else { - return "was <= zero"; - } - } - } - - @Test - public void shouldReplaceIFLEWithIGT() throws Exception { - final Mutant mutant = getFirstMutant(HasIFLE.class); - assertMutantCallableReturns(new HasIFLE(1), mutant, "was <= zero"); - assertMutantCallableReturns(new HasIFLE(-1), mutant, "was > zero"); - assertMutantCallableReturns(new HasIFLE(0), mutant, "was > zero"); - } - - private static class HasIFGE implements Callable { - private final int i; - - HasIFGE(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i < 0) { - return "was < zero"; - } else { - return "was >= zero"; - } - } - } - - @Test - public void shouldReplaceIFGEWithIFLT() throws Exception { - final Mutant mutant = getFirstMutant(HasIFGE.class); - assertMutantCallableReturns(new HasIFGE(-1), mutant, "was >= zero"); - assertMutantCallableReturns(new HasIFGE(1), mutant, "was < zero"); - assertMutantCallableReturns(new HasIFGE(0), mutant, "was < zero"); - } - - private static class HasIFGT implements Callable { - private final int i; - - HasIFGT(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i <= 0) { - return "was <= zero"; - } else { - return "was > zero"; - } - } - } - - @Test - public void shouldReplaceIFGTWithIFLE() throws Exception { - final Mutant mutant = getFirstMutant(HasIFGT.class); - assertMutantCallableReturns(new HasIFGT(-1), mutant, "was > zero"); - assertMutantCallableReturns(new HasIFGT(1), mutant, "was <= zero"); - assertMutantCallableReturns(new HasIFGT(0), mutant, "was > zero"); - } - - private static class HasIFLT implements Callable { - private final int i; - - HasIFLT(final int i) { - this.i = i; - } - - @Override - public String call() { - if (this.i >= 0) { - return "was >= zero"; - } else { - return "was < zero"; - } - } - } - - @Test - public void shouldReplaceIFLTWithIFGE() throws Exception { - final Mutant mutant = getFirstMutant(HasIFLT.class); - assertMutantCallableReturns(new HasIFLT(-1), mutant, "was >= zero"); - assertMutantCallableReturns(new HasIFLT(1), mutant, "was < zero"); - assertMutantCallableReturns(new HasIFLT(0), mutant, "was < zero"); - } - - private static class HasIFNULL implements Callable { - private final Object i; - - HasIFNULL(final Object i) { - this.i = i; - } - - @Override - public String call() { - if (this.i != null) { - return "was not null"; - } else { - return "was null"; - } - } - } - - @Test - public void shouldReplaceIFNULLWithIFNONNULL() throws Exception { - final Mutant mutant = getFirstMutant(HasIFNULL.class); - assertMutantCallableReturns(new HasIFNULL(null), mutant, "was not null"); - assertMutantCallableReturns(new HasIFNULL("foo"), mutant, "was null"); - } - - private static class HasIFNONNULL implements Callable { - private final Object i; - - HasIFNONNULL(final Object i) { - this.i = i; - } - - @Override - public String call() { - if (this.i == null) { - return "was null"; - } else { - return "was not null"; - } - } - } - - @Test - public void shouldReplaceIFNONNULLWithIFNULL() throws Exception { - final Mutant mutant = getFirstMutant(HasIFNONNULL.class); - assertMutantCallableReturns(new HasIFNONNULL(null), mutant, "was not null"); - assertMutantCallableReturns(new HasIFNONNULL("foo"), mutant, "was null"); - } - - private static class HasIF_ICMPNE implements Callable { - private final int i; - - HasIF_ICMPNE(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i == j) { - return "was zero"; - } else { - return "was not zero"; - } - } - } - - @Test - public void shouldReplaceIF_ICMPNEWithIF_CMPEQ() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPNE.class); - assertMutantCallableReturns(new HasIF_ICMPNE(1), mutant, "was zero"); - assertMutantCallableReturns(new HasIF_ICMPNE(0), mutant, "was not zero"); - } - - private static class HasIF_ICMPEQ implements Callable { - private final int i; - - HasIF_ICMPEQ(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i != j) { - return "was not zero"; - } else { - return "was zero"; - } - } - } - - @Test - public void shouldReplaceIF_ICMPEQWithIF_CMPNE() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPEQ.class); - assertMutantCallableReturns(new HasIF_ICMPEQ(1), mutant, "was zero"); - assertMutantCallableReturns(new HasIF_ICMPEQ(0), mutant, "was not zero"); - } - - private static class HasIF_ICMPLE implements Callable { - private final int i; - - HasIF_ICMPLE(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i > j) { - return "was > zero"; - } else { - return "was <= zero"; - } - } - } - - @Test - public void shouldReplaceHasIF_ICMPLEWithHasIF_ICMPGT() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPLE.class); - assertMutantCallableReturns(new HasIF_ICMPLE(1), mutant, "was <= zero"); - assertMutantCallableReturns(new HasIF_ICMPLE(-1), mutant, "was > zero"); - assertMutantCallableReturns(new HasIF_ICMPLE(0), mutant, "was > zero"); - } - - private static class HasIF_ICMPGE implements Callable { - private final int i; - - HasIF_ICMPGE(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i < j) { - return "was < zero"; - } else { - return "was >= zero"; - } - } - } - - @Test - public void shouldReplaceIF_ICMPGEWithHasIF_ICMPLT() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPGE.class); - assertMutantCallableReturns(new HasIF_ICMPGE(-1), mutant, "was >= zero"); - assertMutantCallableReturns(new HasIF_ICMPGE(1), mutant, "was < zero"); - assertMutantCallableReturns(new HasIF_ICMPGE(0), mutant, "was < zero"); - } - - private static class HasIF_ICMPGT implements Callable { - private final int i; - - HasIF_ICMPGT(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i <= j) { - return "was <= zero"; - } else { - return "was > zero"; - } - } - } - - @Test - public void shouldReplaceHasIF_ICMPGTWithHasIF_ICMPLE() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPGT.class); - assertMutantCallableReturns(new HasIF_ICMPGT(-1), mutant, "was > zero"); - assertMutantCallableReturns(new HasIF_ICMPGT(1), mutant, "was <= zero"); - assertMutantCallableReturns(new HasIF_ICMPGT(0), mutant, "was > zero"); - } - - private static class HasIF_ICMPLT implements Callable { - private final int i; - - HasIF_ICMPLT(final int i) { - this.i = i; - } - - @Override - public String call() { - final int j = getZeroButPreventInlining(); - if (this.i >= j) { - return "was >= zero"; - } else { - return "was < zero"; - } - } - } - - @Test - public void shouldReplaceHasIF_ICMPLTWithHasIF_ICMPGE() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ICMPLT.class); - assertMutantCallableReturns(new HasIF_ICMPLT(-1), mutant, "was >= zero"); - assertMutantCallableReturns(new HasIF_ICMPLT(1), mutant, "was < zero"); - assertMutantCallableReturns(new HasIF_ICMPLT(0), mutant, "was < zero"); - } - - private static class HasIF_ACMPNE implements Callable { - private final Object i; - - HasIF_ACMPNE(final Object i) { - this.i = i; - } - - @Override - public String call() { - final Object integer = Integer.class; - if (this.i == integer) { - return "was integer"; - } else { - return "was not integer"; - } - } - } - - @Test - public void shouldReplaceIF_ACMPNEWithIF_CMPEQ() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ACMPNE.class); - printMutant(mutant); - assertMutantCallableReturns(new HasIF_ACMPNE(String.class), mutant, - "was integer"); - assertMutantCallableReturns(new HasIF_ACMPNE(Integer.class), mutant, - "was not integer"); - } - - private static class HasIF_ACMPEQ implements Callable { - private final Object i; - - HasIF_ACMPEQ(final Object i) { - this.i = i; - } - - @Override - public String call() { - final Object integer = Integer.class; - if (this.i != integer) { - return "was not integer"; - } else { - return "was integer"; - } - } - } - - @Test - public void shouldReplaceIF_ACMPEQWithIF_CMPNE() throws Exception { - final Mutant mutant = getFirstMutant(HasIF_ACMPEQ.class); - assertMutantCallableReturns(new HasIF_ACMPEQ(String.class), mutant, - "was integer"); - assertMutantCallableReturns(new HasIF_ACMPEQ(Integer.class), mutant, - "was not integer"); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.mutators; + +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class NegateConditionalsMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyConditionals() { + createTesteeWith(NegateConditionalsMutator.NEGATE_CONDITIONALS_MUTATOR); + } + + private static int getZeroButPreventInlining() { + return 0; + } + + private static class HasIFEQ implements Callable { + private final int i; + + HasIFEQ(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i != 0) { + return "was not zero"; + } else { + return "was zero"; + } + } + } + + @Test + public void shouldReplaceIFEQWithIFNE() throws Exception { + final Mutant mutant = getFirstMutant(HasIFEQ.class); + assertMutantCallableReturns(new HasIFEQ(1), mutant, "was zero"); + assertMutantCallableReturns(new HasIFEQ(0), mutant, "was not zero"); + } + + private static class HasIFNE implements Callable { + private final int i; + + HasIFNE(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i == 0) { + return "was zero"; + } else { + return "was not zero"; + } + } + } + + @Test + public void shouldReplaceIFNEWithIFEQ() throws Exception { + final Mutant mutant = getFirstMutant(HasIFNE.class); + assertMutantCallableReturns(new HasIFNE(1), mutant, "was zero"); + assertMutantCallableReturns(new HasIFNE(0), mutant, "was not zero"); + } + + private static class HasIFLE implements Callable { + private final int i; + + HasIFLE(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i > 0) { + return "was > zero"; + } else { + return "was <= zero"; + } + } + } + + @Test + public void shouldReplaceIFLEWithIGT() throws Exception { + final Mutant mutant = getFirstMutant(HasIFLE.class); + assertMutantCallableReturns(new HasIFLE(1), mutant, "was <= zero"); + assertMutantCallableReturns(new HasIFLE(-1), mutant, "was > zero"); + assertMutantCallableReturns(new HasIFLE(0), mutant, "was > zero"); + } + + private static class HasIFGE implements Callable { + private final int i; + + HasIFGE(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i < 0) { + return "was < zero"; + } else { + return "was >= zero"; + } + } + } + + @Test + public void shouldReplaceIFGEWithIFLT() throws Exception { + final Mutant mutant = getFirstMutant(HasIFGE.class); + assertMutantCallableReturns(new HasIFGE(-1), mutant, "was >= zero"); + assertMutantCallableReturns(new HasIFGE(1), mutant, "was < zero"); + assertMutantCallableReturns(new HasIFGE(0), mutant, "was < zero"); + } + + private static class HasIFGT implements Callable { + private final int i; + + HasIFGT(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i <= 0) { + return "was <= zero"; + } else { + return "was > zero"; + } + } + } + + @Test + public void shouldReplaceIFGTWithIFLE() throws Exception { + final Mutant mutant = getFirstMutant(HasIFGT.class); + assertMutantCallableReturns(new HasIFGT(-1), mutant, "was > zero"); + assertMutantCallableReturns(new HasIFGT(1), mutant, "was <= zero"); + assertMutantCallableReturns(new HasIFGT(0), mutant, "was > zero"); + } + + private static class HasIFLT implements Callable { + private final int i; + + HasIFLT(final int i) { + this.i = i; + } + + @Override + public String call() { + if (this.i >= 0) { + return "was >= zero"; + } else { + return "was < zero"; + } + } + } + + @Test + public void shouldReplaceIFLTWithIFGE() throws Exception { + final Mutant mutant = getFirstMutant(HasIFLT.class); + assertMutantCallableReturns(new HasIFLT(-1), mutant, "was >= zero"); + assertMutantCallableReturns(new HasIFLT(1), mutant, "was < zero"); + assertMutantCallableReturns(new HasIFLT(0), mutant, "was < zero"); + } + + private static class HasIFNULL implements Callable { + private final Object i; + + HasIFNULL(final Object i) { + this.i = i; + } + + @Override + public String call() { + if (this.i != null) { + return "was not null"; + } else { + return "was null"; + } + } + } + + @Test + public void shouldReplaceIFNULLWithIFNONNULL() throws Exception { + final Mutant mutant = getFirstMutant(HasIFNULL.class); + assertMutantCallableReturns(new HasIFNULL(null), mutant, "was not null"); + assertMutantCallableReturns(new HasIFNULL("foo"), mutant, "was null"); + } + + private static class HasIFNONNULL implements Callable { + private final Object i; + + HasIFNONNULL(final Object i) { + this.i = i; + } + + @Override + public String call() { + if (this.i == null) { + return "was null"; + } else { + return "was not null"; + } + } + } + + @Test + public void shouldReplaceIFNONNULLWithIFNULL() throws Exception { + final Mutant mutant = getFirstMutant(HasIFNONNULL.class); + assertMutantCallableReturns(new HasIFNONNULL(null), mutant, "was not null"); + assertMutantCallableReturns(new HasIFNONNULL("foo"), mutant, "was null"); + } + + private static class HasIF_ICMPNE implements Callable { + private final int i; + + HasIF_ICMPNE(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i == j) { + return "was zero"; + } else { + return "was not zero"; + } + } + } + + @Test + public void shouldReplaceIF_ICMPNEWithIF_CMPEQ() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPNE.class); + assertMutantCallableReturns(new HasIF_ICMPNE(1), mutant, "was zero"); + assertMutantCallableReturns(new HasIF_ICMPNE(0), mutant, "was not zero"); + } + + private static class HasIF_ICMPEQ implements Callable { + private final int i; + + HasIF_ICMPEQ(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i != j) { + return "was not zero"; + } else { + return "was zero"; + } + } + } + + @Test + public void shouldReplaceIF_ICMPEQWithIF_CMPNE() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPEQ.class); + assertMutantCallableReturns(new HasIF_ICMPEQ(1), mutant, "was zero"); + assertMutantCallableReturns(new HasIF_ICMPEQ(0), mutant, "was not zero"); + } + + private static class HasIF_ICMPLE implements Callable { + private final int i; + + HasIF_ICMPLE(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i > j) { + return "was > zero"; + } else { + return "was <= zero"; + } + } + } + + @Test + public void shouldReplaceHasIF_ICMPLEWithHasIF_ICMPGT() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPLE.class); + assertMutantCallableReturns(new HasIF_ICMPLE(1), mutant, "was <= zero"); + assertMutantCallableReturns(new HasIF_ICMPLE(-1), mutant, "was > zero"); + assertMutantCallableReturns(new HasIF_ICMPLE(0), mutant, "was > zero"); + } + + private static class HasIF_ICMPGE implements Callable { + private final int i; + + HasIF_ICMPGE(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i < j) { + return "was < zero"; + } else { + return "was >= zero"; + } + } + } + + @Test + public void shouldReplaceIF_ICMPGEWithHasIF_ICMPLT() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPGE.class); + assertMutantCallableReturns(new HasIF_ICMPGE(-1), mutant, "was >= zero"); + assertMutantCallableReturns(new HasIF_ICMPGE(1), mutant, "was < zero"); + assertMutantCallableReturns(new HasIF_ICMPGE(0), mutant, "was < zero"); + } + + private static class HasIF_ICMPGT implements Callable { + private final int i; + + HasIF_ICMPGT(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i <= j) { + return "was <= zero"; + } else { + return "was > zero"; + } + } + } + + @Test + public void shouldReplaceHasIF_ICMPGTWithHasIF_ICMPLE() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPGT.class); + assertMutantCallableReturns(new HasIF_ICMPGT(-1), mutant, "was > zero"); + assertMutantCallableReturns(new HasIF_ICMPGT(1), mutant, "was <= zero"); + assertMutantCallableReturns(new HasIF_ICMPGT(0), mutant, "was > zero"); + } + + private static class HasIF_ICMPLT implements Callable { + private final int i; + + HasIF_ICMPLT(final int i) { + this.i = i; + } + + @Override + public String call() { + final int j = getZeroButPreventInlining(); + if (this.i >= j) { + return "was >= zero"; + } else { + return "was < zero"; + } + } + } + + @Test + public void shouldReplaceHasIF_ICMPLTWithHasIF_ICMPGE() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ICMPLT.class); + assertMutantCallableReturns(new HasIF_ICMPLT(-1), mutant, "was >= zero"); + assertMutantCallableReturns(new HasIF_ICMPLT(1), mutant, "was < zero"); + assertMutantCallableReturns(new HasIF_ICMPLT(0), mutant, "was < zero"); + } + + private static class HasIF_ACMPNE implements Callable { + private final Object i; + + HasIF_ACMPNE(final Object i) { + this.i = i; + } + + @Override + public String call() { + final Object integer = Integer.class; + if (this.i == integer) { + return "was integer"; + } else { + return "was not integer"; + } + } + } + + @Test + public void shouldReplaceIF_ACMPNEWithIF_CMPEQ() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ACMPNE.class); + printMutant(mutant); + assertMutantCallableReturns(new HasIF_ACMPNE(String.class), mutant, + "was integer"); + assertMutantCallableReturns(new HasIF_ACMPNE(Integer.class), mutant, + "was not integer"); + } + + private static class HasIF_ACMPEQ implements Callable { + private final Object i; + + HasIF_ACMPEQ(final Object i) { + this.i = i; + } + + @Override + public String call() { + final Object integer = Integer.class; + if (this.i != integer) { + return "was not integer"; + } else { + return "was integer"; + } + } + } + + @Test + public void shouldReplaceIF_ACMPEQWithIF_CMPNE() throws Exception { + final Mutant mutant = getFirstMutant(HasIF_ACMPEQ.class); + assertMutantCallableReturns(new HasIF_ACMPEQ(String.class), mutant, + "was integer"); + assertMutantCallableReturns(new HasIF_ACMPEQ(Integer.class), mutant, + "was not integer"); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NonVoidMethodCallMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NonVoidMethodCallMutatorTest.java index 308254fc1..72fbe7c8a 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NonVoidMethodCallMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NonVoidMethodCallMutatorTest.java @@ -1,283 +1,283 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.logging.Logger; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; -import org.pitest.mutationtest.engine.gregor.mutators.ConstructorCallMutatorTest.HasConstructorCall; - -public class NonVoidMethodCallMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToRemoveVoidMethods() { - createTesteeWith(mutateOnlyCallMethod(), - NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); - } - - @Test - public void shouldRemoveNonVoidMethods() throws Exception { - final Mutant mutant = getFirstMutant(HasIntMethodCall.class); - assertMutantCallableReturns(new HasIntMethodCall(), mutant, "0"); - } - - private static class HasVoidMethodCall implements Callable { - - private String s = ""; - - public void set(final int i) { - this.s = this.s + i; - } - - @Override - public String call() throws Exception { - set(1); - return this.s; - } - - } - - @Test - public void shouldNotRemoveVoidMethodCalls() throws Exception { - assertTrue(findMutationsFor(HasVoidMethodCall.class).isEmpty()); - } - - @Test - public void shouldNotRemoveConstructorCalls() throws Exception { - final List actual = findMutationsFor(HasConstructorCall.class); - assertFalse(actual.stream().filter(descriptionContaining("Integer")).findFirst().isPresent()); - } - - private static class HasObjectMethodCall implements Callable { - - @Override - public String call() throws Exception { - return this.toString(); - } - } - - @Test - public void shouldRemoveNonVoidMethodCallReturningObjectType() - throws Exception { - final Mutant mutant = getFirstMutant(HasObjectMethodCall.class); - assertMutantCallableReturns(new HasObjectMethodCall(), mutant, null); - } - - private static class HasBooleanMethodCall implements Callable { - private boolean booleanMethod() { - return true; - } - - @Override - public String call() throws Exception { - final boolean result = booleanMethod(); - return "" + result; - } - } - - @Test - public void shouldRemoveNonVoidMethodCallReturningBooleanType() - throws Exception { - final Mutant mutant = getFirstMutant(HasBooleanMethodCall.class); - assertMutantCallableReturns(new HasBooleanMethodCall(), mutant, "false"); - } - - private static class HasDoubleMethodCall implements Callable { - private double doubleMethod() { - return 9123475.3d; - } - - @Override - public String call() throws Exception { - final double result = doubleMethod(); - return "" + result; - } - } - - @Test - public void shouldRemoveNonVoidMethodCallReturningDoubleType() - throws Exception { - final Mutant mutant = getFirstMutant(HasDoubleMethodCall.class); - assertMutantCallableReturns(new HasDoubleMethodCall(), mutant, "0.0"); - } - - private static class HasByteMethodCall implements Callable { - private byte byteMethod() { - return 5; - } - - @Override - public String call() throws Exception { - final byte result = byteMethod(); - return "" + result; - } - } - - @Test - public void shouldRemoveNonVoidMethodCallReturningByteType() throws Exception { - final Mutant mutant = getFirstMutant(HasByteMethodCall.class); - assertMutantCallableReturns(new HasByteMethodCall(), mutant, "0"); - } - - private static class HasCharMethodCall implements Callable { - private char charMethod() { - return 'g'; - } - - @Override - public String call() throws Exception { - final char result = charMethod(); - return "" + result; - } - } - - @Test - public void shouldRemoveNonVoidMethodCallReturningCharType() throws Exception { - final Mutant mutant = getFirstMutant(HasCharMethodCall.class); - assertMutantCallableReturns(new HasCharMethodCall(), mutant, "" + '\0'); - } - - private static class HasShortMethodCall implements Callable { - private short shortMethod() { - return 23; - } - - @Override - public String call() throws Exception { - final short result = shortMethod(); - return "" + result; - } - } - - @Test - public void shouldRemoveNonVoidMethodCallReturningShortType() - throws Exception { - final Mutant mutant = getFirstMutant(HasShortMethodCall.class); - assertMutantCallableReturns(new HasShortMethodCall(), mutant, "0"); - } - - private static class HasLongMethodCall implements Callable { - private long longMethod() { - return 23; - } - - @Override - public String call() throws Exception { - final long result = longMethod(); - return "" + result; - } - } - - @Test - public void shouldRemoveNonVoidMethodCallReturningLongType() throws Exception { - final Mutant mutant = getFirstMutant(HasLongMethodCall.class); - assertMutantCallableReturns(new HasLongMethodCall(), mutant, "0"); - } - - private static class HasFloatMethodCall implements Callable { - private float floatMethod() { - return 23; - } - - @Override - public String call() throws Exception { - final float result = floatMethod(); - return "" + result; - } - } - - @Test - public void shouldRemoveNonVoidMethodCallReturningFloatType() - throws Exception { - final Mutant mutant = getFirstMutant(HasFloatMethodCall.class); - assertMutantCallableReturns(new HasFloatMethodCall(), mutant, "0.0"); - } - - private static class UsesReturnValueOfMethodCall implements Callable { - @Override - public String call() throws Exception { - return this.toString().toUpperCase(); - } - } - - @Test(expected = NullPointerException.class) - public void canCauseNullPointerExceptionWhenMethodCallRemoved() - throws Exception { - final Collection actual = findMutationsFor(UsesReturnValueOfMethodCall.class); - final Mutant mutant = getFirstMutant(actual); - mutateAndCall(new UsesReturnValueOfMethodCall(), mutant); - } - - private static class HasLogger implements Callable { - @SuppressWarnings("unused") - private static Logger log = Logger.getLogger(HasLogger.class.getName()); - - @Override - public String call() throws Exception { - return "ok"; - } - } - - @Test - @Ignore("functionality moving to filter") - public void shouldNotGenerateRunErrorsWhenMutatingLoggers() throws Exception { - createTesteeWith(i -> true, - NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); - assertTrue(this.findMutationsFor(HasLogger.class).isEmpty()); - - } - - static class HasIntMethodCall implements Callable { - - private static int i = 0; - - public int set(final int newVal) { - i = newVal; - return i + 42; - } - - @Override - @SuppressWarnings("finally") - public String call() throws Exception { - int c = 2; - try { - c = set(1); - } finally { - return "" + c; - } - } - - } - - @Test - public void shouldReplaceAssignmentsFromIntMethodCallsWithZero() - throws Exception { - final Mutant mutant = getFirstMutant(HasIntMethodCall.class); - assertMutantCallableReturns(new HasIntMethodCall(), mutant, "0"); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.logging.Logger; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; +import org.pitest.mutationtest.engine.gregor.mutators.ConstructorCallMutatorTest.HasConstructorCall; + +public class NonVoidMethodCallMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToRemoveVoidMethods() { + createTesteeWith(mutateOnlyCallMethod(), + NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); + } + + @Test + public void shouldRemoveNonVoidMethods() throws Exception { + final Mutant mutant = getFirstMutant(HasIntMethodCall.class); + assertMutantCallableReturns(new HasIntMethodCall(), mutant, "0"); + } + + private static class HasVoidMethodCall implements Callable { + + private String s = ""; + + public void set(final int i) { + this.s = this.s + i; + } + + @Override + public String call() throws Exception { + set(1); + return this.s; + } + + } + + @Test + public void shouldNotRemoveVoidMethodCalls() throws Exception { + assertTrue(findMutationsFor(HasVoidMethodCall.class).isEmpty()); + } + + @Test + public void shouldNotRemoveConstructorCalls() throws Exception { + final List actual = findMutationsFor(HasConstructorCall.class); + assertFalse(actual.stream().filter(descriptionContaining("Integer")).findFirst().isPresent()); + } + + private static class HasObjectMethodCall implements Callable { + + @Override + public String call() throws Exception { + return this.toString(); + } + } + + @Test + public void shouldRemoveNonVoidMethodCallReturningObjectType() + throws Exception { + final Mutant mutant = getFirstMutant(HasObjectMethodCall.class); + assertMutantCallableReturns(new HasObjectMethodCall(), mutant, null); + } + + private static class HasBooleanMethodCall implements Callable { + private boolean booleanMethod() { + return true; + } + + @Override + public String call() throws Exception { + final boolean result = booleanMethod(); + return "" + result; + } + } + + @Test + public void shouldRemoveNonVoidMethodCallReturningBooleanType() + throws Exception { + final Mutant mutant = getFirstMutant(HasBooleanMethodCall.class); + assertMutantCallableReturns(new HasBooleanMethodCall(), mutant, "false"); + } + + private static class HasDoubleMethodCall implements Callable { + private double doubleMethod() { + return 9123475.3d; + } + + @Override + public String call() throws Exception { + final double result = doubleMethod(); + return "" + result; + } + } + + @Test + public void shouldRemoveNonVoidMethodCallReturningDoubleType() + throws Exception { + final Mutant mutant = getFirstMutant(HasDoubleMethodCall.class); + assertMutantCallableReturns(new HasDoubleMethodCall(), mutant, "0.0"); + } + + private static class HasByteMethodCall implements Callable { + private byte byteMethod() { + return 5; + } + + @Override + public String call() throws Exception { + final byte result = byteMethod(); + return "" + result; + } + } + + @Test + public void shouldRemoveNonVoidMethodCallReturningByteType() throws Exception { + final Mutant mutant = getFirstMutant(HasByteMethodCall.class); + assertMutantCallableReturns(new HasByteMethodCall(), mutant, "0"); + } + + private static class HasCharMethodCall implements Callable { + private char charMethod() { + return 'g'; + } + + @Override + public String call() throws Exception { + final char result = charMethod(); + return "" + result; + } + } + + @Test + public void shouldRemoveNonVoidMethodCallReturningCharType() throws Exception { + final Mutant mutant = getFirstMutant(HasCharMethodCall.class); + assertMutantCallableReturns(new HasCharMethodCall(), mutant, "" + '\0'); + } + + private static class HasShortMethodCall implements Callable { + private short shortMethod() { + return 23; + } + + @Override + public String call() throws Exception { + final short result = shortMethod(); + return "" + result; + } + } + + @Test + public void shouldRemoveNonVoidMethodCallReturningShortType() + throws Exception { + final Mutant mutant = getFirstMutant(HasShortMethodCall.class); + assertMutantCallableReturns(new HasShortMethodCall(), mutant, "0"); + } + + private static class HasLongMethodCall implements Callable { + private long longMethod() { + return 23; + } + + @Override + public String call() throws Exception { + final long result = longMethod(); + return "" + result; + } + } + + @Test + public void shouldRemoveNonVoidMethodCallReturningLongType() throws Exception { + final Mutant mutant = getFirstMutant(HasLongMethodCall.class); + assertMutantCallableReturns(new HasLongMethodCall(), mutant, "0"); + } + + private static class HasFloatMethodCall implements Callable { + private float floatMethod() { + return 23; + } + + @Override + public String call() throws Exception { + final float result = floatMethod(); + return "" + result; + } + } + + @Test + public void shouldRemoveNonVoidMethodCallReturningFloatType() + throws Exception { + final Mutant mutant = getFirstMutant(HasFloatMethodCall.class); + assertMutantCallableReturns(new HasFloatMethodCall(), mutant, "0.0"); + } + + private static class UsesReturnValueOfMethodCall implements Callable { + @Override + public String call() throws Exception { + return this.toString().toUpperCase(); + } + } + + @Test(expected = NullPointerException.class) + public void canCauseNullPointerExceptionWhenMethodCallRemoved() + throws Exception { + final Collection actual = findMutationsFor(UsesReturnValueOfMethodCall.class); + final Mutant mutant = getFirstMutant(actual); + mutateAndCall(new UsesReturnValueOfMethodCall(), mutant); + } + + private static class HasLogger implements Callable { + @SuppressWarnings("unused") + private static Logger log = Logger.getLogger(HasLogger.class.getName()); + + @Override + public String call() throws Exception { + return "ok"; + } + } + + @Test + @Ignore("functionality moving to filter") + public void shouldNotGenerateRunErrorsWhenMutatingLoggers() throws Exception { + createTesteeWith(i -> true, + NonVoidMethodCallMutator.NON_VOID_METHOD_CALL_MUTATOR); + assertTrue(this.findMutationsFor(HasLogger.class).isEmpty()); + + } + + static class HasIntMethodCall implements Callable { + + private static int i = 0; + + public int set(final int newVal) { + i = newVal; + return i + 42; + } + + @Override + @SuppressWarnings("finally") + public String call() throws Exception { + int c = 2; + try { + c = set(1); + } finally { + return "" + c; + } + } + + } + + @Test + public void shouldReplaceAssignmentsFromIntMethodCallsWithZero() + throws Exception { + final Mutant mutant = getFirstMutant(HasIntMethodCall.class); + assertMutantCallableReturns(new HasIntMethodCall(), mutant, "0"); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NullReturnValsMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NullReturnValsMutatorTest.java index 5310d9ed0..5ae28c542 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NullReturnValsMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/NullReturnValsMutatorTest.java @@ -1,94 +1,94 @@ -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class NullReturnValsMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyReturnVals() { - createTesteeWith(NullReturnValsMutator.NULL_RETURN_VALUES); - } - - @Test - public void mutatesObjectReturnValuesToNull() throws Exception { - assertMutantCallableReturns(new ObjectReturn(), - createFirstMutant(ObjectReturn.class), null); - } - - @Test - public void doesNotMutateMethodsAnnotatedWithNotNull() throws Exception { - final Collection actual = findMutationsFor( - AnnotatedObjectReturn.class); - assertThat(actual).isEmpty(); - } - - @Test - public void mutatesMethodsWithOtherAnnoations() throws Exception { - final Collection actual = findMutationsFor( - HasOtherAnnotation.class); - assertThat(actual).hasSize(1); - } - - - @Test - public void doesNotMutateMethodsAnnotatedWithNotNullAndOthers() throws Exception { - final Collection actual = findMutationsFor( - MultipleAnnotatedObjectReturn.class); - assertThat(actual).isEmpty(); - } - - - @Test - public void describesMutationsToObject() { - assertMutantDescriptionIncludes("replaced return value with null", ObjectReturn.class); - assertMutantDescriptionIncludes("ObjectReturn::call", ObjectReturn.class); - } - - private static class ObjectReturn implements Callable { - @Override - public Object call() throws Exception { - return ""; - } - } - - private static class AnnotatedObjectReturn implements Callable { - @Override - @NotNull - public Object call() throws Exception { - return ""; - } - } - - private static class HasOtherAnnotation implements Callable { - @Override - @SomethingElse - public Object call() throws Exception { - return ""; - } - } - - private static class MultipleAnnotatedObjectReturn implements Callable { - @Override - @NotNull - @SomethingElse - public Object call() throws Exception { - return ""; - } - } -} - -@interface SomethingElse { - -} - -@interface NotNull { - -} +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class NullReturnValsMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyReturnVals() { + createTesteeWith(NullReturnValsMutator.NULL_RETURN_VALUES); + } + + @Test + public void mutatesObjectReturnValuesToNull() throws Exception { + assertMutantCallableReturns(new ObjectReturn(), + createFirstMutant(ObjectReturn.class), null); + } + + @Test + public void doesNotMutateMethodsAnnotatedWithNotNull() throws Exception { + final Collection actual = findMutationsFor( + AnnotatedObjectReturn.class); + assertThat(actual).isEmpty(); + } + + @Test + public void mutatesMethodsWithOtherAnnoations() throws Exception { + final Collection actual = findMutationsFor( + HasOtherAnnotation.class); + assertThat(actual).hasSize(1); + } + + + @Test + public void doesNotMutateMethodsAnnotatedWithNotNullAndOthers() throws Exception { + final Collection actual = findMutationsFor( + MultipleAnnotatedObjectReturn.class); + assertThat(actual).isEmpty(); + } + + + @Test + public void describesMutationsToObject() { + assertMutantDescriptionIncludes("replaced return value with null", ObjectReturn.class); + assertMutantDescriptionIncludes("ObjectReturn::call", ObjectReturn.class); + } + + private static class ObjectReturn implements Callable { + @Override + public Object call() throws Exception { + return ""; + } + } + + private static class AnnotatedObjectReturn implements Callable { + @Override + @NotNull + public Object call() throws Exception { + return ""; + } + } + + private static class HasOtherAnnotation implements Callable { + @Override + @SomethingElse + public Object call() throws Exception { + return ""; + } + } + + private static class MultipleAnnotatedObjectReturn implements Callable { + @Override + @NotNull + @SomethingElse + public Object call() throws Exception { + return ""; + } + } +} + +@interface SomethingElse { + +} + +@interface NotNull { + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/PrimitiveReturnMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/PrimitiveReturnMutatorTest.java index 17d5c7494..590cf5059 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/PrimitiveReturnMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/PrimitiveReturnMutatorTest.java @@ -1,216 +1,216 @@ -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class PrimitiveReturnMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyReturnVals() { - createTesteeWith(PrimitiveReturnsMutator.PRIMITIVE_RETURN_VALS_MUTATOR); - } - - @Test - public void doesNotMutateBooleans() throws Exception { - assertNoMutants(BooleanReturn.class); - } - - @Test - public void mutatesReturnTo0ForBytes() throws Exception { - assertMutantCallableReturns(new ByteReturn(), - createFirstMutant(ByteReturn.class), "0"); - } - - @Test - public void describesMutationsToBytes() { - assertMutantDescriptionIncludes("replaced byte return with 0", ByteReturn.class); - assertMutantDescriptionIncludes("ByteReturn::mutable", ByteReturn.class); - } - - @Test - public void mutatesReturnToReturn0ForInts() throws Exception { - assertMutantCallableReturns(new IntReturn(), - createFirstMutant(IntReturn.class), "0"); - } - - @Test - public void describesMutationsToInts() { - assertMutantDescriptionIncludes("replaced int return with 0", IntReturn.class); - assertMutantDescriptionIncludes("IntReturn::mutable", IntReturn.class); - } - - @Test - public void mutatesReturnToReturn0ForShorts() throws Exception { - assertMutantCallableReturns(new ShortReturn(), - createFirstMutant(ShortReturn.class), "0"); - } - - @Test - public void describesMutationsToShorts() { - assertMutantDescriptionIncludes("replaced short return with 0", ShortReturn.class); - assertMutantDescriptionIncludes("ShortReturn::mutable", ShortReturn.class); - } - - @Test - public void mutatesReturnToReturn0ForChars() throws Exception { - assertMutantCallableReturns(new CharReturn(), - createFirstMutant(CharReturn.class), "" + (char)0); - } - - @Test - public void describesMutationsToChars() { - assertMutantDescriptionIncludes("replaced char return with 0", CharReturn.class); - assertMutantDescriptionIncludes("CharReturn::mutable", CharReturn.class); - } - - @Test - public void mutatesReturnToReturn0ForLongs() throws Exception { - assertMutantCallableReturns(new LongReturn(), - createFirstMutant(LongReturn.class), "0"); - } - - @Test - public void describesMutationsToLongs() { - assertMutantDescriptionIncludes("replaced long return with 0", LongReturn.class); - assertMutantDescriptionIncludes("LongReturn::mutable", LongReturn.class); - } - - @Test - public void mutatesReturnToReturn0ForFloats() throws Exception { - assertMutantCallableReturns(new FloatReturn(), - createFirstMutant(FloatReturn.class), "0.0"); - } - - @Test - public void describesMutationsToFloats() { - assertMutantDescriptionIncludes("replaced float return with 0.0f", FloatReturn.class); - assertMutantDescriptionIncludes("FloatReturn::mutable", FloatReturn.class); - } - - @Test - public void mutatesReturnToReturn0ForDoubles() throws Exception { - assertMutantCallableReturns(new DoubleReturn(), - createFirstMutant(DoubleReturn.class), "0.0"); - } - - @Test - public void describesMutationsToDoubless() { - assertMutantDescriptionIncludes("replaced double return with 0.0d", DoubleReturn.class); - assertMutantDescriptionIncludes("DoubleReturn::mutable", DoubleReturn.class); - } - - @Test - public void doesNotMutateObjectReturns() { - final Collection actual = findMutationsFor(BoxedIntReturn.class); - assertThat(actual).isEmpty(); - } - - private static class BooleanReturn implements Callable { - public boolean mutable() { - return true; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - private static class ByteReturn implements Callable { - public byte mutable() { - return 101; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - private static class IntReturn implements Callable { - public int mutable() { - return 101; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - - private static class ShortReturn implements Callable { - public short mutable() { - return 1; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - private static class CharReturn implements Callable { - public char mutable() { - return 42; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - private static class LongReturn implements Callable { - public long mutable() { - return 10; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - - private static class FloatReturn implements Callable { - public float mutable() { - return Float.MAX_VALUE; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - private static class DoubleReturn implements Callable { - public double mutable() { - return Double.MAX_VALUE; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - - private static class BoxedIntReturn implements Callable { - public Integer mutable() { - return null; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - } - -} +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class PrimitiveReturnMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyReturnVals() { + createTesteeWith(PrimitiveReturnsMutator.PRIMITIVE_RETURN_VALS_MUTATOR); + } + + @Test + public void doesNotMutateBooleans() throws Exception { + assertNoMutants(BooleanReturn.class); + } + + @Test + public void mutatesReturnTo0ForBytes() throws Exception { + assertMutantCallableReturns(new ByteReturn(), + createFirstMutant(ByteReturn.class), "0"); + } + + @Test + public void describesMutationsToBytes() { + assertMutantDescriptionIncludes("replaced byte return with 0", ByteReturn.class); + assertMutantDescriptionIncludes("ByteReturn::mutable", ByteReturn.class); + } + + @Test + public void mutatesReturnToReturn0ForInts() throws Exception { + assertMutantCallableReturns(new IntReturn(), + createFirstMutant(IntReturn.class), "0"); + } + + @Test + public void describesMutationsToInts() { + assertMutantDescriptionIncludes("replaced int return with 0", IntReturn.class); + assertMutantDescriptionIncludes("IntReturn::mutable", IntReturn.class); + } + + @Test + public void mutatesReturnToReturn0ForShorts() throws Exception { + assertMutantCallableReturns(new ShortReturn(), + createFirstMutant(ShortReturn.class), "0"); + } + + @Test + public void describesMutationsToShorts() { + assertMutantDescriptionIncludes("replaced short return with 0", ShortReturn.class); + assertMutantDescriptionIncludes("ShortReturn::mutable", ShortReturn.class); + } + + @Test + public void mutatesReturnToReturn0ForChars() throws Exception { + assertMutantCallableReturns(new CharReturn(), + createFirstMutant(CharReturn.class), "" + (char)0); + } + + @Test + public void describesMutationsToChars() { + assertMutantDescriptionIncludes("replaced char return with 0", CharReturn.class); + assertMutantDescriptionIncludes("CharReturn::mutable", CharReturn.class); + } + + @Test + public void mutatesReturnToReturn0ForLongs() throws Exception { + assertMutantCallableReturns(new LongReturn(), + createFirstMutant(LongReturn.class), "0"); + } + + @Test + public void describesMutationsToLongs() { + assertMutantDescriptionIncludes("replaced long return with 0", LongReturn.class); + assertMutantDescriptionIncludes("LongReturn::mutable", LongReturn.class); + } + + @Test + public void mutatesReturnToReturn0ForFloats() throws Exception { + assertMutantCallableReturns(new FloatReturn(), + createFirstMutant(FloatReturn.class), "0.0"); + } + + @Test + public void describesMutationsToFloats() { + assertMutantDescriptionIncludes("replaced float return with 0.0f", FloatReturn.class); + assertMutantDescriptionIncludes("FloatReturn::mutable", FloatReturn.class); + } + + @Test + public void mutatesReturnToReturn0ForDoubles() throws Exception { + assertMutantCallableReturns(new DoubleReturn(), + createFirstMutant(DoubleReturn.class), "0.0"); + } + + @Test + public void describesMutationsToDoubless() { + assertMutantDescriptionIncludes("replaced double return with 0.0d", DoubleReturn.class); + assertMutantDescriptionIncludes("DoubleReturn::mutable", DoubleReturn.class); + } + + @Test + public void doesNotMutateObjectReturns() { + final Collection actual = findMutationsFor(BoxedIntReturn.class); + assertThat(actual).isEmpty(); + } + + private static class BooleanReturn implements Callable { + public boolean mutable() { + return true; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + private static class ByteReturn implements Callable { + public byte mutable() { + return 101; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + private static class IntReturn implements Callable { + public int mutable() { + return 101; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + + private static class ShortReturn implements Callable { + public short mutable() { + return 1; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + private static class CharReturn implements Callable { + public char mutable() { + return 42; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + private static class LongReturn implements Callable { + public long mutable() { + return 10; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + + private static class FloatReturn implements Callable { + public float mutable() { + return Float.MAX_VALUE; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + private static class DoubleReturn implements Callable { + public double mutable() { + return Double.MAX_VALUE; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + + private static class BoxedIntReturn implements Callable { + public Integer mutable() { + return null; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ReturnValsMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ReturnValsMutatorTest.java index 1bea64a28..207285945 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ReturnValsMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/ReturnValsMutatorTest.java @@ -1,230 +1,230 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.mutators; - -import java.util.Collection; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class ReturnValsMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyReturnVals() { - createTesteeWith(ReturnValsMutator.RETURN_VALS_MUTATOR); - } - - private static class IReturn implements Callable { - private final int value; - - public IReturn(final int value) { - this.value = value; - } - - public int mutable() { - return this.value; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - - } - - @Test - public void shouldMutateIReturnsOf0To1() throws Exception { - final Collection actual = findMutationsFor(IReturn.class); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new IReturn(0), mutant, "1"); - } - - @Test - public void shouldMutateIReturnsOf1To0() throws Exception { - final Collection actual = findMutationsFor(IReturn.class); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new IReturn(1), mutant, "0"); - } - - @Test - public void shouldMutateIReturnsOfAnyNonZeroValueTo0() throws Exception { - final Collection actual = findMutationsFor(IReturn.class); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new IReturn(1234), mutant, "0"); - } - - private static class LReturn implements Callable { - - private final long value; - - public LReturn(final long value) { - this.value = value; - } - - public long mutable() { - return this.value; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - - } - - @Test - public void shouldAddOneToValueOfLReturn() throws Exception { - assertMutantCallableReturns(new LReturn(0), - createFirstMutant(LReturn.class), "1"); - } - - private static class BooleanReturn implements Callable { - - private final boolean value; - - public BooleanReturn(final boolean value) { - this.value = value; - } - - public boolean mutable() { - return this.value; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - - } - - @Test - public void shouldMutateReturnsTrueToReturnsFalse() throws Exception { - assertMutantCallableReturns(new BooleanReturn(true), - createFirstMutant(BooleanReturn.class), "false"); - } - - @Test - public void shouldMutateReturnsFalseToReturnsTrue() throws Exception { - assertMutantCallableReturns(new BooleanReturn(false), - createFirstMutant(BooleanReturn.class), "true"); - } - - private static class FReturn implements Callable { - - private final float value; - - public FReturn(final float value) { - this.value = value; - } - - public float mutable() { - return this.value; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - - } - - @Test - public void shouldMutateFReturnsOfAnyNonZeroValueToInverseOfOnePlusTheValue() - throws Exception { - final Collection actual = findMutationsFor(FReturn.class); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new FReturn(1234f), mutant, "-1235.0"); - } - - @Test - public void shouldMutateReturnsOfFloatNotANumberToMinusOne() throws Exception { - final Collection actual = findMutationsFor(FReturn.class); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new FReturn(Float.NaN), mutant, "-1.0"); - } - - private static class DReturn implements Callable { - - private final double value; - - public DReturn(final double value) { - this.value = value; - } - - public double mutable() { - return this.value; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - - } - - @Test - public void shouldMutateDReturnsOfAnyNonZeroValueToInverseOfOnePlusTheValue() - throws Exception { - final Collection actual = findMutationsFor(DReturn.class); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new DReturn(1234d), mutant, "-1235.0"); - } - - @Test - public void shouldMutateReturnsOfDoubleNotANumberToMinusOne() - throws Exception { - final Collection actual = findMutationsFor(DReturn.class); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new DReturn(Double.NaN), mutant, "-1.0"); - } - - private static class AReturn implements Callable { - - private final Object value; - - public AReturn(final Object value) { - this.value = value; - } - - public Object mutable() { - return this.value; - } - - @Override - public String call() throws Exception { - return "" + mutable(); - } - - } - - @Test - public void shouldMutateReturnsOfNonNullObjectsToNull() throws Exception { - final Collection actual = findMutationsFor(AReturn.class); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new AReturn("foo"), mutant, "null"); - } - - @Test(expected = RuntimeException.class) - public void shouldMutateReturnsOfNullObjectsToRuntimeExceptions() - throws Exception { - final Mutant mutant = getFirstMutant(AReturn.class); - mutateAndCall(new AReturn(null), mutant); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.mutators; + +import java.util.Collection; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class ReturnValsMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyReturnVals() { + createTesteeWith(ReturnValsMutator.RETURN_VALS_MUTATOR); + } + + private static class IReturn implements Callable { + private final int value; + + public IReturn(final int value) { + this.value = value; + } + + public int mutable() { + return this.value; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + + } + + @Test + public void shouldMutateIReturnsOf0To1() throws Exception { + final Collection actual = findMutationsFor(IReturn.class); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new IReturn(0), mutant, "1"); + } + + @Test + public void shouldMutateIReturnsOf1To0() throws Exception { + final Collection actual = findMutationsFor(IReturn.class); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new IReturn(1), mutant, "0"); + } + + @Test + public void shouldMutateIReturnsOfAnyNonZeroValueTo0() throws Exception { + final Collection actual = findMutationsFor(IReturn.class); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new IReturn(1234), mutant, "0"); + } + + private static class LReturn implements Callable { + + private final long value; + + public LReturn(final long value) { + this.value = value; + } + + public long mutable() { + return this.value; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + + } + + @Test + public void shouldAddOneToValueOfLReturn() throws Exception { + assertMutantCallableReturns(new LReturn(0), + createFirstMutant(LReturn.class), "1"); + } + + private static class BooleanReturn implements Callable { + + private final boolean value; + + public BooleanReturn(final boolean value) { + this.value = value; + } + + public boolean mutable() { + return this.value; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + + } + + @Test + public void shouldMutateReturnsTrueToReturnsFalse() throws Exception { + assertMutantCallableReturns(new BooleanReturn(true), + createFirstMutant(BooleanReturn.class), "false"); + } + + @Test + public void shouldMutateReturnsFalseToReturnsTrue() throws Exception { + assertMutantCallableReturns(new BooleanReturn(false), + createFirstMutant(BooleanReturn.class), "true"); + } + + private static class FReturn implements Callable { + + private final float value; + + public FReturn(final float value) { + this.value = value; + } + + public float mutable() { + return this.value; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + + } + + @Test + public void shouldMutateFReturnsOfAnyNonZeroValueToInverseOfOnePlusTheValue() + throws Exception { + final Collection actual = findMutationsFor(FReturn.class); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new FReturn(1234f), mutant, "-1235.0"); + } + + @Test + public void shouldMutateReturnsOfFloatNotANumberToMinusOne() throws Exception { + final Collection actual = findMutationsFor(FReturn.class); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new FReturn(Float.NaN), mutant, "-1.0"); + } + + private static class DReturn implements Callable { + + private final double value; + + public DReturn(final double value) { + this.value = value; + } + + public double mutable() { + return this.value; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + + } + + @Test + public void shouldMutateDReturnsOfAnyNonZeroValueToInverseOfOnePlusTheValue() + throws Exception { + final Collection actual = findMutationsFor(DReturn.class); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new DReturn(1234d), mutant, "-1235.0"); + } + + @Test + public void shouldMutateReturnsOfDoubleNotANumberToMinusOne() + throws Exception { + final Collection actual = findMutationsFor(DReturn.class); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new DReturn(Double.NaN), mutant, "-1.0"); + } + + private static class AReturn implements Callable { + + private final Object value; + + public AReturn(final Object value) { + this.value = value; + } + + public Object mutable() { + return this.value; + } + + @Override + public String call() throws Exception { + return "" + mutable(); + } + + } + + @Test + public void shouldMutateReturnsOfNonNullObjectsToNull() throws Exception { + final Collection actual = findMutationsFor(AReturn.class); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new AReturn("foo"), mutant, "null"); + } + + @Test(expected = RuntimeException.class) + public void shouldMutateReturnsOfNullObjectsToRuntimeExceptions() + throws Exception { + final Mutant mutant = getFirstMutant(AReturn.class); + mutateAndCall(new AReturn(null), mutant); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/VoidMethodCallMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/VoidMethodCallMutatorTest.java index 50ccf1d5a..b29681965 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/VoidMethodCallMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/VoidMethodCallMutatorTest.java @@ -1,129 +1,129 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.engine.gregor.mutators; - -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; -import org.pitest.mutationtest.engine.gregor.mutators.ConstructorCallMutatorTest.HasConstructorCall; -import org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutatorTest.HasIntMethodCall; - -public class VoidMethodCallMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToRemoveVoidMethods() { - createTesteeWith(mutateOnlyCallMethod(), - VoidMethodCallMutator.VOID_METHOD_CALL_MUTATOR); - } - - static class HasVoidMethodCall implements Callable { - - private int i = 0; - - public void set(final int i) { - this.i = i; - } - - @Override - public String call() throws Exception { - set(1); - return "" + this.i; - } - - } - - @Test - public void shouldRemoveVoidMethodCalls() throws Exception { - final Mutant mutant = getFirstMutant(HasVoidMethodCall.class); - assertMutantCallableReturns(new HasVoidMethodCall(), mutant, "0"); - } - - @Test - public void shouldNotRemoveConstructorCalls() throws Exception { - assertTrue(findMutationsFor(HasConstructorCall.class).isEmpty()); - } - - @Test - public void shouldNotRemoveNonVoidMethods() throws Exception { - assertTrue(findMutationsFor(HasIntMethodCall.class).isEmpty()); - } - - private static class HasVoidMethodCallWithFinallyBlock implements - Callable { - - private int i = 0; - - public void set(final int i, final long k, final double l, - final HasVoidMethodCallWithFinallyBlock m, final String n) { - this.i = i; - } - - @Override - @SuppressWarnings("finally") - public String call() throws Exception { - final double a = 1; - final String b = "foo"; - try { - set(1, 2l, a, this, b); - } finally { - return "" + this.i; - } - } - - } - - @Test - public void shouldMaintainStack() throws Exception { - final Mutant mutant = getFirstMutant(HasVoidMethodCallWithFinallyBlock.class); - assertMutantCallableReturns(new HasVoidMethodCallWithFinallyBlock(), - mutant, "0"); - } - - private static class HasVoidStaticMethodCall implements Callable { - - private static int i = 0; - - public static void set(final int newVal, final long k, final double l, - final HasVoidStaticMethodCall m, final String n) { - i = newVal; - } - - @Override - @SuppressWarnings("finally") - public String call() throws Exception { - final double a = 1; - final String b = "foo"; - try { - set(1, 2l, a, this, b); - } finally { - return "" + i; - } - } - - } - - @Test - public void shouldMaintainStackWhenCallIsStatic() throws Exception { - final Mutant mutant = getFirstMutant(HasVoidStaticMethodCall.class); - assertMutantCallableReturns(new HasVoidStaticMethodCall(), mutant, "0"); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.engine.gregor.mutators; + +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; +import org.pitest.mutationtest.engine.gregor.mutators.ConstructorCallMutatorTest.HasConstructorCall; +import org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutatorTest.HasIntMethodCall; + +public class VoidMethodCallMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToRemoveVoidMethods() { + createTesteeWith(mutateOnlyCallMethod(), + VoidMethodCallMutator.VOID_METHOD_CALL_MUTATOR); + } + + static class HasVoidMethodCall implements Callable { + + private int i = 0; + + public void set(final int i) { + this.i = i; + } + + @Override + public String call() throws Exception { + set(1); + return "" + this.i; + } + + } + + @Test + public void shouldRemoveVoidMethodCalls() throws Exception { + final Mutant mutant = getFirstMutant(HasVoidMethodCall.class); + assertMutantCallableReturns(new HasVoidMethodCall(), mutant, "0"); + } + + @Test + public void shouldNotRemoveConstructorCalls() throws Exception { + assertTrue(findMutationsFor(HasConstructorCall.class).isEmpty()); + } + + @Test + public void shouldNotRemoveNonVoidMethods() throws Exception { + assertTrue(findMutationsFor(HasIntMethodCall.class).isEmpty()); + } + + private static class HasVoidMethodCallWithFinallyBlock implements + Callable { + + private int i = 0; + + public void set(final int i, final long k, final double l, + final HasVoidMethodCallWithFinallyBlock m, final String n) { + this.i = i; + } + + @Override + @SuppressWarnings("finally") + public String call() throws Exception { + final double a = 1; + final String b = "foo"; + try { + set(1, 2l, a, this, b); + } finally { + return "" + this.i; + } + } + + } + + @Test + public void shouldMaintainStack() throws Exception { + final Mutant mutant = getFirstMutant(HasVoidMethodCallWithFinallyBlock.class); + assertMutantCallableReturns(new HasVoidMethodCallWithFinallyBlock(), + mutant, "0"); + } + + private static class HasVoidStaticMethodCall implements Callable { + + private static int i = 0; + + public static void set(final int newVal, final long k, final double l, + final HasVoidStaticMethodCall m, final String n) { + i = newVal; + } + + @Override + @SuppressWarnings("finally") + public String call() throws Exception { + final double a = 1; + final String b = "foo"; + try { + set(1, 2l, a, this, b); + } finally { + return "" + i; + } + } + + } + + @Test + public void shouldMaintainStackWhenCallIsStatic() throws Exception { + final Mutant mutant = getFirstMutant(HasVoidStaticMethodCall.class); + assertMutantCallableReturns(new HasVoidStaticMethodCall(), mutant, "0"); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/experimental/NakedReceiverMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/experimental/NakedReceiverMutatorTest.java index d04192c08..cf0746eee 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/experimental/NakedReceiverMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/experimental/NakedReceiverMutatorTest.java @@ -1,169 +1,169 @@ -/* - * Copyright 2015 Urs Metz - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.mutationtest.engine.gregor.mutators.experimental; - -import static java.util.Collections.singletonList; -import static org.pitest.mutationtest.engine.gregor.mutators.experimental.NakedReceiverMutator.NAKED_RECEIVER; - -import java.util.ArrayList; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class NakedReceiverMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToUseReplaceMethodWithArgumentOfSameTypeAsReturnValueMutator() { - createTesteeWith(mutateOnlyCallMethod(), NAKED_RECEIVER); - } - - @Test - public void shouldReplaceMethodCallOnString() throws Exception { - final Mutant mutant = getFirstMutant(HasStringMethodCall.class); - assertMutantCallableReturns(new HasStringMethodCall("EXAMPLE"), mutant, - "EXAMPLE"); - } - - @Test - public void shouldNotReplaceMethodCallWhenDifferentReturnType() - throws Exception { - assertNoMutants(HasMethodWithDifferentReturnType.class); - } - - @Test - public void shouldNotMutateVoidMethodCall() throws Exception { - assertNoMutants(HasVoidMethodCall.class); - } - - @Test - public void shouldNotMutateStaticMethodCall() { - assertNoMutants(HasStaticMethodCallWithSameType.class); - } - - @Test - public void willReplaceCallToMethodWithDifferentGenericTypeDueToTypeErasure() - throws Exception { - final Mutant mutant = getFirstMutant(CallsMethodsWithGenericTypes.class); - final Foo receiver = new Foo<>("3"); - assertMutantCallableReturns(new CallsMethodsWithGenericTypes(receiver), - mutant, receiver); - } - - @Test - public void shouldRemoveDslMethods() throws Exception { - final Mutant mutant = getFirstMutant(HasDslMethodCall.class); - assertMutantCallableReturns(new HasDslMethodCall(), mutant, "HasDslMethodCall [i=3]"); - } - - private static class HasStringMethodCall implements Callable { - private final String arg; - - public HasStringMethodCall(String arg) { - this.arg = arg; - } - - @Override - public String call() throws Exception { - return this.arg.toLowerCase(); - } - } - - static class HasMethodWithDifferentReturnType { - public int call() throws Exception { - return "".length(); - } - } - - static class HasVoidMethodCall { - public void call() throws Exception { - } - } - - private static class CallsMethodsWithGenericTypes - implements Callable> { - private final Foo myArg; - - public CallsMethodsWithGenericTypes(Foo myArg) { - this.myArg = myArg; - } - - @Override - public Foo call() { - return this.myArg.returnsFooInteger(); - } - } - - static class HasStaticMethodCallWithSameType { - public void call() { - HasStaticMethodCallWithSameType.instance(); - } - - private static HasStaticMethodCallWithSameType instance() { - return new HasStaticMethodCallWithSameType(); - } - } - - static class Foo extends ArrayList { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public Foo(T arg) { - super(singletonList(arg)); - } - - public Foo returnsFooInteger() { - return new Foo<>(2); - } - } - - static class HasDslMethodCall implements Callable { - - private int i = 0; - - public HasDslMethodCall chain(final int newVal) { - this.i += newVal; - return this; - } - - public void voidNonDsl(final int newVal) { - this.i += newVal; - } - - public int nonDsl(final int newVal) { - this.i += newVal; - return this.i; - } - - @Override - public String call() throws Exception { - final HasDslMethodCall dsl = this; - dsl.chain(1).nonDsl(3); - return "" + dsl; - } - - @Override - public String toString() { - return "HasDslMethodCall [i=" + this.i + "]"; - } - - } -} +/* + * Copyright 2015 Urs Metz + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.mutationtest.engine.gregor.mutators.experimental; + +import static java.util.Collections.singletonList; +import static org.pitest.mutationtest.engine.gregor.mutators.experimental.NakedReceiverMutator.NAKED_RECEIVER; + +import java.util.ArrayList; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class NakedReceiverMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToUseReplaceMethodWithArgumentOfSameTypeAsReturnValueMutator() { + createTesteeWith(mutateOnlyCallMethod(), NAKED_RECEIVER); + } + + @Test + public void shouldReplaceMethodCallOnString() throws Exception { + final Mutant mutant = getFirstMutant(HasStringMethodCall.class); + assertMutantCallableReturns(new HasStringMethodCall("EXAMPLE"), mutant, + "EXAMPLE"); + } + + @Test + public void shouldNotReplaceMethodCallWhenDifferentReturnType() + throws Exception { + assertNoMutants(HasMethodWithDifferentReturnType.class); + } + + @Test + public void shouldNotMutateVoidMethodCall() throws Exception { + assertNoMutants(HasVoidMethodCall.class); + } + + @Test + public void shouldNotMutateStaticMethodCall() { + assertNoMutants(HasStaticMethodCallWithSameType.class); + } + + @Test + public void willReplaceCallToMethodWithDifferentGenericTypeDueToTypeErasure() + throws Exception { + final Mutant mutant = getFirstMutant(CallsMethodsWithGenericTypes.class); + final Foo receiver = new Foo<>("3"); + assertMutantCallableReturns(new CallsMethodsWithGenericTypes(receiver), + mutant, receiver); + } + + @Test + public void shouldRemoveDslMethods() throws Exception { + final Mutant mutant = getFirstMutant(HasDslMethodCall.class); + assertMutantCallableReturns(new HasDslMethodCall(), mutant, "HasDslMethodCall [i=3]"); + } + + private static class HasStringMethodCall implements Callable { + private final String arg; + + public HasStringMethodCall(String arg) { + this.arg = arg; + } + + @Override + public String call() throws Exception { + return this.arg.toLowerCase(); + } + } + + static class HasMethodWithDifferentReturnType { + public int call() throws Exception { + return "".length(); + } + } + + static class HasVoidMethodCall { + public void call() throws Exception { + } + } + + private static class CallsMethodsWithGenericTypes + implements Callable> { + private final Foo myArg; + + public CallsMethodsWithGenericTypes(Foo myArg) { + this.myArg = myArg; + } + + @Override + public Foo call() { + return this.myArg.returnsFooInteger(); + } + } + + static class HasStaticMethodCallWithSameType { + public void call() { + HasStaticMethodCallWithSameType.instance(); + } + + private static HasStaticMethodCallWithSameType instance() { + return new HasStaticMethodCallWithSameType(); + } + } + + static class Foo extends ArrayList { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public Foo(T arg) { + super(singletonList(arg)); + } + + public Foo returnsFooInteger() { + return new Foo<>(2); + } + } + + static class HasDslMethodCall implements Callable { + + private int i = 0; + + public HasDslMethodCall chain(final int newVal) { + this.i += newVal; + return this; + } + + public void voidNonDsl(final int newVal) { + this.i += newVal; + } + + public int nonDsl(final int newVal) { + this.i += newVal; + return this.i; + } + + @Override + public String call() throws Exception { + final HasDslMethodCall dsl = this; + dsl.chain(1).nonDsl(3); + return "" + dsl; + } + + @Override + public String toString() { + return "HasDslMethodCall [i=" + this.i + "]"; + } + + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/experimental/RemoveIncrementsMutatorTest.java b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/experimental/RemoveIncrementsMutatorTest.java index 212f7ca6e..5023df197 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/experimental/RemoveIncrementsMutatorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/engine/gregor/mutators/experimental/RemoveIncrementsMutatorTest.java @@ -1,77 +1,77 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.engine.gregor.mutators.experimental; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; - -import java.util.Collection; -import java.util.concurrent.Callable; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.gregor.MutatorTestBase; - -public class RemoveIncrementsMutatorTest extends MutatorTestBase { - - @Before - public void setupEngineToMutateOnlyIncrements() { - createTesteeWith(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR); - } - - private static class HasIncrement implements Callable { - public int containsIincInstructions(int i) { - return ++i; - } - - @Override - public String call() throws Exception { - return "" + containsIincInstructions(1); - } - - } - - @Test - public void shouldProvideAMeaningfulName() { - assertEquals("REMOVE_INCREMENTS_MUTATOR", - RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR.getName()); - } - - @Test - public void shouldRemoveArgumentsToIInc() throws Exception { - final Collection actual = findMutationsFor(HasIncrement.class); - assertEquals(1, actual.size()); - final Mutant mutant = getFirstMutant(actual); - assertMutantCallableReturns(new HasIncrement(), mutant, "1"); - } - - private static class HasNoIncrements implements Callable { - - @Override - public String call() throws Exception { - return "foo"; - } - - } - - @Test - public void shouldCreateNoMutationsWhenNoIncrementsPresent() { - final Collection actual = findMutationsFor(HasNoIncrements.class); - assertThat(actual).isEmpty(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.engine.gregor.mutators.experimental; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +import java.util.Collection; +import java.util.concurrent.Callable; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.gregor.MutatorTestBase; + +public class RemoveIncrementsMutatorTest extends MutatorTestBase { + + @Before + public void setupEngineToMutateOnlyIncrements() { + createTesteeWith(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR); + } + + private static class HasIncrement implements Callable { + public int containsIincInstructions(int i) { + return ++i; + } + + @Override + public String call() throws Exception { + return "" + containsIincInstructions(1); + } + + } + + @Test + public void shouldProvideAMeaningfulName() { + assertEquals("REMOVE_INCREMENTS_MUTATOR", + RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR.getName()); + } + + @Test + public void shouldRemoveArgumentsToIInc() throws Exception { + final Collection actual = findMutationsFor(HasIncrement.class); + assertEquals(1, actual.size()); + final Mutant mutant = getFirstMutant(actual); + assertMutantCallableReturns(new HasIncrement(), mutant, "1"); + } + + private static class HasNoIncrements implements Callable { + + @Override + public String call() throws Exception { + return "foo"; + } + + } + + @Test + public void shouldCreateNoMutationsWhenNoIncrementsPresent() { + final Collection actual = findMutationsFor(HasNoIncrements.class); + assertThat(actual).isEmpty(); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/execute/CheckTestHasFailedResultListenerTest.java b/pitest/src/test/java/org/pitest/mutationtest/execute/CheckTestHasFailedResultListenerTest.java index 6f370fffd..b1e055934 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/execute/CheckTestHasFailedResultListenerTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/execute/CheckTestHasFailedResultListenerTest.java @@ -1,63 +1,63 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.execute; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.DescriptionMother; -import java.util.Optional; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.testapi.Description; -import org.pitest.testapi.TestResult; - -public class CheckTestHasFailedResultListenerTest { - - private CheckTestHasFailedResultListener testee; - - private Description description; - - @Before - public void setUp() { - this.testee = new CheckTestHasFailedResultListener(); - this.description = DescriptionMother.createEmptyDescription("foo"); - } - - @Test - public void shouldReturnDetectionStatusOfSurvivedWhenNoFailuresOrErrors() { - this.testee.onTestSuccess(new TestResult(this.description, null)); - assertEquals(DetectionStatus.SURVIVED, this.testee.status()); - } - - @Test - public void shouldReturnDetectionStatusOfKilledWhenEncountersFailure() { - this.testee.onTestFailure(new TestResult(this.description, null)); - assertEquals(DetectionStatus.KILLED, this.testee.status()); - } - - @Test - public void shouldRecordDescriptionOfLastFailingTest() { - this.testee.onTestFailure(new TestResult(this.description, null)); - assertEquals(Optional.ofNullable(this.description), this.testee.lastFailingTest()); - } - - @Test - public void shouldRecordNumberOfTestsRun() { - assertEquals(0, this.testee.getNumberOfTestsRun()); - this.testee.onTestStart(null); - assertEquals(1, this.testee.getNumberOfTestsRun()); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.execute; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.DescriptionMother; +import java.util.Optional; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.testapi.Description; +import org.pitest.testapi.TestResult; + +public class CheckTestHasFailedResultListenerTest { + + private CheckTestHasFailedResultListener testee; + + private Description description; + + @Before + public void setUp() { + this.testee = new CheckTestHasFailedResultListener(); + this.description = DescriptionMother.createEmptyDescription("foo"); + } + + @Test + public void shouldReturnDetectionStatusOfSurvivedWhenNoFailuresOrErrors() { + this.testee.onTestSuccess(new TestResult(this.description, null)); + assertEquals(DetectionStatus.SURVIVED, this.testee.status()); + } + + @Test + public void shouldReturnDetectionStatusOfKilledWhenEncountersFailure() { + this.testee.onTestFailure(new TestResult(this.description, null)); + assertEquals(DetectionStatus.KILLED, this.testee.status()); + } + + @Test + public void shouldRecordDescriptionOfLastFailingTest() { + this.testee.onTestFailure(new TestResult(this.description, null)); + assertEquals(Optional.ofNullable(this.description), this.testee.lastFailingTest()); + } + + @Test + public void shouldRecordNumberOfTestsRun() { + assertEquals(0, this.testee.getNumberOfTestsRun()); + this.testee.onTestStart(null); + assertEquals(1, this.testee.getNumberOfTestsRun()); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/execute/DefaultReporterTest.java b/pitest/src/test/java/org/pitest/mutationtest/execute/DefaultReporterTest.java index 0120619f9..54424dff3 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/execute/DefaultReporterTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/execute/DefaultReporterTest.java @@ -1,68 +1,68 @@ -package org.pitest.mutationtest.execute; - -import static org.junit.Assert.assertEquals; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.util.ExitCode; -import org.pitest.util.Id; -import org.pitest.util.SafeDataInputStream; - -public class DefaultReporterTest { - - private DefaultReporter testee; - - private ByteArrayOutputStream os; - - @Before - public void setUp() { - this.os = new ByteArrayOutputStream(); - this.testee = new DefaultReporter(this.os); - } - - @Test - public void shouldSendMutationIdentifierToOutputStream() throws IOException { - final MutationIdentifier mi = aMutationId().withIndex(0).withMutator("foo") - .build(); - this.testee.describe(mi); - final SafeDataInputStream is = resultToStream(); - assertEquals(Id.DESCRIBE, is.readByte()); - assertEquals(is.read(MutationIdentifier.class), mi); - } - - @Test - public void shouldSendDetectionStatus() throws IOException { - final MutationIdentifier mi = aMutationId().withIndex(0).withMutator("foo") - .build(); - final MutationStatusTestPair ms = new MutationStatusTestPair(2, - DetectionStatus.KILLED, "foo"); - this.testee.report(mi, ms); - final SafeDataInputStream is = resultToStream(); - assertEquals(Id.REPORT, is.readByte()); - assertEquals(is.read(MutationIdentifier.class), mi); - assertEquals(is.read(MutationStatusTestPair.class), ms); - } - - private SafeDataInputStream resultToStream() { - final SafeDataInputStream is = new SafeDataInputStream( - new ByteArrayInputStream(this.os.toByteArray())); - return is; - } - - @Test - public void shouldSendExitCode() { - this.testee.done(ExitCode.TIMEOUT); - final SafeDataInputStream is = resultToStream(); - assertEquals(Id.DONE, is.readByte()); - assertEquals(is.readInt(), ExitCode.TIMEOUT.getCode()); - } - -} +package org.pitest.mutationtest.execute; + +import static org.junit.Assert.assertEquals; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.util.ExitCode; +import org.pitest.util.Id; +import org.pitest.util.SafeDataInputStream; + +public class DefaultReporterTest { + + private DefaultReporter testee; + + private ByteArrayOutputStream os; + + @Before + public void setUp() { + this.os = new ByteArrayOutputStream(); + this.testee = new DefaultReporter(this.os); + } + + @Test + public void shouldSendMutationIdentifierToOutputStream() throws IOException { + final MutationIdentifier mi = aMutationId().withIndex(0).withMutator("foo") + .build(); + this.testee.describe(mi); + final SafeDataInputStream is = resultToStream(); + assertEquals(Id.DESCRIBE, is.readByte()); + assertEquals(is.read(MutationIdentifier.class), mi); + } + + @Test + public void shouldSendDetectionStatus() throws IOException { + final MutationIdentifier mi = aMutationId().withIndex(0).withMutator("foo") + .build(); + final MutationStatusTestPair ms = new MutationStatusTestPair(2, + DetectionStatus.KILLED, "foo"); + this.testee.report(mi, ms); + final SafeDataInputStream is = resultToStream(); + assertEquals(Id.REPORT, is.readByte()); + assertEquals(is.read(MutationIdentifier.class), mi); + assertEquals(is.read(MutationStatusTestPair.class), ms); + } + + private SafeDataInputStream resultToStream() { + final SafeDataInputStream is = new SafeDataInputStream( + new ByteArrayInputStream(this.os.toByteArray())); + return is; + } + + @Test + public void shouldSendExitCode() { + this.testee.done(ExitCode.TIMEOUT); + final SafeDataInputStream is = resultToStream(); + assertEquals(Id.DONE, is.readByte()); + assertEquals(is.readInt(), ExitCode.TIMEOUT.getCode()); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestMinionTest.java b/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestMinionTest.java index ab84d4026..ce67db130 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestMinionTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestMinionTest.java @@ -1,100 +1,100 @@ -package org.pitest.mutationtest.execute; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.util.ArrayList; -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.EngineArguments; -import org.pitest.mutationtest.MutationEngineFactory; -import org.pitest.mutationtest.TimeoutLengthStrategy; -import org.pitest.mutationtest.config.MinionSettings; -import org.pitest.mutationtest.config.TestPluginArguments; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationEngine; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.testapi.Configuration; -import org.pitest.util.ExitCode; -import org.pitest.util.PitError; -import org.pitest.util.SafeDataInputStream; - -public class MutationTestMinionTest { - - private MutationTestMinion testee; - - @Mock - private Reporter reporter; - - @Mock - private SafeDataInputStream is; - - @Mock - private MutationEngine engine; - - @Mock - private TimeoutLengthStrategy timeoutStrategy; - - @Mock - private Configuration testConfig; - - @Mock - private Mutater mutater; - - @Mock - private MinionSettings settings; - - private MinionArguments args; - - private Collection mutations; - - private Collection tests; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - this.mutations = new ArrayList<>(); - this.tests = new ArrayList<>(); - - this.args = new MinionArguments(this.mutations, this.tests, "anEgine", EngineArguments.arguments(), - this.timeoutStrategy, false, TestPluginArguments.defaults()); - - when(this.is.read(MinionArguments.class)).thenReturn(this.args); - when(this.engine.createMutator(any(ClassByteArraySource.class))) - .thenReturn(this.mutater); - - final MutationEngineFactory factory = Mockito.mock(MutationEngineFactory.class); - when(factory.createEngine(any(EngineArguments.class))).thenReturn(this.engine); - - when(this.settings.createEngine(any(String.class))).thenReturn(factory); - - this.testee = new MutationTestMinion(this.settings, this.is, this.reporter); - } - - @Test - public void shouldReportNoErrorWhenNoMutationsSupplied() { - this.testee.run(); - verify(this.reporter).done(ExitCode.OK); - } - - @Test - public void shouldReportErrorWhenOneOccursDuringAnalysis() { - this.mutations.add(new MutationDetails(aMutationId().withIndex(0) - .withMutator("foo").build(), "file", "desc", 0, 0)); - when(this.mutater.getMutation(any(MutationIdentifier.class))).thenThrow( - new PitError("foo")); - this.testee.run(); - verify(this.reporter).done(ExitCode.UNKNOWN_ERROR); - } - -} +package org.pitest.mutationtest.execute; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.util.ArrayList; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.EngineArguments; +import org.pitest.mutationtest.MutationEngineFactory; +import org.pitest.mutationtest.TimeoutLengthStrategy; +import org.pitest.mutationtest.config.MinionSettings; +import org.pitest.mutationtest.config.TestPluginArguments; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationEngine; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.testapi.Configuration; +import org.pitest.util.ExitCode; +import org.pitest.util.PitError; +import org.pitest.util.SafeDataInputStream; + +public class MutationTestMinionTest { + + private MutationTestMinion testee; + + @Mock + private Reporter reporter; + + @Mock + private SafeDataInputStream is; + + @Mock + private MutationEngine engine; + + @Mock + private TimeoutLengthStrategy timeoutStrategy; + + @Mock + private Configuration testConfig; + + @Mock + private Mutater mutater; + + @Mock + private MinionSettings settings; + + private MinionArguments args; + + private Collection mutations; + + private Collection tests; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + this.mutations = new ArrayList<>(); + this.tests = new ArrayList<>(); + + this.args = new MinionArguments(this.mutations, this.tests, "anEgine", EngineArguments.arguments(), + this.timeoutStrategy, false, TestPluginArguments.defaults()); + + when(this.is.read(MinionArguments.class)).thenReturn(this.args); + when(this.engine.createMutator(any(ClassByteArraySource.class))) + .thenReturn(this.mutater); + + final MutationEngineFactory factory = Mockito.mock(MutationEngineFactory.class); + when(factory.createEngine(any(EngineArguments.class))).thenReturn(this.engine); + + when(this.settings.createEngine(any(String.class))).thenReturn(factory); + + this.testee = new MutationTestMinion(this.settings, this.is, this.reporter); + } + + @Test + public void shouldReportNoErrorWhenNoMutationsSupplied() { + this.testee.run(); + verify(this.reporter).done(ExitCode.OK); + } + + @Test + public void shouldReportErrorWhenOneOccursDuringAnalysis() { + this.mutations.add(new MutationDetails(aMutationId().withIndex(0) + .withMutator("foo").build(), "file", "desc", 0, 0)); + when(this.mutater.getMutation(any(MutationIdentifier.class))).thenThrow( + new PitError("foo")); + this.testee.run(); + verify(this.reporter).done(ExitCode.UNKNOWN_ERROR); + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestWorkerTest.java b/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestWorkerTest.java index 16b443b46..a3cd75d00 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestWorkerTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestWorkerTest.java @@ -1,177 +1,177 @@ -package org.pitest.mutationtest.execute; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.pitest.mutationtest.LocationMother.aLocation; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassName; -import org.pitest.functional.F3; -import org.pitest.mutationtest.DetectionStatus; -import org.pitest.mutationtest.MutationStatusTestPair; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.Mutater; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.mutationtest.engine.MutationIdentifier; -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; -import org.pitest.testapi.TestUnit; - -import junit.framework.AssertionFailedError; - -public class MutationTestWorkerTest { - - private MutationTestWorker testee; - - @Mock - private ClassLoader loader; - - @Mock - private Mutater mutater; - - @Mock - private F3 hotswapper; - - @Mock - private TimeOutDecoratedTestSource testSource; - - @Mock - private Reporter reporter; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new MutationTestWorker(this.hotswapper, this.mutater, - this.loader); - } - - @Test - public void shouldDescribeEachExaminedMutation() throws IOException { - final MutationDetails mutantOne = makeMutant("foo", 1); - final MutationDetails mutantTwo = makeMutant("foo", 2); - final Collection range = Arrays.asList(mutantOne, - mutantTwo); - this.testee.run(range, this.reporter, this.testSource); - verify(this.reporter).describe(mutantOne.getId()); - verify(this.reporter).describe(mutantTwo.getId()); - } - - @Test - @Ignore("disabled while checking coverage issue") - public void shouldReportNoCoverageForMutationWithNoTestCoverage() - throws IOException { - final MutationDetails mutantOne = makeMutant("foo", 1); - final Collection range = Arrays.asList(mutantOne); - this.testee.run(range, this.reporter, this.testSource); - verify(this.reporter).report(mutantOne.getId(), - new MutationStatusTestPair(0, DetectionStatus.NO_COVERAGE)); - } - - @Test - public void shouldReportWhenMutationNotDetected() throws IOException { - final MutationDetails mutantOne = makeMutant("foo", 1); - final Collection range = Arrays.asList(mutantOne); - final TestUnit tu = makePassingTest(); - when(this.testSource.translateTests(any(List.class))).thenReturn( - Collections.singletonList(tu)); - when( - this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), - any(byte[].class))).thenReturn(true); - this.testee.run(range, this.reporter, this.testSource); - verify(this.reporter).report(mutantOne.getId(), - new MutationStatusTestPair(1, DetectionStatus.SURVIVED)); - - } - - @Test - public void shouldReportWhenMutationNotViable() throws IOException { - final MutationDetails mutantOne = makeMutant("foo", 1); - final Collection range = Arrays.asList(mutantOne); - final TestUnit tu = makePassingTest(); - when(this.testSource.translateTests(any(List.class))).thenReturn( - Collections.singletonList(tu)); - when( - this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), - any(byte[].class))).thenReturn(false); - this.testee.run(range, this.reporter, this.testSource); - verify(this.reporter).report(mutantOne.getId(), - new MutationStatusTestPair(0, DetectionStatus.NON_VIABLE)); - } - - @Test - public void shouldReportWhenMutationKilledByTest() throws IOException { - final MutationDetails mutantOne = makeMutant("foo", 1); - final Collection range = Arrays.asList(mutantOne); - final TestUnit tu = makeFailingTest(); - when(this.testSource.translateTests(any(List.class))).thenReturn( - Collections.singletonList(tu)); - when( - this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), - any(byte[].class))).thenReturn(true); - this.testee.run(range, this.reporter, this.testSource); - verify(this.reporter).report( - mutantOne.getId(), - new MutationStatusTestPair(1, DetectionStatus.KILLED, tu - .getDescription().getName())); - } - - private TestUnit makeFailingTest() { - return new TestUnit() { - - @Override - public void execute(final ResultCollector rc) { - rc.notifyStart(getDescription()); - rc.notifyEnd(getDescription(), new AssertionFailedError()); - } - - @Override - public Description getDescription() { - return new Description("atest"); - } - - }; - } - - private TestUnit makePassingTest() { - return new TestUnit() { - - @Override - public void execute(final ResultCollector rc) { - rc.notifyStart(getDescription()); - rc.notifyEnd(getDescription()); - } - - @Override - public Description getDescription() { - return new Description("atest"); - } - - }; - } - - public MutationDetails makeMutant(final String clazz, final int index) { - final MutationIdentifier id = aMutationId() - .withLocation(aLocation().withClass(ClassName.fromString(clazz))) - .withIndex(index).withMutator("mutator").build(); - final MutationDetails md = new MutationDetails(id, "sourceFile", "desc", - 42, 0); - - when(this.mutater.getMutation(md.getId())).thenReturn( - new Mutant(md, new byte[0])); - - return md; - } - -} +package org.pitest.mutationtest.execute; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.pitest.mutationtest.LocationMother.aLocation; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassName; +import org.pitest.functional.F3; +import org.pitest.mutationtest.DetectionStatus; +import org.pitest.mutationtest.MutationStatusTestPair; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.Mutater; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.mutationtest.engine.MutationIdentifier; +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; +import org.pitest.testapi.TestUnit; + +import junit.framework.AssertionFailedError; + +public class MutationTestWorkerTest { + + private MutationTestWorker testee; + + @Mock + private ClassLoader loader; + + @Mock + private Mutater mutater; + + @Mock + private F3 hotswapper; + + @Mock + private TimeOutDecoratedTestSource testSource; + + @Mock + private Reporter reporter; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new MutationTestWorker(this.hotswapper, this.mutater, + this.loader); + } + + @Test + public void shouldDescribeEachExaminedMutation() throws IOException { + final MutationDetails mutantOne = makeMutant("foo", 1); + final MutationDetails mutantTwo = makeMutant("foo", 2); + final Collection range = Arrays.asList(mutantOne, + mutantTwo); + this.testee.run(range, this.reporter, this.testSource); + verify(this.reporter).describe(mutantOne.getId()); + verify(this.reporter).describe(mutantTwo.getId()); + } + + @Test + @Ignore("disabled while checking coverage issue") + public void shouldReportNoCoverageForMutationWithNoTestCoverage() + throws IOException { + final MutationDetails mutantOne = makeMutant("foo", 1); + final Collection range = Arrays.asList(mutantOne); + this.testee.run(range, this.reporter, this.testSource); + verify(this.reporter).report(mutantOne.getId(), + new MutationStatusTestPair(0, DetectionStatus.NO_COVERAGE)); + } + + @Test + public void shouldReportWhenMutationNotDetected() throws IOException { + final MutationDetails mutantOne = makeMutant("foo", 1); + final Collection range = Arrays.asList(mutantOne); + final TestUnit tu = makePassingTest(); + when(this.testSource.translateTests(any(List.class))).thenReturn( + Collections.singletonList(tu)); + when( + this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), + any(byte[].class))).thenReturn(true); + this.testee.run(range, this.reporter, this.testSource); + verify(this.reporter).report(mutantOne.getId(), + new MutationStatusTestPair(1, DetectionStatus.SURVIVED)); + + } + + @Test + public void shouldReportWhenMutationNotViable() throws IOException { + final MutationDetails mutantOne = makeMutant("foo", 1); + final Collection range = Arrays.asList(mutantOne); + final TestUnit tu = makePassingTest(); + when(this.testSource.translateTests(any(List.class))).thenReturn( + Collections.singletonList(tu)); + when( + this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), + any(byte[].class))).thenReturn(false); + this.testee.run(range, this.reporter, this.testSource); + verify(this.reporter).report(mutantOne.getId(), + new MutationStatusTestPair(0, DetectionStatus.NON_VIABLE)); + } + + @Test + public void shouldReportWhenMutationKilledByTest() throws IOException { + final MutationDetails mutantOne = makeMutant("foo", 1); + final Collection range = Arrays.asList(mutantOne); + final TestUnit tu = makeFailingTest(); + when(this.testSource.translateTests(any(List.class))).thenReturn( + Collections.singletonList(tu)); + when( + this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), + any(byte[].class))).thenReturn(true); + this.testee.run(range, this.reporter, this.testSource); + verify(this.reporter).report( + mutantOne.getId(), + new MutationStatusTestPair(1, DetectionStatus.KILLED, tu + .getDescription().getName())); + } + + private TestUnit makeFailingTest() { + return new TestUnit() { + + @Override + public void execute(final ResultCollector rc) { + rc.notifyStart(getDescription()); + rc.notifyEnd(getDescription(), new AssertionFailedError()); + } + + @Override + public Description getDescription() { + return new Description("atest"); + } + + }; + } + + private TestUnit makePassingTest() { + return new TestUnit() { + + @Override + public void execute(final ResultCollector rc) { + rc.notifyStart(getDescription()); + rc.notifyEnd(getDescription()); + } + + @Override + public Description getDescription() { + return new Description("atest"); + } + + }; + } + + public MutationDetails makeMutant(final String clazz, final int index) { + final MutationIdentifier id = aMutationId() + .withLocation(aLocation().withClass(ClassName.fromString(clazz))) + .withIndex(index).withMutator("mutator").build(); + final MutationDetails md = new MutationDetails(id, "sourceFile", "desc", + 42, 0); + + when(this.mutater.getMutation(md.getId())).thenReturn( + new Mutant(md, new byte[0])); + + return md; + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTimeoutDecoratorTest.java b/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTimeoutDecoratorTest.java index 6fcd12d84..65698045b 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTimeoutDecoratorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/execute/MutationTimeoutDecoratorTest.java @@ -1,79 +1,79 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.execute; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.functional.SideEffect; -import org.pitest.mutationtest.TimeoutLengthStrategy; -import org.pitest.testapi.ResultCollector; -import org.pitest.testapi.TestUnit; - -public class MutationTimeoutDecoratorTest { - - private MutationTimeoutDecorator testee; - - @Mock - private SideEffect sideEffect; - - @Mock - private TimeoutLengthStrategy timeoutStrategy; - - @Mock - private TestUnit child; - - @Mock - private ResultCollector rc; - - private static final long NORMAL_EXECUTION = 1; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new MutationTimeoutDecorator(this.child, this.sideEffect, - this.timeoutStrategy, NORMAL_EXECUTION); - } - - @Test - public void shouldCompleteNormallyWhenChildExecutesWithinAllowedTime() { - when(this.timeoutStrategy.getAllowedTime(NORMAL_EXECUTION)).thenReturn( - 1000l); - this.testee.execute(this.rc); - verify(this.child).execute(any(ResultCollector.class)); - verify(this.sideEffect, never()).apply(); - } - - @Test - public void shouldApplySideEffectWhenChildRunsForLongerThanAllowedTime() { - when(this.timeoutStrategy.getAllowedTime(NORMAL_EXECUTION)).thenReturn(50l); - - doAnswer(invocation -> { - Thread.sleep(100); - return null; - }).when(this.child).execute(any(ResultCollector.class)); - - this.testee.execute(this.rc); - verify(this.child).execute(any(ResultCollector.class)); - verify(this.sideEffect).apply(); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.execute; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.functional.SideEffect; +import org.pitest.mutationtest.TimeoutLengthStrategy; +import org.pitest.testapi.ResultCollector; +import org.pitest.testapi.TestUnit; + +public class MutationTimeoutDecoratorTest { + + private MutationTimeoutDecorator testee; + + @Mock + private SideEffect sideEffect; + + @Mock + private TimeoutLengthStrategy timeoutStrategy; + + @Mock + private TestUnit child; + + @Mock + private ResultCollector rc; + + private static final long NORMAL_EXECUTION = 1; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new MutationTimeoutDecorator(this.child, this.sideEffect, + this.timeoutStrategy, NORMAL_EXECUTION); + } + + @Test + public void shouldCompleteNormallyWhenChildExecutesWithinAllowedTime() { + when(this.timeoutStrategy.getAllowedTime(NORMAL_EXECUTION)).thenReturn( + 1000l); + this.testee.execute(this.rc); + verify(this.child).execute(any(ResultCollector.class)); + verify(this.sideEffect, never()).apply(); + } + + @Test + public void shouldApplySideEffectWhenChildRunsForLongerThanAllowedTime() { + when(this.timeoutStrategy.getAllowedTime(NORMAL_EXECUTION)).thenReturn(50l); + + doAnswer(invocation -> { + Thread.sleep(100); + return null; + }).when(this.child).execute(any(ResultCollector.class)); + + this.testee.execute(this.rc); + verify(this.child).execute(any(ResultCollector.class)); + verify(this.sideEffect).apply(); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/execute/TimeOutDecoratedTestSourceTest.java b/pitest/src/test/java/org/pitest/mutationtest/execute/TimeOutDecoratedTestSourceTest.java index e8ecb8fcd..d3a10c34a 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/execute/TimeOutDecoratedTestSourceTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/execute/TimeOutDecoratedTestSourceTest.java @@ -1,90 +1,90 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.execute; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classinfo.ClassName; -import org.pitest.coverage.TestInfo; -import java.util.Optional; -import org.pitest.mutationtest.TimeoutLengthStrategy; -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; -import org.pitest.testapi.TestUnit; - -public class TimeOutDecoratedTestSourceTest { - - private TimeOutDecoratedTestSource testee; - - @Mock - private TimeoutLengthStrategy timeoutStrategy; - - @Mock - private Reporter reporter; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - this.testee = new TimeOutDecoratedTestSource(this.timeoutStrategy, - Arrays.asList(makeTestUnit("one"), makeTestUnit("two")), this.reporter); - } - - @Test - public void shouldReturnNoTestUnitsWhenNoTestDetailsSupplied() { - assertTrue(this.testee.translateTests(Collections. emptyList()) - .isEmpty()); - } - - @Test - public void shouldReturnNoTestUnitWhenNonMatchingTestDetailSupplied() { - assertTrue(this.testee.translateTests( - Arrays.asList(new TestInfo("foo", "bar", 42, Optional. empty(), - 0))).isEmpty()); - } - - @Test - public void shouldReturnTestUnitWhenMatchingTestDetailSupplied() { - final List actual = this.testee.translateTests(Arrays - .asList(new TestInfo("foo", "one", 42, Optional. empty(), 0))); - assertEquals(1, actual.size()); - } - - private TestUnit makeTestUnit(final String name) { - return new TestUnit() { - private final Description description = new Description(name); - - @Override - public void execute(final ResultCollector rc) { - } - - @Override - public Description getDescription() { - return this.description; - } - - }; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.execute; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classinfo.ClassName; +import org.pitest.coverage.TestInfo; +import java.util.Optional; +import org.pitest.mutationtest.TimeoutLengthStrategy; +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; +import org.pitest.testapi.TestUnit; + +public class TimeOutDecoratedTestSourceTest { + + private TimeOutDecoratedTestSource testee; + + @Mock + private TimeoutLengthStrategy timeoutStrategy; + + @Mock + private Reporter reporter; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + this.testee = new TimeOutDecoratedTestSource(this.timeoutStrategy, + Arrays.asList(makeTestUnit("one"), makeTestUnit("two")), this.reporter); + } + + @Test + public void shouldReturnNoTestUnitsWhenNoTestDetailsSupplied() { + assertTrue(this.testee.translateTests(Collections. emptyList()) + .isEmpty()); + } + + @Test + public void shouldReturnNoTestUnitWhenNonMatchingTestDetailSupplied() { + assertTrue(this.testee.translateTests( + Arrays.asList(new TestInfo("foo", "bar", 42, Optional. empty(), + 0))).isEmpty()); + } + + @Test + public void shouldReturnTestUnitWhenMatchingTestDetailSupplied() { + final List actual = this.testee.translateTests(Arrays + .asList(new TestInfo("foo", "one", 42, Optional. empty(), 0))); + assertEquals(1, actual.size()); + } + + private TestUnit makeTestUnit(final String name) { + return new TestUnit() { + private final Description description = new Description(name); + + @Override + public void execute(final ResultCollector rc) { + } + + @Override + public Description getDescription() { + return this.description; + } + + }; + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/execute/TimeOutSystemExitSideEffectTest.java b/pitest/src/test/java/org/pitest/mutationtest/execute/TimeOutSystemExitSideEffectTest.java index f2e89a5b4..8803867fa 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/execute/TimeOutSystemExitSideEffectTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/execute/TimeOutSystemExitSideEffectTest.java @@ -1,44 +1,44 @@ -/* - * Copyright 2012 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.mutationtest.execute; - -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.util.ExitCode; - -public class TimeOutSystemExitSideEffectTest { - - @Mock - private Reporter reporter; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void shouldReportExitCodeOfTimeOut() { - final TimeOutSystemExitSideEffect testee = new TimeOutSystemExitSideEffect( - this.reporter); - testee.apply(); - verify(this.reporter).done(ExitCode.TIMEOUT); - - } - -} +/* + * Copyright 2012 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.execute; + +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.util.ExitCode; + +public class TimeOutSystemExitSideEffectTest { + + @Mock + private Reporter reporter; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldReportExitCodeOfTimeOut() { + final TimeOutSystemExitSideEffect testee = new TimeOutSystemExitSideEffect( + this.reporter); + testee.apply(); + verify(this.reporter).done(ExitCode.TIMEOUT); + + } + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/mocksupport/BendJavassistToMyWillTransformerTest.java b/pitest/src/test/java/org/pitest/mutationtest/mocksupport/BendJavassistToMyWillTransformerTest.java index 3508aaa3a..332a5ad12 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/mocksupport/BendJavassistToMyWillTransformerTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/mocksupport/BendJavassistToMyWillTransformerTest.java @@ -1,52 +1,52 @@ -package org.pitest.mutationtest.mocksupport; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - -import java.lang.instrument.IllegalClassFormatException; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.classpath.ClassloaderByteArraySource; -import org.pitest.util.IsolationUtils; - -public class BendJavassistToMyWillTransformerTest { - - private BendJavassistToMyWillTransformer testee; - - @Mock - private Predicate filter; - - private byte[] bytes; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new BendJavassistToMyWillTransformer(this.filter, JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistInterceptor.class)); - final ClassloaderByteArraySource source = new ClassloaderByteArraySource( - IsolationUtils.getContextClassLoader()); - this.bytes = source.getBytes("java.lang.String").get(); - } - - @Test - public void shouldNotTransformClassesNotMatchingFilter() - throws IllegalClassFormatException { - when(this.filter.test(any(String.class))).thenReturn(false); - assertNull(this.testee.transform(null, "foo", null, null, this.bytes)); - } - - @Test - public void shouldTransformClassesMatchingFilter() - throws IllegalClassFormatException { - when(this.filter.test(any(String.class))).thenReturn(true); - assertFalse(null == this.testee.transform(null, "foo", null, null, - this.bytes)); - } - - -} +package org.pitest.mutationtest.mocksupport; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +import java.lang.instrument.IllegalClassFormatException; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.classpath.ClassloaderByteArraySource; +import org.pitest.util.IsolationUtils; + +public class BendJavassistToMyWillTransformerTest { + + private BendJavassistToMyWillTransformer testee; + + @Mock + private Predicate filter; + + private byte[] bytes; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new BendJavassistToMyWillTransformer(this.filter, JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistInterceptor.class)); + final ClassloaderByteArraySource source = new ClassloaderByteArraySource( + IsolationUtils.getContextClassLoader()); + this.bytes = source.getBytes("java.lang.String").get(); + } + + @Test + public void shouldNotTransformClassesNotMatchingFilter() + throws IllegalClassFormatException { + when(this.filter.test(any(String.class))).thenReturn(false); + assertNull(this.testee.transform(null, "foo", null, null, this.bytes)); + } + + @Test + public void shouldTransformClassesMatchingFilter() + throws IllegalClassFormatException { + when(this.filter.test(any(String.class))).thenReturn(true); + assertFalse(null == this.testee.transform(null, "foo", null, null, + this.bytes)); + } + + +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/mocksupport/JavassistInputStreamInterceptorAdapaterTest.java b/pitest/src/test/java/org/pitest/mutationtest/mocksupport/JavassistInputStreamInterceptorAdapaterTest.java index ec9479195..dcafe25cd 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/mocksupport/JavassistInputStreamInterceptorAdapaterTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/mocksupport/JavassistInputStreamInterceptorAdapaterTest.java @@ -1,58 +1,58 @@ -package org.pitest.mutationtest.mocksupport; - -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -public class JavassistInputStreamInterceptorAdapaterTest { - - private JavassistInputStreamInterceptorMethodVisitor testee; - - @Mock - private MethodVisitor mv; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new JavassistInputStreamInterceptorMethodVisitor(this.mv, "com.example.TheInterceptorClassName"); - } - - @Test - public void shouldNotInterceptNormalInvokeInterfaceCalls() { - this.testee.visitMethodInsn(Opcodes.INVOKEINTERFACE, "foo", "bar", "far", - false); - verify(this.mv).visitMethodInsn(Opcodes.INVOKEINTERFACE, "foo", "bar", - "far", false); - } - - @Test - public void shouldNotInterceptNormalInvokeStaticCalls() { - this.testee.visitMethodInsn(Opcodes.INVOKESTATIC, "foo", "bar", "far", - false); - verify(this.mv).visitMethodInsn(Opcodes.INVOKESTATIC, "foo", "bar", "far", - false); - } - - @Test - public void shouldNotInterceptCallsToMethodsCalledOpenClassFileNotInJavaAssist() { - this.testee.visitMethodInsn(Opcodes.INVOKEINTERFACE, "foo", - "openClassfile", "far", false); - verify(this.mv).visitMethodInsn(Opcodes.INVOKEINTERFACE, "foo", - "openClassfile", "far", false); - } - - @Test - public void shouldInterceptCallsToOpenClassFileInJavaAssist() { - this.testee.visitMethodInsn(Opcodes.INVOKEINTERFACE, "javassist/ClassPath", - "openClassfile", "far", false); - verify(this.mv).visitMethodInsn(Opcodes.INVOKESTATIC, - "com.example.TheInterceptorClassName", - "openClassfile", - "(Ljava/lang/Object;Ljava/lang/String;)Ljava/io/InputStream;", false); - } -} +package org.pitest.mutationtest.mocksupport; + +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +public class JavassistInputStreamInterceptorAdapaterTest { + + private JavassistInputStreamInterceptorMethodVisitor testee; + + @Mock + private MethodVisitor mv; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new JavassistInputStreamInterceptorMethodVisitor(this.mv, "com.example.TheInterceptorClassName"); + } + + @Test + public void shouldNotInterceptNormalInvokeInterfaceCalls() { + this.testee.visitMethodInsn(Opcodes.INVOKEINTERFACE, "foo", "bar", "far", + false); + verify(this.mv).visitMethodInsn(Opcodes.INVOKEINTERFACE, "foo", "bar", + "far", false); + } + + @Test + public void shouldNotInterceptNormalInvokeStaticCalls() { + this.testee.visitMethodInsn(Opcodes.INVOKESTATIC, "foo", "bar", "far", + false); + verify(this.mv).visitMethodInsn(Opcodes.INVOKESTATIC, "foo", "bar", "far", + false); + } + + @Test + public void shouldNotInterceptCallsToMethodsCalledOpenClassFileNotInJavaAssist() { + this.testee.visitMethodInsn(Opcodes.INVOKEINTERFACE, "foo", + "openClassfile", "far", false); + verify(this.mv).visitMethodInsn(Opcodes.INVOKEINTERFACE, "foo", + "openClassfile", "far", false); + } + + @Test + public void shouldInterceptCallsToOpenClassFileInJavaAssist() { + this.testee.visitMethodInsn(Opcodes.INVOKEINTERFACE, "javassist/ClassPath", + "openClassfile", "far", false); + verify(this.mv).visitMethodInsn(Opcodes.INVOKESTATIC, + "com.example.TheInterceptorClassName", + "openClassfile", + "(Ljava/lang/Object;Ljava/lang/String;)Ljava/io/InputStream;", false); + } +} diff --git a/pitest/src/test/java/org/pitest/mutationtest/mocksupport/JavassistInterceptorTest.java b/pitest/src/test/java/org/pitest/mutationtest/mocksupport/JavassistInterceptorTest.java index 3fb02b71c..9ee50cb3d 100644 --- a/pitest/src/test/java/org/pitest/mutationtest/mocksupport/JavassistInterceptorTest.java +++ b/pitest/src/test/java/org/pitest/mutationtest/mocksupport/JavassistInterceptorTest.java @@ -1,72 +1,72 @@ -package org.pitest.mutationtest.mocksupport; - -import static org.junit.Assert.assertEquals; -import static org.pitest.mutationtest.LocationMother.aLocation; -import static org.pitest.mutationtest.LocationMother.aMutationId; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.classinfo.ClassName; -import org.pitest.mutationtest.engine.Mutant; -import org.pitest.mutationtest.engine.MutationDetails; -import org.pitest.util.StreamUtil; - -public class JavassistInterceptorTest { - - public class AClassWithAOpenClassFileMethod { - public InputStream openClassfile(final String name) { - return new ByteArrayInputStream("original".getBytes()); - } - } - - private AClassWithAOpenClassFileMethod interceptedClass; - private Mutant mutant; - - @Before - public void setUp() { - this.interceptedClass = new AClassWithAOpenClassFileMethod(); - final byte[] bytes = "replaced".getBytes(); - this.mutant = new Mutant(new MutationDetails(aMutationId().withLocation( - aLocation().withClass(ClassName.fromString("match"))).build(), "foo", - "foo", 0, 0), bytes); - } - - @Test - public void shouldNotReplaceRequestedClassWithMutantWhenClassNameIsDifferent() - throws IOException { - JavassistInterceptor.setMutant(this.mutant); - final InputStream actual = JavassistInterceptor.openClassfile( - this.interceptedClass, "nomatch"); - assertEquals(streamToString(actual), - streamToString(this.interceptedClass.openClassfile(""))); - } - - @Test - public void shouldNotReplaceRequestedClassWithMutantWhenNoMutantIsSet() - throws IOException { - JavassistInterceptor.setMutant(null); - final InputStream actual = JavassistInterceptor.openClassfile( - this.interceptedClass, "nomatch"); - assertEquals(streamToString(actual), - streamToString(this.interceptedClass.openClassfile(""))); - } - - @Test - public void shouldReplaceRequestedClassWithMutantWhenClassNameMatches() - throws IOException { - JavassistInterceptor.setMutant(this.mutant); - final InputStream actual = JavassistInterceptor.openClassfile( - this.interceptedClass, "match"); - - assertEquals(streamToString(actual), "replaced"); - } - - private String streamToString(final InputStream is) throws IOException { - return new String(StreamUtil.streamToByteArray(is)); - } - -} +package org.pitest.mutationtest.mocksupport; + +import static org.junit.Assert.assertEquals; +import static org.pitest.mutationtest.LocationMother.aLocation; +import static org.pitest.mutationtest.LocationMother.aMutationId; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.classinfo.ClassName; +import org.pitest.mutationtest.engine.Mutant; +import org.pitest.mutationtest.engine.MutationDetails; +import org.pitest.util.StreamUtil; + +public class JavassistInterceptorTest { + + public class AClassWithAOpenClassFileMethod { + public InputStream openClassfile(final String name) { + return new ByteArrayInputStream("original".getBytes()); + } + } + + private AClassWithAOpenClassFileMethod interceptedClass; + private Mutant mutant; + + @Before + public void setUp() { + this.interceptedClass = new AClassWithAOpenClassFileMethod(); + final byte[] bytes = "replaced".getBytes(); + this.mutant = new Mutant(new MutationDetails(aMutationId().withLocation( + aLocation().withClass(ClassName.fromString("match"))).build(), "foo", + "foo", 0, 0), bytes); + } + + @Test + public void shouldNotReplaceRequestedClassWithMutantWhenClassNameIsDifferent() + throws IOException { + JavassistInterceptor.setMutant(this.mutant); + final InputStream actual = JavassistInterceptor.openClassfile( + this.interceptedClass, "nomatch"); + assertEquals(streamToString(actual), + streamToString(this.interceptedClass.openClassfile(""))); + } + + @Test + public void shouldNotReplaceRequestedClassWithMutantWhenNoMutantIsSet() + throws IOException { + JavassistInterceptor.setMutant(null); + final InputStream actual = JavassistInterceptor.openClassfile( + this.interceptedClass, "nomatch"); + assertEquals(streamToString(actual), + streamToString(this.interceptedClass.openClassfile(""))); + } + + @Test + public void shouldReplaceRequestedClassWithMutantWhenClassNameMatches() + throws IOException { + JavassistInterceptor.setMutant(this.mutant); + final InputStream actual = JavassistInterceptor.openClassfile( + this.interceptedClass, "match"); + + assertEquals(streamToString(actual), "replaced"); + } + + private String streamToString(final InputStream is) throws IOException { + return new String(StreamUtil.streamToByteArray(is)); + } + +} diff --git a/pitest/src/test/java/org/pitest/plugin/FeatureParserTest.java b/pitest/src/test/java/org/pitest/plugin/FeatureParserTest.java index 34bb88260..4cbcbe34d 100644 --- a/pitest/src/test/java/org/pitest/plugin/FeatureParserTest.java +++ b/pitest/src/test/java/org/pitest/plugin/FeatureParserTest.java @@ -1,91 +1,91 @@ - package org.pitest.plugin; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collections; -import java.util.List; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import java.util.Optional; - -public class FeatureParserTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - FeatureParser testee = new FeatureParser(); - - @Test - public void shouldRejectInputNotStartingWithPlusOrMinus() { - this.thrown.expect(RuntimeException.class); - final FeatureSetting actual = parse("FOO"); - assertThat(actual.addsFeature()).isFalse(); - } - - @Test - public void shouldEnableFeaturesStartingWithPlus() { - final FeatureSetting actual = parse("+FOO"); - assertThat(actual.addsFeature()).isTrue(); - assertThat(actual.removesFeature()).isFalse(); - } - - @Test - public void shouldDisableFeaturesStartingWithMinus() { - final FeatureSetting actual = parse("-FOO"); - assertThat(actual.addsFeature()).isFalse(); - assertThat(actual.removesFeature()).isTrue(); - } - - @Test - public void shouldParseFeatureNameWhenNoConfig() { - final FeatureSetting actual = parse("-FOO"); - assertThat(actual.feature()).isEqualTo("FOO"); - } - - @Test - public void shouldParseFeatureNameWhenLeadingWhitespace() { - final FeatureSetting actual = parse(" -FOO"); - assertThat(actual.feature()).isEqualTo("FOO"); - } - - @Test - public void shouldParseFeatureNameWhenTrailingWhitespace() { - final FeatureSetting actual = parse("-FOO "); - assertThat(actual.feature()).isEqualTo("FOO"); - } - - @Test - public void shouldParseFeatureNameWhenEmptyConfig() { - final FeatureSetting actual = parse("+BAR()"); - assertThat(actual.feature()).isEqualTo("BAR"); - } - - @Test - public void shouldParseSingleConfigValues() { - final FeatureSetting actual = parse("+BAR(name[hello])"); - assertThat(actual.getString("name")).isEqualTo(Optional.ofNullable("hello")); - } - - @Test - public void shouldParseMultipleConfigValues() { - final FeatureSetting actual = parse("+BAR(name[hello]size[42])"); - assertThat(actual.getString("name")).isEqualTo(Optional.ofNullable("hello")); - assertThat(actual.getString("size")).isEqualTo(Optional.ofNullable("42")); - } - - - @Test - public void shouldParseListValues() { - final FeatureSetting actual = parse("+BAR(things[1] things[2] things[3] things[4] size[42])"); - assertThat(actual.getList("things")).contains("1","2","3","4"); - } - - - private FeatureSetting parse(String dsl) { - final List actual = this.testee.parseFeatures(Collections.singletonList(dsl)); - return actual.get(0); - } - -} + package org.pitest.plugin; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import java.util.Optional; + +public class FeatureParserTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + FeatureParser testee = new FeatureParser(); + + @Test + public void shouldRejectInputNotStartingWithPlusOrMinus() { + this.thrown.expect(RuntimeException.class); + final FeatureSetting actual = parse("FOO"); + assertThat(actual.addsFeature()).isFalse(); + } + + @Test + public void shouldEnableFeaturesStartingWithPlus() { + final FeatureSetting actual = parse("+FOO"); + assertThat(actual.addsFeature()).isTrue(); + assertThat(actual.removesFeature()).isFalse(); + } + + @Test + public void shouldDisableFeaturesStartingWithMinus() { + final FeatureSetting actual = parse("-FOO"); + assertThat(actual.addsFeature()).isFalse(); + assertThat(actual.removesFeature()).isTrue(); + } + + @Test + public void shouldParseFeatureNameWhenNoConfig() { + final FeatureSetting actual = parse("-FOO"); + assertThat(actual.feature()).isEqualTo("FOO"); + } + + @Test + public void shouldParseFeatureNameWhenLeadingWhitespace() { + final FeatureSetting actual = parse(" -FOO"); + assertThat(actual.feature()).isEqualTo("FOO"); + } + + @Test + public void shouldParseFeatureNameWhenTrailingWhitespace() { + final FeatureSetting actual = parse("-FOO "); + assertThat(actual.feature()).isEqualTo("FOO"); + } + + @Test + public void shouldParseFeatureNameWhenEmptyConfig() { + final FeatureSetting actual = parse("+BAR()"); + assertThat(actual.feature()).isEqualTo("BAR"); + } + + @Test + public void shouldParseSingleConfigValues() { + final FeatureSetting actual = parse("+BAR(name[hello])"); + assertThat(actual.getString("name")).isEqualTo(Optional.ofNullable("hello")); + } + + @Test + public void shouldParseMultipleConfigValues() { + final FeatureSetting actual = parse("+BAR(name[hello]size[42])"); + assertThat(actual.getString("name")).isEqualTo(Optional.ofNullable("hello")); + assertThat(actual.getString("size")).isEqualTo(Optional.ofNullable("42")); + } + + + @Test + public void shouldParseListValues() { + final FeatureSetting actual = parse("+BAR(things[1] things[2] things[3] things[4] size[42])"); + assertThat(actual.getList("things")).contains("1","2","3","4"); + } + + + private FeatureSetting parse(String dsl) { + final List actual = this.testee.parseFeatures(Collections.singletonList(dsl)); + return actual.get(0); + } + +} diff --git a/pitest/src/test/java/org/pitest/plugin/FeatureSelectorTest.java b/pitest/src/test/java/org/pitest/plugin/FeatureSelectorTest.java index 285b34d6d..1a9a1ee4c 100644 --- a/pitest/src/test/java/org/pitest/plugin/FeatureSelectorTest.java +++ b/pitest/src/test/java/org/pitest/plugin/FeatureSelectorTest.java @@ -1,101 +1,101 @@ -package org.pitest.plugin; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class FeatureSelectorTest { - - FeatureSelector testee; - - ProvidesFooByDefault onByDefault = new ProvidesFooByDefault(); - ProvidesBarOptionally offByDefault = new ProvidesBarOptionally(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void shouldSelectFeaturesThatAreOnByDefault() { - final ProvidesFooByDefault onByDefault = new ProvidesFooByDefault(); - this.testee = new FeatureSelector<>(noSettings(), features(onByDefault)); - - assertThat(this.testee.getActiveFeatures()).contains(onByDefault); - } - - @Test - public void shouldSelectFeaturesThatAreOffByDefault() { - this.testee = new FeatureSelector<>(noSettings(), features(this.onByDefault, this.offByDefault)); - - assertThat(this.testee.getActiveFeatures()).containsOnly(this.onByDefault); - } - - @Test - public void shouldEnableFeaturesWhenRequested() { - final FeatureSetting enableBar = new FeatureSetting("bar", ToggleStatus.ACTIVATE, new HashMap>()); - this.testee = new FeatureSelector<>(Arrays.asList(enableBar), features(this.onByDefault, this.offByDefault)); - - assertThat(this.testee.getActiveFeatures()).containsOnly(this.offByDefault, this.onByDefault); - } - - @Test - public void shouldDisableFeaturesWhenRequested() { - final FeatureSetting disableFoo = new FeatureSetting("foo", ToggleStatus.DEACTIVATE, new HashMap>()); - this.testee = new FeatureSelector<>(Arrays.asList(disableFoo), features(this.onByDefault)); - - assertThat(this.testee.getActiveFeatures()).isEmpty(); - } - - @Test - public void shouldThrowErrorWhenConfigForUnknownFeatureProvided() { - final FeatureSetting wrong = new FeatureSetting("unknown", ToggleStatus.DEACTIVATE, new HashMap>()); - - this.thrown.expect(IllegalArgumentException.class); - this.testee = new FeatureSelector<>(Arrays.asList(wrong), features(this.onByDefault)); - } - - @Test - public void shouldProvideConfigurationForFeatureWhenProvided() { - final FeatureSetting fooConfig = new FeatureSetting("foo", ToggleStatus.DEACTIVATE, new HashMap>()); - this.testee = new FeatureSelector<>(Arrays.asList(fooConfig), features(this.onByDefault)); - - assertThat(this.testee.getSettingForFeature("foo")).isEqualTo(fooConfig); - assertThat(this.testee.getSettingForFeature("bar")).isNull(); - } - - private List noSettings() { - return Collections.emptyList(); - } - - private List features(AFeature ...features) { - return Arrays.asList(features); - } -} - -interface AFeature extends ProvidesFeature { - -} - -class ProvidesFooByDefault implements AFeature { - - @Override - public Feature provides() { - return Feature.named("foo").withOnByDefault(true); - } - -} - -class ProvidesBarOptionally implements AFeature { - - @Override - public Feature provides() { - return Feature.named("bar").withOnByDefault(false); - } - -} +package org.pitest.plugin; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class FeatureSelectorTest { + + FeatureSelector testee; + + ProvidesFooByDefault onByDefault = new ProvidesFooByDefault(); + ProvidesBarOptionally offByDefault = new ProvidesBarOptionally(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void shouldSelectFeaturesThatAreOnByDefault() { + final ProvidesFooByDefault onByDefault = new ProvidesFooByDefault(); + this.testee = new FeatureSelector<>(noSettings(), features(onByDefault)); + + assertThat(this.testee.getActiveFeatures()).contains(onByDefault); + } + + @Test + public void shouldSelectFeaturesThatAreOffByDefault() { + this.testee = new FeatureSelector<>(noSettings(), features(this.onByDefault, this.offByDefault)); + + assertThat(this.testee.getActiveFeatures()).containsOnly(this.onByDefault); + } + + @Test + public void shouldEnableFeaturesWhenRequested() { + final FeatureSetting enableBar = new FeatureSetting("bar", ToggleStatus.ACTIVATE, new HashMap>()); + this.testee = new FeatureSelector<>(Arrays.asList(enableBar), features(this.onByDefault, this.offByDefault)); + + assertThat(this.testee.getActiveFeatures()).containsOnly(this.offByDefault, this.onByDefault); + } + + @Test + public void shouldDisableFeaturesWhenRequested() { + final FeatureSetting disableFoo = new FeatureSetting("foo", ToggleStatus.DEACTIVATE, new HashMap>()); + this.testee = new FeatureSelector<>(Arrays.asList(disableFoo), features(this.onByDefault)); + + assertThat(this.testee.getActiveFeatures()).isEmpty(); + } + + @Test + public void shouldThrowErrorWhenConfigForUnknownFeatureProvided() { + final FeatureSetting wrong = new FeatureSetting("unknown", ToggleStatus.DEACTIVATE, new HashMap>()); + + this.thrown.expect(IllegalArgumentException.class); + this.testee = new FeatureSelector<>(Arrays.asList(wrong), features(this.onByDefault)); + } + + @Test + public void shouldProvideConfigurationForFeatureWhenProvided() { + final FeatureSetting fooConfig = new FeatureSetting("foo", ToggleStatus.DEACTIVATE, new HashMap>()); + this.testee = new FeatureSelector<>(Arrays.asList(fooConfig), features(this.onByDefault)); + + assertThat(this.testee.getSettingForFeature("foo")).isEqualTo(fooConfig); + assertThat(this.testee.getSettingForFeature("bar")).isNull(); + } + + private List noSettings() { + return Collections.emptyList(); + } + + private List features(AFeature ...features) { + return Arrays.asList(features); + } +} + +interface AFeature extends ProvidesFeature { + +} + +class ProvidesFooByDefault implements AFeature { + + @Override + public Feature provides() { + return Feature.named("foo").withOnByDefault(true); + } + +} + +class ProvidesBarOptionally implements AFeature { + + @Override + public Feature provides() { + return Feature.named("bar").withOnByDefault(false); + } + +} diff --git a/pitest/src/test/java/org/pitest/plugin/FeatureSettingTest.java b/pitest/src/test/java/org/pitest/plugin/FeatureSettingTest.java index ebfddfc4f..cf3654bcb 100644 --- a/pitest/src/test/java/org/pitest/plugin/FeatureSettingTest.java +++ b/pitest/src/test/java/org/pitest/plugin/FeatureSettingTest.java @@ -1,53 +1,53 @@ -package org.pitest.plugin; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import java.util.Optional; - -public class FeatureSettingTest { - - FeatureSetting testee; - private final Map> values = new HashMap<>(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void shouldReturnNoneWhenNoneSupplied() { - this.testee = new FeatureSetting("name", ToggleStatus.ACTIVATE, this.values); - assertThat(this.testee.getString("foo")).isEqualTo(Optional.empty()); - } - - - @Test - public void shouldReturnSingleValuesWhenSupplied() { - this.values.put("foo", Arrays.asList("1")); - this.testee = new FeatureSetting("name", ToggleStatus.ACTIVATE, this.values); - assertThat(this.testee.getString("foo")).isEqualTo(Optional.ofNullable("1")); - } - - @Test - public void shouldThrowErrorWhenMultipleItemsSuppliedForNonList() { - this.values.put("foo", Arrays.asList("1", "2")); - this.testee = new FeatureSetting("name", ToggleStatus.ACTIVATE, this.values); - - this.thrown.expect(IllegalArgumentException.class); - this.testee.getString("foo"); - } - - @Test - public void shouldReturnMultipleValuesForLists() { - this.values.put("foo", Arrays.asList("1", "2", "3")); - this.testee = new FeatureSetting("name", ToggleStatus.ACTIVATE, this.values); - assertThat(this.testee.getList("foo")).contains("1", "2", "3"); - } - -} +package org.pitest.plugin; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import java.util.Optional; + +public class FeatureSettingTest { + + FeatureSetting testee; + private final Map> values = new HashMap<>(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void shouldReturnNoneWhenNoneSupplied() { + this.testee = new FeatureSetting("name", ToggleStatus.ACTIVATE, this.values); + assertThat(this.testee.getString("foo")).isEqualTo(Optional.empty()); + } + + + @Test + public void shouldReturnSingleValuesWhenSupplied() { + this.values.put("foo", Arrays.asList("1")); + this.testee = new FeatureSetting("name", ToggleStatus.ACTIVATE, this.values); + assertThat(this.testee.getString("foo")).isEqualTo(Optional.ofNullable("1")); + } + + @Test + public void shouldThrowErrorWhenMultipleItemsSuppliedForNonList() { + this.values.put("foo", Arrays.asList("1", "2")); + this.testee = new FeatureSetting("name", ToggleStatus.ACTIVATE, this.values); + + this.thrown.expect(IllegalArgumentException.class); + this.testee.getString("foo"); + } + + @Test + public void shouldReturnMultipleValuesForLists() { + this.values.put("foo", Arrays.asList("1", "2", "3")); + this.testee = new FeatureSetting("name", ToggleStatus.ACTIVATE, this.values); + assertThat(this.testee.getList("foo")).contains("1", "2", "3"); + } + +} diff --git a/pitest/src/test/java/org/pitest/plugin/FeatureTest.java b/pitest/src/test/java/org/pitest/plugin/FeatureTest.java index c57b1e9f6..26506ac81 100644 --- a/pitest/src/test/java/org/pitest/plugin/FeatureTest.java +++ b/pitest/src/test/java/org/pitest/plugin/FeatureTest.java @@ -1,22 +1,22 @@ -package org.pitest.plugin; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class FeatureTest { - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(Feature.class).verify(); - } - - @Test - public void shouldUseOnlyNameForEquality() { - assertThat(Feature.named("foo")) - .isEqualTo(Feature.named("foo").withDescription("?").withOnByDefault(false)); - } - -} +package org.pitest.plugin; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class FeatureTest { + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(Feature.class).verify(); + } + + @Test + public void shouldUseOnlyNameForEquality() { + assertThat(Feature.named("foo")) + .isEqualTo(Feature.named("foo").withDescription("?").withOnByDefault(false)); + } + +} diff --git a/pitest/src/test/java/org/pitest/reflection/ReflectionTest.java b/pitest/src/test/java/org/pitest/reflection/ReflectionTest.java index 762190fb0..1432e8917 100644 --- a/pitest/src/test/java/org/pitest/reflection/ReflectionTest.java +++ b/pitest/src/test/java/org/pitest/reflection/ReflectionTest.java @@ -1,67 +1,67 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.reflection; - -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Set; - -import org.junit.Test; - -public class ReflectionTest { - - static class Parent { - public int first; - - public void foo() { - - } - } - - static class Child extends Parent { - public int second; - public static int third; - } - - @Test - public void allMethodsShouldReturnPublicMethodsDeclaredByParent() { - final Set actual = Reflection.allMethods(Child.class); - final Method expected = Reflection.publicMethod(Parent.class, "foo"); - assertTrue(actual.contains(expected)); - } - - @Test - public void publicFieldsReturnsFieldsDeclaredInParent() throws Exception { - final Set actual = Reflection.publicFields(Child.class); - final Field expected = Parent.class.getField("first"); - assertTrue(actual.contains(expected)); - } - - @Test - public void publicFieldsReturnsFieldsDeclaredInChild() throws Exception { - final Set actual = Reflection.publicFields(Child.class); - final Field expected = Child.class.getField("second"); - assertTrue(actual.contains(expected)); - } - - @Test - public void publicFieldsReturnsStaticFields() throws Exception { - final Set actual = Reflection.publicFields(Child.class); - final Field expected = Child.class.getField("third"); - assertTrue(actual.contains(expected)); - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.reflection; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Set; + +import org.junit.Test; + +public class ReflectionTest { + + static class Parent { + public int first; + + public void foo() { + + } + } + + static class Child extends Parent { + public int second; + public static int third; + } + + @Test + public void allMethodsShouldReturnPublicMethodsDeclaredByParent() { + final Set actual = Reflection.allMethods(Child.class); + final Method expected = Reflection.publicMethod(Parent.class, "foo"); + assertTrue(actual.contains(expected)); + } + + @Test + public void publicFieldsReturnsFieldsDeclaredInParent() throws Exception { + final Set actual = Reflection.publicFields(Child.class); + final Field expected = Parent.class.getField("first"); + assertTrue(actual.contains(expected)); + } + + @Test + public void publicFieldsReturnsFieldsDeclaredInChild() throws Exception { + final Set actual = Reflection.publicFields(Child.class); + final Field expected = Child.class.getField("second"); + assertTrue(actual.contains(expected)); + } + + @Test + public void publicFieldsReturnsStaticFields() throws Exception { + final Set actual = Reflection.publicFields(Child.class); + final Field expected = Child.class.getField("third"); + assertTrue(actual.contains(expected)); + } +} diff --git a/pitest/src/test/java/org/pitest/sequence/MatchTest.java b/pitest/src/test/java/org/pitest/sequence/MatchTest.java index d92e2175c..82df5b263 100644 --- a/pitest/src/test/java/org/pitest/sequence/MatchTest.java +++ b/pitest/src/test/java/org/pitest/sequence/MatchTest.java @@ -1,60 +1,60 @@ -package org.pitest.sequence; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class MatchTest { - - private final Context unused = null; - - @Test - public void alwaysShouldAlwaysMatch() { - final Match testee = Match.always(); - assertTrue(testee.test(this.unused, 1)); - assertTrue(testee.test(this.unused, Integer.MAX_VALUE)); - } - - @Test - public void neverShouldNeverMatch() { - final Match testee = Match.never(); - assertFalse(testee.test(this.unused, 1)); - assertFalse(testee.test(this.unused, Integer.MAX_VALUE)); - } - - @Test - public void negateShouldInvertLogic() { - final Match testee = Match.never(); - assertTrue(testee.negate().test(this.unused, 1)); - assertFalse(testee.negate().negate().test(this.unused, Integer.MAX_VALUE)); - } - - @Test - public void isEqualShouldCheckEquality() { - final Match testee = Match.isEqual(1); - assertTrue(testee.test(this.unused, 1)); - assertFalse(testee.test(this.unused, 2)); - } - - @Test - public void andShouldLogicallyAnd() { - final Match isTrue = Match.always(); - final Match isFalse = Match.never(); - assertTrue(isTrue.and(isTrue).test(this.unused, 1)); - assertFalse(isTrue.and(isFalse).test(this.unused, 1)); - assertFalse(isFalse.and(isFalse).test(this.unused, 1)); - assertFalse(isFalse.and(isTrue).test(this.unused, 1)); - } - - @Test - public void orShouldLogicallyOr() { - final Match isTrue = Match.always(); - final Match isFalse = Match.never(); - assertTrue(isTrue.or(isTrue).test(this.unused, 1)); - assertTrue(isTrue.or(isFalse).test(this.unused, 1)); - assertFalse(isFalse.or(isFalse).test(this.unused, 1)); - assertTrue(isFalse.or(isTrue).test(this.unused, 1)); - } - -} +package org.pitest.sequence; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class MatchTest { + + private final Context unused = null; + + @Test + public void alwaysShouldAlwaysMatch() { + final Match testee = Match.always(); + assertTrue(testee.test(this.unused, 1)); + assertTrue(testee.test(this.unused, Integer.MAX_VALUE)); + } + + @Test + public void neverShouldNeverMatch() { + final Match testee = Match.never(); + assertFalse(testee.test(this.unused, 1)); + assertFalse(testee.test(this.unused, Integer.MAX_VALUE)); + } + + @Test + public void negateShouldInvertLogic() { + final Match testee = Match.never(); + assertTrue(testee.negate().test(this.unused, 1)); + assertFalse(testee.negate().negate().test(this.unused, Integer.MAX_VALUE)); + } + + @Test + public void isEqualShouldCheckEquality() { + final Match testee = Match.isEqual(1); + assertTrue(testee.test(this.unused, 1)); + assertFalse(testee.test(this.unused, 2)); + } + + @Test + public void andShouldLogicallyAnd() { + final Match isTrue = Match.always(); + final Match isFalse = Match.never(); + assertTrue(isTrue.and(isTrue).test(this.unused, 1)); + assertFalse(isTrue.and(isFalse).test(this.unused, 1)); + assertFalse(isFalse.and(isFalse).test(this.unused, 1)); + assertFalse(isFalse.and(isTrue).test(this.unused, 1)); + } + + @Test + public void orShouldLogicallyOr() { + final Match isTrue = Match.always(); + final Match isFalse = Match.never(); + assertTrue(isTrue.or(isTrue).test(this.unused, 1)); + assertTrue(isTrue.or(isFalse).test(this.unused, 1)); + assertFalse(isFalse.or(isFalse).test(this.unused, 1)); + assertTrue(isFalse.or(isTrue).test(this.unused, 1)); + } + +} diff --git a/pitest/src/test/java/org/pitest/sequence/SequenceQueryTest.java b/pitest/src/test/java/org/pitest/sequence/SequenceQueryTest.java index efa5c6cf0..76fbc534b 100644 --- a/pitest/src/test/java/org/pitest/sequence/SequenceQueryTest.java +++ b/pitest/src/test/java/org/pitest/sequence/SequenceQueryTest.java @@ -1,117 +1,117 @@ -package org.pitest.sequence; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; - -public class SequenceQueryTest { - - @Test - public void shouldMatchSingleLiterals() { - final SequenceMatcher testee = QueryStart - .match(eq(1)) - .compile(); - - assertTrue(testee.matches(asList(1))); - assertFalse(testee.matches( asList(2))); - } - - @Test - public void shouldMatchSimpleSequences() { - final SequenceMatcher testee = QueryStart - .match(eq(1)) - .then(eq(2)) - .then(eq(3)) - .compile(); - - assertTrue(testee.matches(asList(1, 2, 3))); - assertFalse(testee.matches(asList(1, 2))); - assertFalse(testee.matches(asList(1, 2, 3, 4))); - } - - @Test - public void shouldMatchSimpleOrs() { - final SequenceQuery right = QueryStart.match(eq(2)); - - final SequenceMatcher testee = QueryStart - .match(eq(1)) - .or(right) - .compile(); - - assertTrue(testee.matches(asList(1))); - assertTrue(testee.matches(asList(2))); - assertFalse(testee.matches(asList(3))); - } - - @Test - public void shouldMatchSimpleZeroOrMores() { - final SequenceQuery right = QueryStart.match(eq(2)); - - final SequenceMatcher testee = QueryStart - .match(eq(1)) - .zeroOrMore(right) - .compile(); - - assertTrue(testee.matches(asList(1))); - assertTrue(testee.matches(asList(1, 2))); - assertTrue(testee.matches(asList(1, 2, 2, 2))); - assertFalse(testee.matches(asList(1, 2, 3))); - assertFalse(testee.matches(asList(1, 3))); - } - - @Test - public void shouldMatchSimpleOneOrMores() { - final SequenceQuery right = QueryStart.match(eq(2)); - - final SequenceMatcher testee = QueryStart - .match(eq(1)) - .oneOrMore(right) - .compile(); - - assertFalse(testee.matches(asList(1))); - assertTrue(testee.matches(asList(1, 2))); - assertTrue(testee.matches(asList(1, 2, 2, 2))); - assertFalse(testee.matches(asList(1, 2, 3))); - assertFalse(testee.matches(asList(1, 3))); - } - - @Test - public void shouldMatchAnyOf() { - final SequenceQuery left = QueryStart.match(eq(2)); - - final SequenceQuery right = QueryStart.match(eq(3)); - - final SequenceMatcher testee = QueryStart.match(eq(1)) - .thenAnyOf(left, right) - .then(eq(99)) - .compile(); - - assertTrue(testee.matches(asList(1, 2, 99))); - assertTrue(testee.matches(asList(1, 3, 99))); - assertFalse(testee.matches(asList(1, 2))); - assertFalse(testee.matches(asList(1, 2, 3, 99))); - } - - @Test - public void shouldSkipItemsMatchingIgnoreList() { - final SequenceMatcher testee = QueryStart - .match(eq(1)) - .then(eq(2)) - .compile(QueryParams.params(Integer.class).withIgnores(eq(99))); - - assertTrue(testee.matches(asList(1, 99, 2))); - } - - private Match eq(final int i) { - return Match.isEqual(i); - } - - private static List asList(Integer... is) { - return Arrays.asList(is); - } - -} +package org.pitest.sequence; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class SequenceQueryTest { + + @Test + public void shouldMatchSingleLiterals() { + final SequenceMatcher testee = QueryStart + .match(eq(1)) + .compile(); + + assertTrue(testee.matches(asList(1))); + assertFalse(testee.matches( asList(2))); + } + + @Test + public void shouldMatchSimpleSequences() { + final SequenceMatcher testee = QueryStart + .match(eq(1)) + .then(eq(2)) + .then(eq(3)) + .compile(); + + assertTrue(testee.matches(asList(1, 2, 3))); + assertFalse(testee.matches(asList(1, 2))); + assertFalse(testee.matches(asList(1, 2, 3, 4))); + } + + @Test + public void shouldMatchSimpleOrs() { + final SequenceQuery right = QueryStart.match(eq(2)); + + final SequenceMatcher testee = QueryStart + .match(eq(1)) + .or(right) + .compile(); + + assertTrue(testee.matches(asList(1))); + assertTrue(testee.matches(asList(2))); + assertFalse(testee.matches(asList(3))); + } + + @Test + public void shouldMatchSimpleZeroOrMores() { + final SequenceQuery right = QueryStart.match(eq(2)); + + final SequenceMatcher testee = QueryStart + .match(eq(1)) + .zeroOrMore(right) + .compile(); + + assertTrue(testee.matches(asList(1))); + assertTrue(testee.matches(asList(1, 2))); + assertTrue(testee.matches(asList(1, 2, 2, 2))); + assertFalse(testee.matches(asList(1, 2, 3))); + assertFalse(testee.matches(asList(1, 3))); + } + + @Test + public void shouldMatchSimpleOneOrMores() { + final SequenceQuery right = QueryStart.match(eq(2)); + + final SequenceMatcher testee = QueryStart + .match(eq(1)) + .oneOrMore(right) + .compile(); + + assertFalse(testee.matches(asList(1))); + assertTrue(testee.matches(asList(1, 2))); + assertTrue(testee.matches(asList(1, 2, 2, 2))); + assertFalse(testee.matches(asList(1, 2, 3))); + assertFalse(testee.matches(asList(1, 3))); + } + + @Test + public void shouldMatchAnyOf() { + final SequenceQuery left = QueryStart.match(eq(2)); + + final SequenceQuery right = QueryStart.match(eq(3)); + + final SequenceMatcher testee = QueryStart.match(eq(1)) + .thenAnyOf(left, right) + .then(eq(99)) + .compile(); + + assertTrue(testee.matches(asList(1, 2, 99))); + assertTrue(testee.matches(asList(1, 3, 99))); + assertFalse(testee.matches(asList(1, 2))); + assertFalse(testee.matches(asList(1, 2, 3, 99))); + } + + @Test + public void shouldSkipItemsMatchingIgnoreList() { + final SequenceMatcher testee = QueryStart + .match(eq(1)) + .then(eq(2)) + .compile(QueryParams.params(Integer.class).withIgnores(eq(99))); + + assertTrue(testee.matches(asList(1, 99, 2))); + } + + private Match eq(final int i) { + return Match.isEqual(i); + } + + private static List asList(Integer... is) { + return Arrays.asList(is); + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/BasicTestUnitFinder.java b/pitest/src/test/java/org/pitest/simpletest/BasicTestUnitFinder.java index 093b55fd9..59c9d22c7 100644 --- a/pitest/src/test/java/org/pitest/simpletest/BasicTestUnitFinder.java +++ b/pitest/src/test/java/org/pitest/simpletest/BasicTestUnitFinder.java @@ -1,124 +1,124 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.simpletest; - -import static org.pitest.util.Unchecked.translateCheckedException; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Predicate; - -import org.pitest.functional.FCollection; -import org.pitest.reflection.Reflection; -import org.pitest.simpletest.steps.CallStep; -import org.pitest.testapi.Description; -import org.pitest.testapi.TestUnit; -import org.pitest.testapi.TestUnitFinder; -import org.pitest.util.PitError; - -public class BasicTestUnitFinder implements TestUnitFinder { - - private final Set instantiationStrategies = new LinkedHashSet<>(); - private final MethodFinder testMethodFinder; - - public BasicTestUnitFinder( - final Collection instantiationStrategies, - final MethodFinder testMethodFinder) { - this.instantiationStrategies.addAll(instantiationStrategies); - this.testMethodFinder = testMethodFinder; - } - - @Override - public List findTestUnits(final Class testClass) { - try { - - final List units = new ArrayList<>(); - final InstantiationStrategy instantiationStrategy = findInstantiationStrategy(testClass); - final List instantiations = instantiationStrategy - .instantiations(testClass); - for (int instantiation = 0; instantiation != instantiations.size(); instantiation++) { - for (final TestMethod m : findTestMethods(testClass)) { - final TestStep step = instantiations.get(instantiation); - units - .add(createTestUnitForInstantiation(step, - getNamePrefix(instantiations.size(), instantiation), - testClass, m)); - } - } - - return units; - - } catch (final Exception ex) { - throw translateCheckedException(ex); - } - } - - private String getNamePrefix(final int size, final int i) { - if (size == 1) { - return ""; - } else { - return "[" + i + "] "; - } - } - - private TestUnit createTestUnitForInstantiation( - final TestStep instantiationStep, final String namePrefix, - final Class testClass, final TestMethod testMethod) { - - final List steps = new ArrayList<>(); - - steps.add(instantiationStep); - steps.add(new CallStep(testMethod)); - - final TestUnit unit = new SteppedTestUnit(new Description(namePrefix - + testMethod.getName(), testClass), steps, testMethod.getExpected()); - return unit; - - } - - private InstantiationStrategy findInstantiationStrategy(final Class clazz) { - final List strategies = FCollection.filter( - this.instantiationStrategies, canInstantiate(clazz)); - if (strategies.isEmpty()) { - throw new PitError("Cannot instantiate " + clazz); - } else { - return strategies.get(0); - } - } - - private Predicate canInstantiate(final Class clazz) { - return a -> a.canInstantiate(clazz); - } - - private Collection findTestMethods(final Class clazz) { - - final EqualitySet set = new EqualitySet<>( - new SignatureEqualityStrategy()); - final Consumer> addToSet = a -> a.ifPresent(m -> set.add(m)); - final Collection methods = Reflection.allMethods(clazz); - methods.stream().map(this.testMethodFinder).forEach(addToSet); - - - return set.toCollection(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.simpletest; + +import static org.pitest.util.Unchecked.translateCheckedException; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Predicate; + +import org.pitest.functional.FCollection; +import org.pitest.reflection.Reflection; +import org.pitest.simpletest.steps.CallStep; +import org.pitest.testapi.Description; +import org.pitest.testapi.TestUnit; +import org.pitest.testapi.TestUnitFinder; +import org.pitest.util.PitError; + +public class BasicTestUnitFinder implements TestUnitFinder { + + private final Set instantiationStrategies = new LinkedHashSet<>(); + private final MethodFinder testMethodFinder; + + public BasicTestUnitFinder( + final Collection instantiationStrategies, + final MethodFinder testMethodFinder) { + this.instantiationStrategies.addAll(instantiationStrategies); + this.testMethodFinder = testMethodFinder; + } + + @Override + public List findTestUnits(final Class testClass) { + try { + + final List units = new ArrayList<>(); + final InstantiationStrategy instantiationStrategy = findInstantiationStrategy(testClass); + final List instantiations = instantiationStrategy + .instantiations(testClass); + for (int instantiation = 0; instantiation != instantiations.size(); instantiation++) { + for (final TestMethod m : findTestMethods(testClass)) { + final TestStep step = instantiations.get(instantiation); + units + .add(createTestUnitForInstantiation(step, + getNamePrefix(instantiations.size(), instantiation), + testClass, m)); + } + } + + return units; + + } catch (final Exception ex) { + throw translateCheckedException(ex); + } + } + + private String getNamePrefix(final int size, final int i) { + if (size == 1) { + return ""; + } else { + return "[" + i + "] "; + } + } + + private TestUnit createTestUnitForInstantiation( + final TestStep instantiationStep, final String namePrefix, + final Class testClass, final TestMethod testMethod) { + + final List steps = new ArrayList<>(); + + steps.add(instantiationStep); + steps.add(new CallStep(testMethod)); + + final TestUnit unit = new SteppedTestUnit(new Description(namePrefix + + testMethod.getName(), testClass), steps, testMethod.getExpected()); + return unit; + + } + + private InstantiationStrategy findInstantiationStrategy(final Class clazz) { + final List strategies = FCollection.filter( + this.instantiationStrategies, canInstantiate(clazz)); + if (strategies.isEmpty()) { + throw new PitError("Cannot instantiate " + clazz); + } else { + return strategies.get(0); + } + } + + private Predicate canInstantiate(final Class clazz) { + return a -> a.canInstantiate(clazz); + } + + private Collection findTestMethods(final Class clazz) { + + final EqualitySet set = new EqualitySet<>( + new SignatureEqualityStrategy()); + final Consumer> addToSet = a -> a.ifPresent(m -> set.add(m)); + final Collection methods = Reflection.allMethods(clazz); + methods.stream().map(this.testMethodFinder).forEach(addToSet); + + + return set.toCollection(); + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/CanNotCreateTestClassException.java b/pitest/src/test/java/org/pitest/simpletest/CanNotCreateTestClassException.java index decb9eec8..c29cd337c 100644 --- a/pitest/src/test/java/org/pitest/simpletest/CanNotCreateTestClassException.java +++ b/pitest/src/test/java/org/pitest/simpletest/CanNotCreateTestClassException.java @@ -1,29 +1,29 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -/** - * @author henry - * - */ -public class CanNotCreateTestClassException extends RuntimeException { - - public CanNotCreateTestClassException(final String message, final Throwable t) { - super(message, t); - } - - private static final long serialVersionUID = 1L; - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +/** + * @author henry + * + */ +public class CanNotCreateTestClassException extends RuntimeException { + + public CanNotCreateTestClassException(final String message, final Throwable t) { + super(message, t); + } + + private static final long serialVersionUID = 1L; + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/ConfigurationForTesting.java b/pitest/src/test/java/org/pitest/simpletest/ConfigurationForTesting.java index 8e2f266b8..055f17716 100644 --- a/pitest/src/test/java/org/pitest/simpletest/ConfigurationForTesting.java +++ b/pitest/src/test/java/org/pitest/simpletest/ConfigurationForTesting.java @@ -1,59 +1,59 @@ -package org.pitest.simpletest; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -import org.pitest.extension.common.NoTestSuiteFinder; -import org.pitest.help.PitHelpError; -import org.pitest.junit.CompoundTestUnitFinder; -import org.pitest.testapi.Configuration; -import org.pitest.testapi.TestSuiteFinder; -import org.pitest.testapi.TestUnitFinder; - -public class ConfigurationForTesting implements Configuration { - - private static class TestFinder implements MethodFinder { - - @Override - public Optional apply(final Method method) { - final TestAnnotationForTesting annotation = method - .getAnnotation(TestAnnotationForTesting.class); - - if (annotation != null) { - final Class expected = !annotation.expected() - .getName().equals(TestAnnotationForTesting.NONE.class.getName()) ? annotation - .expected() : null; - return Optional.ofNullable(new TestMethod(method, expected)); - } else { - return Optional.empty(); - } - } - - } - - @Override - public TestUnitFinder testUnitFinder() { - final List instantiationStrategies = - - Arrays - . asList(new NoArgsConstructorInstantiationStrategy()); - - return new CompoundTestUnitFinder( - Collections. singletonList(new BasicTestUnitFinder( - instantiationStrategies, new TestFinder()))); - } - - @Override - public TestSuiteFinder testSuiteFinder() { - return new NoTestSuiteFinder(); - } - - @Override - public Optional verifyEnvironment() { - return Optional.empty(); - } - -} +package org.pitest.simpletest; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.pitest.extension.common.NoTestSuiteFinder; +import org.pitest.help.PitHelpError; +import org.pitest.junit.CompoundTestUnitFinder; +import org.pitest.testapi.Configuration; +import org.pitest.testapi.TestSuiteFinder; +import org.pitest.testapi.TestUnitFinder; + +public class ConfigurationForTesting implements Configuration { + + private static class TestFinder implements MethodFinder { + + @Override + public Optional apply(final Method method) { + final TestAnnotationForTesting annotation = method + .getAnnotation(TestAnnotationForTesting.class); + + if (annotation != null) { + final Class expected = !annotation.expected() + .getName().equals(TestAnnotationForTesting.NONE.class.getName()) ? annotation + .expected() : null; + return Optional.ofNullable(new TestMethod(method, expected)); + } else { + return Optional.empty(); + } + } + + } + + @Override + public TestUnitFinder testUnitFinder() { + final List instantiationStrategies = + + Arrays + . asList(new NoArgsConstructorInstantiationStrategy()); + + return new CompoundTestUnitFinder( + Collections. singletonList(new BasicTestUnitFinder( + instantiationStrategies, new TestFinder()))); + } + + @Override + public TestSuiteFinder testSuiteFinder() { + return new NoTestSuiteFinder(); + } + + @Override + public Optional verifyEnvironment() { + return Optional.empty(); + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/EqualitySet.java b/pitest/src/test/java/org/pitest/simpletest/EqualitySet.java index 6eed05d4d..44e9e7d6d 100644 --- a/pitest/src/test/java/org/pitest/simpletest/EqualitySet.java +++ b/pitest/src/test/java/org/pitest/simpletest/EqualitySet.java @@ -1,72 +1,72 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -/** - * @author henry - * - */ -public class EqualitySet implements Iterable { - - private final List members = new ArrayList<>(); - private final EqualityStrategy equality; - - public EqualitySet(final EqualityStrategy equality) { - this.equality = equality; - } - - public boolean add(final T arg0) { - if (!contains(arg0)) { - return this.members.add(arg0); - } - return false; - } - - public boolean addAll(final Collection arg0) { - boolean isAdded = false; - for (final T each : arg0) { - isAdded |= add(each); - } - return isAdded; - } - - public boolean contains(final T arg0) { - for (final T each : this.members) { - if (this.equality.isEqual(arg0, each)) { - return true; - } - } - return false; - } - - public boolean isEmpty() { - return this.members.isEmpty(); - } - - @Override - public Iterator iterator() { - return this.members.iterator(); - } - - public Collection toCollection() { - return this.members; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +/** + * @author henry + * + */ +public class EqualitySet implements Iterable { + + private final List members = new ArrayList<>(); + private final EqualityStrategy equality; + + public EqualitySet(final EqualityStrategy equality) { + this.equality = equality; + } + + public boolean add(final T arg0) { + if (!contains(arg0)) { + return this.members.add(arg0); + } + return false; + } + + public boolean addAll(final Collection arg0) { + boolean isAdded = false; + for (final T each : arg0) { + isAdded |= add(each); + } + return isAdded; + } + + public boolean contains(final T arg0) { + for (final T each : this.members) { + if (this.equality.isEqual(arg0, each)) { + return true; + } + } + return false; + } + + public boolean isEmpty() { + return this.members.isEmpty(); + } + + @Override + public Iterator iterator() { + return this.members.iterator(); + } + + public Collection toCollection() { + return this.members; + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/EqualitySetTest.java b/pitest/src/test/java/org/pitest/simpletest/EqualitySetTest.java index d28f18e85..afcb91f50 100644 --- a/pitest/src/test/java/org/pitest/simpletest/EqualitySetTest.java +++ b/pitest/src/test/java/org/pitest/simpletest/EqualitySetTest.java @@ -1,85 +1,85 @@ -package org.pitest.simpletest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -public class EqualitySetTest { - - EqualitySet testee; - - @Before - public void createTestee() { - final EqualityStrategy e = (lhs, rhs) -> lhs.equals(rhs); - this.testee = new EqualitySet<>(e); - } - - @Test - public void shouldIterateOverMembers() { - this.testee.add("one"); - this.testee.add("two"); - final List expected = Arrays.asList("one", "two"); - final List actual = new ArrayList<>(); - for (final String each : this.testee) { - actual.add(each); - } - assertEquals(expected, actual); - } - - @Test - public void containsShouldReturnTrueWhenMemberPresent() { - this.testee.add("one"); - assertTrue(this.testee.contains("one")); - } - - @Test - public void containsShouldReturnFalseWhenMemberNotPresent() { - this.testee.add("one"); - assertFalse(this.testee.contains("two")); - } - - @Test - public void toCollectionShouldReturnAllMembers() { - this.testee.add("one"); - this.testee.add("two"); - final List expected = Arrays.asList("one", "two"); - assertEquals(expected, this.testee.toCollection()); - } - - @Test - public void shouldOnlyAddOneInstanceOfEachValue() { - this.testee.add("one"); - this.testee.add("two"); - this.testee.add("one"); - this.testee.add("two"); - final List expected = Arrays.asList("one", "two"); - assertEquals(expected, this.testee.toCollection()); - } - - @Test - public void shouldOnlyAddOneInstanceOfEachValueViaAddAll() { - final List expected = Arrays.asList("one", "two"); - this.testee.addAll(expected); - this.testee.addAll(expected); - assertEquals(expected, this.testee.toCollection()); - } - - @Test - public void isEmptyShouldReturnTrueWhenEmpty() { - assertTrue(this.testee.isEmpty()); - } - - @Test - public void isEmptyShouldReturnFalseWhenNotEmpty() { - this.testee.add("foo"); - assertFalse(this.testee.isEmpty()); - } - -} +package org.pitest.simpletest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class EqualitySetTest { + + EqualitySet testee; + + @Before + public void createTestee() { + final EqualityStrategy e = (lhs, rhs) -> lhs.equals(rhs); + this.testee = new EqualitySet<>(e); + } + + @Test + public void shouldIterateOverMembers() { + this.testee.add("one"); + this.testee.add("two"); + final List expected = Arrays.asList("one", "two"); + final List actual = new ArrayList<>(); + for (final String each : this.testee) { + actual.add(each); + } + assertEquals(expected, actual); + } + + @Test + public void containsShouldReturnTrueWhenMemberPresent() { + this.testee.add("one"); + assertTrue(this.testee.contains("one")); + } + + @Test + public void containsShouldReturnFalseWhenMemberNotPresent() { + this.testee.add("one"); + assertFalse(this.testee.contains("two")); + } + + @Test + public void toCollectionShouldReturnAllMembers() { + this.testee.add("one"); + this.testee.add("two"); + final List expected = Arrays.asList("one", "two"); + assertEquals(expected, this.testee.toCollection()); + } + + @Test + public void shouldOnlyAddOneInstanceOfEachValue() { + this.testee.add("one"); + this.testee.add("two"); + this.testee.add("one"); + this.testee.add("two"); + final List expected = Arrays.asList("one", "two"); + assertEquals(expected, this.testee.toCollection()); + } + + @Test + public void shouldOnlyAddOneInstanceOfEachValueViaAddAll() { + final List expected = Arrays.asList("one", "two"); + this.testee.addAll(expected); + this.testee.addAll(expected); + assertEquals(expected, this.testee.toCollection()); + } + + @Test + public void isEmptyShouldReturnTrueWhenEmpty() { + assertTrue(this.testee.isEmpty()); + } + + @Test + public void isEmptyShouldReturnFalseWhenNotEmpty() { + this.testee.add("foo"); + assertFalse(this.testee.isEmpty()); + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/EqualityStrategy.java b/pitest/src/test/java/org/pitest/simpletest/EqualityStrategy.java index ffc9020a8..df8dcdb53 100644 --- a/pitest/src/test/java/org/pitest/simpletest/EqualityStrategy.java +++ b/pitest/src/test/java/org/pitest/simpletest/EqualityStrategy.java @@ -1,21 +1,21 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -public interface EqualityStrategy { - - public boolean isEqual(T lhs, T rhs); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +public interface EqualityStrategy { + + public boolean isEqual(T lhs, T rhs); + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/ExcludedPrefixIsolationStrategy.java b/pitest/src/test/java/org/pitest/simpletest/ExcludedPrefixIsolationStrategy.java index a5c4a4409..d00c2965c 100644 --- a/pitest/src/test/java/org/pitest/simpletest/ExcludedPrefixIsolationStrategy.java +++ b/pitest/src/test/java/org/pitest/simpletest/ExcludedPrefixIsolationStrategy.java @@ -1,45 +1,45 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.Set; - -public class ExcludedPrefixIsolationStrategy implements IsolationStrategy { - - private final Set excludedPackagePrefixes = new LinkedHashSet<>(); - - public ExcludedPrefixIsolationStrategy(final String... prefixes) { - this(Arrays.asList(prefixes)); - } - - public ExcludedPrefixIsolationStrategy( - final Collection excludedPackagePrefixes) { - this.excludedPackagePrefixes.addAll(excludedPackagePrefixes); - } - - @Override - public boolean shouldIsolate(final String name) { - for (final String s : this.excludedPackagePrefixes) { - if (name.startsWith(s)) { - return false; - } - } - return true; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.Set; + +public class ExcludedPrefixIsolationStrategy implements IsolationStrategy { + + private final Set excludedPackagePrefixes = new LinkedHashSet<>(); + + public ExcludedPrefixIsolationStrategy(final String... prefixes) { + this(Arrays.asList(prefixes)); + } + + public ExcludedPrefixIsolationStrategy( + final Collection excludedPackagePrefixes) { + this.excludedPackagePrefixes.addAll(excludedPackagePrefixes); + } + + @Override + public boolean shouldIsolate(final String name) { + for (final String s : this.excludedPackagePrefixes) { + if (name.startsWith(s)) { + return false; + } + } + return true; + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/InstantiationStrategy.java b/pitest/src/test/java/org/pitest/simpletest/InstantiationStrategy.java index bdd47c45e..b6d5bf19b 100644 --- a/pitest/src/test/java/org/pitest/simpletest/InstantiationStrategy.java +++ b/pitest/src/test/java/org/pitest/simpletest/InstantiationStrategy.java @@ -1,26 +1,26 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.simpletest; - -import java.util.List; - -public interface InstantiationStrategy { - - public boolean canInstantiate(Class clazz); - - public List instantiations(Class clazz); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.simpletest; + +import java.util.List; + +public interface InstantiationStrategy { + + public boolean canInstantiate(Class clazz); + + public List instantiations(Class clazz); + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/IsolationStrategy.java b/pitest/src/test/java/org/pitest/simpletest/IsolationStrategy.java index fce4b970b..17a22efa7 100644 --- a/pitest/src/test/java/org/pitest/simpletest/IsolationStrategy.java +++ b/pitest/src/test/java/org/pitest/simpletest/IsolationStrategy.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -/** - * @author henry - * - */ -public interface IsolationStrategy { - - public boolean shouldIsolate(String name); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +/** + * @author henry + * + */ +public interface IsolationStrategy { + + public boolean shouldIsolate(String name); + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/MethodFinder.java b/pitest/src/test/java/org/pitest/simpletest/MethodFinder.java index 8094ab84d..7f103d463 100644 --- a/pitest/src/test/java/org/pitest/simpletest/MethodFinder.java +++ b/pitest/src/test/java/org/pitest/simpletest/MethodFinder.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.simpletest; - -import java.lang.reflect.Method; -import java.util.function.Function; - -import java.util.Optional; - -public interface MethodFinder extends Function> { - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.simpletest; + +import java.lang.reflect.Method; +import java.util.function.Function; + +import java.util.Optional; + +public interface MethodFinder extends Function> { + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/NoArgsConstructorInstantiationStrategy.java b/pitest/src/test/java/org/pitest/simpletest/NoArgsConstructorInstantiationStrategy.java index 28010a273..21f54f2f7 100644 --- a/pitest/src/test/java/org/pitest/simpletest/NoArgsConstructorInstantiationStrategy.java +++ b/pitest/src/test/java/org/pitest/simpletest/NoArgsConstructorInstantiationStrategy.java @@ -1,38 +1,38 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -import java.util.Collections; -import java.util.List; - -import org.pitest.simpletest.steps.NoArgsInstantiateStep; - -public class NoArgsConstructorInstantiationStrategy implements -InstantiationStrategy { - - @Override - public List instantiations(final Class clazz) { - return Collections. singletonList(NoArgsInstantiateStep - .instantiate(clazz)); - } - - @Override - public boolean canInstantiate(final Class clazz) { - // unwise premature optimization - // don't check if a no-args constructor is present - return true; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +import java.util.Collections; +import java.util.List; + +import org.pitest.simpletest.steps.NoArgsInstantiateStep; + +public class NoArgsConstructorInstantiationStrategy implements +InstantiationStrategy { + + @Override + public List instantiations(final Class clazz) { + return Collections. singletonList(NoArgsInstantiateStep + .instantiate(clazz)); + } + + @Override + public boolean canInstantiate(final Class clazz) { + // unwise premature optimization + // don't check if a no-args constructor is present + return true; + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/NoArgsConstructorInstantiationStrategyTest.java b/pitest/src/test/java/org/pitest/simpletest/NoArgsConstructorInstantiationStrategyTest.java index 4879aafe1..1a21306b0 100644 --- a/pitest/src/test/java/org/pitest/simpletest/NoArgsConstructorInstantiationStrategyTest.java +++ b/pitest/src/test/java/org/pitest/simpletest/NoArgsConstructorInstantiationStrategyTest.java @@ -1,54 +1,54 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.simpletest.steps.NoArgsInstantiateStep; - -public class NoArgsConstructorInstantiationStrategyTest { - - private NoArgsConstructorInstantiationStrategy testee; - - @Before - public void setUp() { - this.testee = new NoArgsConstructorInstantiationStrategy(); - } - - @Test - public void shouldAllwaysReturnsTrue() { - assertTrue(this.testee - .canInstantiate(NoArgsConstructorInstantiationStrategyTest.class)); - assertTrue(this.testee.canInstantiate(null)); - } - - @Test - public void shouldCreateSingleInstantiateTestStep() { - final List expected = new ArrayList<>(); - expected.add(NoArgsInstantiateStep - .instantiate(NoArgsConstructorInstantiationStrategyTest.class)); - assertEquals(expected, - this.testee - .instantiations(NoArgsConstructorInstantiationStrategyTest.class)); - - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.simpletest.steps.NoArgsInstantiateStep; + +public class NoArgsConstructorInstantiationStrategyTest { + + private NoArgsConstructorInstantiationStrategy testee; + + @Before + public void setUp() { + this.testee = new NoArgsConstructorInstantiationStrategy(); + } + + @Test + public void shouldAllwaysReturnsTrue() { + assertTrue(this.testee + .canInstantiate(NoArgsConstructorInstantiationStrategyTest.class)); + assertTrue(this.testee.canInstantiate(null)); + } + + @Test + public void shouldCreateSingleInstantiateTestStep() { + final List expected = new ArrayList<>(); + expected.add(NoArgsInstantiateStep + .instantiate(NoArgsConstructorInstantiationStrategyTest.class)); + assertEquals(expected, + this.testee + .instantiations(NoArgsConstructorInstantiationStrategyTest.class)); + + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/SignatureEqualityStrategy.java b/pitest/src/test/java/org/pitest/simpletest/SignatureEqualityStrategy.java index 96e9863b6..cc8c0d5b3 100644 --- a/pitest/src/test/java/org/pitest/simpletest/SignatureEqualityStrategy.java +++ b/pitest/src/test/java/org/pitest/simpletest/SignatureEqualityStrategy.java @@ -1,52 +1,52 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.simpletest; - -import java.lang.reflect.Method; - -public class SignatureEqualityStrategy implements EqualityStrategy { - - @Override - public boolean isEqual(final TestMethod lhs, final TestMethod rhs) { - final Method m1 = lhs.getMethod(); - final Method m2 = rhs.getMethod(); - - return haveSameSignature(m1, m2); - } - - private boolean haveSameSignature(final Method me, final Method other) { - - if ((me.getName().equals(other.getName()))) { - if (!me.getReturnType().equals(other.getReturnType())) { - return false; - } - - final Class[] params1 = me.getParameterTypes(); - final Class[] params2 = other.getParameterTypes(); - if (params1.length == params2.length) { - for (int i = 0; i < params1.length; i++) { - if (params1[i] != params2[i]) { - return false; - } - } - return true; - } - } - - return false; - } - +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.simpletest; + +import java.lang.reflect.Method; + +public class SignatureEqualityStrategy implements EqualityStrategy { + + @Override + public boolean isEqual(final TestMethod lhs, final TestMethod rhs) { + final Method m1 = lhs.getMethod(); + final Method m2 = rhs.getMethod(); + + return haveSameSignature(m1, m2); + } + + private boolean haveSameSignature(final Method me, final Method other) { + + if ((me.getName().equals(other.getName()))) { + if (!me.getReturnType().equals(other.getReturnType())) { + return false; + } + + final Class[] params1 = me.getParameterTypes(); + final Class[] params2 = other.getParameterTypes(); + if (params1.length == params2.length) { + for (int i = 0; i < params1.length; i++) { + if (params1[i] != params2[i]) { + return false; + } + } + return true; + } + } + + return false; + } + }; \ No newline at end of file diff --git a/pitest/src/test/java/org/pitest/simpletest/SignatureEqualityStrategyTest.java b/pitest/src/test/java/org/pitest/simpletest/SignatureEqualityStrategyTest.java index aade80b43..f5660060b 100644 --- a/pitest/src/test/java/org/pitest/simpletest/SignatureEqualityStrategyTest.java +++ b/pitest/src/test/java/org/pitest/simpletest/SignatureEqualityStrategyTest.java @@ -1,65 +1,65 @@ -package org.pitest.simpletest; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Method; -import java.util.function.Predicate; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.reflection.Reflection; - -public class SignatureEqualityStrategyTest { - - SignatureEqualityStrategy testee; - - @Before - public void createTestee() { - this.testee = new SignatureEqualityStrategy(); - } - - @Test - public void shouldConsiderDifferentlyNamedMethodsNotEqual() { - assertFalse(this.testee.isEqual(createTestMethod("foo"), - createTestMethod("bar"))); - } - - @Test - public void shouldConsiderSameMethodEqual() { - assertTrue(this.testee.isEqual(createTestMethod("foo"), - createTestMethod("foo"))); - } - - @Test - public void shouldConsiderMethodsWithSameNameButDifferentSignaturesNotEqual() { - final Predicate noargs = a -> a.getName().equals("foo") && (a.getParameterTypes().length == 0); - - final Predicate onearg = a -> a.getName().equals("foo") && (a.getParameterTypes().length == 1); - - assertFalse(this.testee.isEqual(createTestMethod(noargs), - createTestMethod(onearg))); - } - - public void foo(final int i) { - - } - - public void foo() { - - } - - public void bar() { - - } - - private TestMethod createTestMethod(final Predicate p) { - return new TestMethod(Reflection.publicMethod(this.getClass(), p)); - } - - private TestMethod createTestMethod(final String name) { - final Predicate p = a -> a.getName().equals(name); - return createTestMethod(p); - } - -} +package org.pitest.simpletest; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.reflection.Reflection; + +public class SignatureEqualityStrategyTest { + + SignatureEqualityStrategy testee; + + @Before + public void createTestee() { + this.testee = new SignatureEqualityStrategy(); + } + + @Test + public void shouldConsiderDifferentlyNamedMethodsNotEqual() { + assertFalse(this.testee.isEqual(createTestMethod("foo"), + createTestMethod("bar"))); + } + + @Test + public void shouldConsiderSameMethodEqual() { + assertTrue(this.testee.isEqual(createTestMethod("foo"), + createTestMethod("foo"))); + } + + @Test + public void shouldConsiderMethodsWithSameNameButDifferentSignaturesNotEqual() { + final Predicate noargs = a -> a.getName().equals("foo") && (a.getParameterTypes().length == 0); + + final Predicate onearg = a -> a.getName().equals("foo") && (a.getParameterTypes().length == 1); + + assertFalse(this.testee.isEqual(createTestMethod(noargs), + createTestMethod(onearg))); + } + + public void foo(final int i) { + + } + + public void foo() { + + } + + public void bar() { + + } + + private TestMethod createTestMethod(final Predicate p) { + return new TestMethod(Reflection.publicMethod(this.getClass(), p)); + } + + private TestMethod createTestMethod(final String name) { + final Predicate p = a -> a.getName().equals(name); + return createTestMethod(p); + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/SimpleTestPlugin.java b/pitest/src/test/java/org/pitest/simpletest/SimpleTestPlugin.java index f90b9989f..c6d46f0a3 100644 --- a/pitest/src/test/java/org/pitest/simpletest/SimpleTestPlugin.java +++ b/pitest/src/test/java/org/pitest/simpletest/SimpleTestPlugin.java @@ -1,30 +1,30 @@ -package org.pitest.simpletest; - -import java.util.Collection; - -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.testapi.Configuration; -import org.pitest.testapi.TestGroupConfig; -import org.pitest.testapi.TestPluginFactory; - -public class SimpleTestPlugin implements TestPluginFactory { - - public static final String NAME = "fortestingonly"; - - @Override - public String description() { - return "Simple plugin for testing"; - } - - @Override - public Configuration createTestFrameworkConfiguration(TestGroupConfig config, - ClassByteArraySource source, Collection excludedRunners, Collection includedMethods) { - return new ConfigurationForTesting(); - } - - @Override - public String name() { - return NAME; - } - -} +package org.pitest.simpletest; + +import java.util.Collection; + +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.testapi.Configuration; +import org.pitest.testapi.TestGroupConfig; +import org.pitest.testapi.TestPluginFactory; + +public class SimpleTestPlugin implements TestPluginFactory { + + public static final String NAME = "fortestingonly"; + + @Override + public String description() { + return "Simple plugin for testing"; + } + + @Override + public Configuration createTestFrameworkConfiguration(TestGroupConfig config, + ClassByteArraySource source, Collection excludedRunners, Collection includedMethods) { + return new ConfigurationForTesting(); + } + + @Override + public String name() { + return NAME; + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/SteppedTestUnit.java b/pitest/src/test/java/org/pitest/simpletest/SteppedTestUnit.java index 5ccb999f5..cb4db789a 100644 --- a/pitest/src/test/java/org/pitest/simpletest/SteppedTestUnit.java +++ b/pitest/src/test/java/org/pitest/simpletest/SteppedTestUnit.java @@ -1,133 +1,133 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -import java.util.Collection; - -import java.util.Optional; -import org.pitest.testapi.AbstractTestUnit; -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; - -/** - * @author henry - * - */ -public class SteppedTestUnit extends AbstractTestUnit { - - private final Collection steps; - private final Optional> expected; - - public SteppedTestUnit(final Description description, - final Collection steps, - final Optional> expected) { - super(description); - this.steps = steps; - this.expected = expected; - } - - @Override - public void execute(final ResultCollector rc) { - if (!this.steps().isEmpty()) { - executeStepsAndReport(rc); - } else { - rc.notifySkipped(this.getDescription()); - } - - } - - private void executeStepsAndReport(final ResultCollector rc) { - rc.notifyStart(this.getDescription()); - Object o = null; - Throwable tResult = null; - try { - for (final TestStep s : this.steps) { - o = s.execute(getDescription(), o); - } - } catch (final TestExecutionException tee) { - tResult = tee.getCause(); - } catch (final Throwable t) { - tResult = t; - } - - tResult = updateResultForExpectations(tResult); - - rc.notifyEnd(this.getDescription(), tResult); - } - - private Throwable updateResultForExpectations(final Throwable tResult) { - if (this.expected.isPresent()) { - if (tResult == null) { - return new java.lang.AssertionError("Expected exception " - + this.expected); - } else if (this.expected.get().isAssignableFrom(tResult.getClass())) { - return null; - } - } - - return tResult; - } - - private Collection steps() { - return this.steps; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = (prime * result) - + ((this.expected == null) ? 0 : this.expected.hashCode()); - result = (prime * result) - + ((this.steps == null) ? 0 : this.steps.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final SteppedTestUnit other = (SteppedTestUnit) obj; - if (this.expected == null) { - if (other.expected != null) { - return false; - } - } else if (!this.expected.equals(other.expected)) { - return false; - } - if (this.steps == null) { - if (other.steps != null) { - return false; - } - } else if (!this.steps.equals(other.steps)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "SteppedTestUnit [steps=" + this.steps + ", expected=" - + this.expected + ", getDescription()=" + getDescription() + "]"; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +import java.util.Collection; + +import java.util.Optional; +import org.pitest.testapi.AbstractTestUnit; +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; + +/** + * @author henry + * + */ +public class SteppedTestUnit extends AbstractTestUnit { + + private final Collection steps; + private final Optional> expected; + + public SteppedTestUnit(final Description description, + final Collection steps, + final Optional> expected) { + super(description); + this.steps = steps; + this.expected = expected; + } + + @Override + public void execute(final ResultCollector rc) { + if (!this.steps().isEmpty()) { + executeStepsAndReport(rc); + } else { + rc.notifySkipped(this.getDescription()); + } + + } + + private void executeStepsAndReport(final ResultCollector rc) { + rc.notifyStart(this.getDescription()); + Object o = null; + Throwable tResult = null; + try { + for (final TestStep s : this.steps) { + o = s.execute(getDescription(), o); + } + } catch (final TestExecutionException tee) { + tResult = tee.getCause(); + } catch (final Throwable t) { + tResult = t; + } + + tResult = updateResultForExpectations(tResult); + + rc.notifyEnd(this.getDescription(), tResult); + } + + private Throwable updateResultForExpectations(final Throwable tResult) { + if (this.expected.isPresent()) { + if (tResult == null) { + return new java.lang.AssertionError("Expected exception " + + this.expected); + } else if (this.expected.get().isAssignableFrom(tResult.getClass())) { + return null; + } + } + + return tResult; + } + + private Collection steps() { + return this.steps; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = (prime * result) + + ((this.expected == null) ? 0 : this.expected.hashCode()); + result = (prime * result) + + ((this.steps == null) ? 0 : this.steps.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final SteppedTestUnit other = (SteppedTestUnit) obj; + if (this.expected == null) { + if (other.expected != null) { + return false; + } + } else if (!this.expected.equals(other.expected)) { + return false; + } + if (this.steps == null) { + if (other.steps != null) { + return false; + } + } else if (!this.steps.equals(other.steps)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "SteppedTestUnit [steps=" + this.steps + ", expected=" + + this.expected + ", getDescription()=" + getDescription() + "]"; + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/TestAnnotationForTesting.java b/pitest/src/test/java/org/pitest/simpletest/TestAnnotationForTesting.java index 6d410712e..148fdb7b3 100644 --- a/pitest/src/test/java/org/pitest/simpletest/TestAnnotationForTesting.java +++ b/pitest/src/test/java/org/pitest/simpletest/TestAnnotationForTesting.java @@ -1,18 +1,18 @@ -package org.pitest.simpletest; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(RetentionPolicy.RUNTIME) -public @interface TestAnnotationForTesting { - - public class NONE extends Throwable { - private NONE() { - } - - private static final long serialVersionUID = 1L; - } - - Class expected() default NONE.class; - -} +package org.pitest.simpletest; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface TestAnnotationForTesting { + + public class NONE extends Throwable { + private NONE() { + } + + private static final long serialVersionUID = 1L; + } + + Class expected() default NONE.class; + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/TestExecutionException.java b/pitest/src/test/java/org/pitest/simpletest/TestExecutionException.java index 24bfdf751..bf57f812f 100644 --- a/pitest/src/test/java/org/pitest/simpletest/TestExecutionException.java +++ b/pitest/src/test/java/org/pitest/simpletest/TestExecutionException.java @@ -1,26 +1,26 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.simpletest; - -public class TestExecutionException extends RuntimeException { - - public TestExecutionException(final Throwable t) { - super(t); - } - - private static final long serialVersionUID = 1L; - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.simpletest; + +public class TestExecutionException extends RuntimeException { + + public TestExecutionException(final Throwable t) { + super(t); + } + + private static final long serialVersionUID = 1L; + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/TestMethod.java b/pitest/src/test/java/org/pitest/simpletest/TestMethod.java index 4a577dcff..8cff71145 100644 --- a/pitest/src/test/java/org/pitest/simpletest/TestMethod.java +++ b/pitest/src/test/java/org/pitest/simpletest/TestMethod.java @@ -1,95 +1,95 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.simpletest; - -import java.lang.reflect.Method; - -import java.util.Optional; - -public class TestMethod { - - private final Method method; - private final Class expected; - - public TestMethod(final Method method) { - this(method, null); - } - - public TestMethod(final Method method, - final Class expected) { - this.method = method; - this.expected = expected; - } - - public String getName() { - return this.method.getName(); - } - - public Method getMethod() { - return this.method; - } - - public Optional> getExpected() { - return Optional.> ofNullable(this.expected); - } - - @Override - public String toString() { - return "TestMethod [expected=" + this.expected + ", method=" + this.method - + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.expected == null) ? 0 : this.expected.hashCode()); - result = (prime * result) - + ((this.method == null) ? 0 : this.method.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final TestMethod other = (TestMethod) obj; - if (this.expected == null) { - if (other.expected != null) { - return false; - } - } else if (!this.expected.equals(other.expected)) { - return false; - } - if (this.method == null) { - if (other.method != null) { - return false; - } - } else if (!this.method.equals(other.method)) { - return false; - } - return true; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.simpletest; + +import java.lang.reflect.Method; + +import java.util.Optional; + +public class TestMethod { + + private final Method method; + private final Class expected; + + public TestMethod(final Method method) { + this(method, null); + } + + public TestMethod(final Method method, + final Class expected) { + this.method = method; + this.expected = expected; + } + + public String getName() { + return this.method.getName(); + } + + public Method getMethod() { + return this.method; + } + + public Optional> getExpected() { + return Optional.> ofNullable(this.expected); + } + + @Override + public String toString() { + return "TestMethod [expected=" + this.expected + ", method=" + this.method + + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.expected == null) ? 0 : this.expected.hashCode()); + result = (prime * result) + + ((this.method == null) ? 0 : this.method.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final TestMethod other = (TestMethod) obj; + if (this.expected == null) { + if (other.expected != null) { + return false; + } + } else if (!this.expected.equals(other.expected)) { + return false; + } + if (this.method == null) { + if (other.method != null) { + return false; + } + } else if (!this.method.equals(other.method)) { + return false; + } + return true; + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/TestMethodTest.java b/pitest/src/test/java/org/pitest/simpletest/TestMethodTest.java index 66a976c0f..b196dea97 100644 --- a/pitest/src/test/java/org/pitest/simpletest/TestMethodTest.java +++ b/pitest/src/test/java/org/pitest/simpletest/TestMethodTest.java @@ -1,29 +1,29 @@ -package org.pitest.simpletest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.lang.reflect.Method; - -import org.junit.Test; -import org.pitest.reflection.Reflection; -import org.pitest.util.XStreamCloning; - -public class TestMethodTest { - - @Test - public void shouldCloneViaXStreamWithoutError() throws Exception { - try { - - final Method m = Reflection.publicMethod(this.getClass(), - "shouldCloneViaXStreamWithoutError"); - final TestMethod testee = new TestMethod(m, IOException.class); - final TestMethod actual = (TestMethod) XStreamCloning.clone(testee); - assertEquals(actual.getMethod(), testee.getMethod()); - } catch (final Throwable t) { - fail(); - } - } - -} +package org.pitest.simpletest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.junit.Test; +import org.pitest.reflection.Reflection; +import org.pitest.util.XStreamCloning; + +public class TestMethodTest { + + @Test + public void shouldCloneViaXStreamWithoutError() throws Exception { + try { + + final Method m = Reflection.publicMethod(this.getClass(), + "shouldCloneViaXStreamWithoutError"); + final TestMethod testee = new TestMethod(m, IOException.class); + final TestMethod actual = (TestMethod) XStreamCloning.clone(testee); + assertEquals(actual.getMethod(), testee.getMethod()); + } catch (final Throwable t) { + fail(); + } + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/TestStep.java b/pitest/src/test/java/org/pitest/simpletest/TestStep.java index cb7047b8e..fc5bf7f79 100644 --- a/pitest/src/test/java/org/pitest/simpletest/TestStep.java +++ b/pitest/src/test/java/org/pitest/simpletest/TestStep.java @@ -1,24 +1,24 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -import org.pitest.testapi.Description; - -public interface TestStep { - - public Object execute(Description testDescription, - Object target); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +import org.pitest.testapi.Description; + +public interface TestStep { + + public Object execute(Description testDescription, + Object target); + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/Transformation.java b/pitest/src/test/java/org/pitest/simpletest/Transformation.java index 3bdb21256..8a17ab00c 100644 --- a/pitest/src/test/java/org/pitest/simpletest/Transformation.java +++ b/pitest/src/test/java/org/pitest/simpletest/Transformation.java @@ -1,22 +1,22 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ - -package org.pitest.simpletest; - -public interface Transformation { - - public byte[] transform(String name, byte[] bytes); - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ + +package org.pitest.simpletest; + +public interface Transformation { + + public byte[] transform(String name, byte[] bytes); + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/TransformingClassLoader.java b/pitest/src/test/java/org/pitest/simpletest/TransformingClassLoader.java index efa70c25c..72e8f8943 100644 --- a/pitest/src/test/java/org/pitest/simpletest/TransformingClassLoader.java +++ b/pitest/src/test/java/org/pitest/simpletest/TransformingClassLoader.java @@ -1,54 +1,54 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest; - -import org.pitest.classpath.ClassPath; -import org.pitest.mutationtest.execute.DefaultPITClassloader; -import org.pitest.util.XStreamCloning; - -public class TransformingClassLoader extends DefaultPITClassloader { - - private final Transformation transformation; - private final IsolationStrategy isolationStrategy; - - public TransformingClassLoader(final Transformation transformation, - final IsolationStrategy isolationStrategy) { - this(new ClassPath(), transformation, isolationStrategy, XStreamCloning - .bootClassLoader()); - } - - public TransformingClassLoader(final ClassPath classPath, - final Transformation transformation, - final IsolationStrategy isolationStrategy, final ClassLoader parent) { - super(classPath, parent); - this.transformation = transformation; - this.isolationStrategy = isolationStrategy; - } - - @Override - protected Class defineClass(final String name, final byte[] bytes) { - final byte[] b = transform(name, bytes); - return defineClass(name, b, 0, b.length); - } - - private byte[] transform(final String name, final byte[] bytes) { - if (this.isolationStrategy.shouldIsolate(name)) { - return this.transformation.transform(name, bytes); - } else { - return bytes; - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest; + +import org.pitest.classpath.ClassPath; +import org.pitest.mutationtest.execute.DefaultPITClassloader; +import org.pitest.util.XStreamCloning; + +public class TransformingClassLoader extends DefaultPITClassloader { + + private final Transformation transformation; + private final IsolationStrategy isolationStrategy; + + public TransformingClassLoader(final Transformation transformation, + final IsolationStrategy isolationStrategy) { + this(new ClassPath(), transformation, isolationStrategy, XStreamCloning + .bootClassLoader()); + } + + public TransformingClassLoader(final ClassPath classPath, + final Transformation transformation, + final IsolationStrategy isolationStrategy, final ClassLoader parent) { + super(classPath, parent); + this.transformation = transformation; + this.isolationStrategy = isolationStrategy; + } + + @Override + protected Class defineClass(final String name, final byte[] bytes) { + final byte[] b = transform(name, bytes); + return defineClass(name, b, 0, b.length); + } + + private byte[] transform(final String name, final byte[] bytes) { + if (this.isolationStrategy.shouldIsolate(name)) { + return this.transformation.transform(name, bytes); + } else { + return bytes; + } + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/steps/CallStep.java b/pitest/src/test/java/org/pitest/simpletest/steps/CallStep.java index bce0a7a97..2077a4ac3 100644 --- a/pitest/src/test/java/org/pitest/simpletest/steps/CallStep.java +++ b/pitest/src/test/java/org/pitest/simpletest/steps/CallStep.java @@ -1,56 +1,56 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest.steps; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.pitest.simpletest.TestExecutionException; -import org.pitest.simpletest.TestMethod; -import org.pitest.simpletest.TestStep; -import org.pitest.testapi.Description; - -/** - * @author henry - * - */ -public class CallStep implements TestStep { - - private final TestMethod m; - - public CallStep(final TestMethod m) { - this.m = m; - } - - @Override - public Object execute(final Description testDescription, final Object target) { - try { - - final Method m2 = this.m.getMethod(); - - if (!m2.isAccessible()) { - m2.setAccessible(true); - } - m2.invoke(target); - - return target; - } catch (final InvocationTargetException t) { - throw new TestExecutionException(t.getCause()); - } catch (final Exception e) { - throw new TestExecutionException(e); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest.steps; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.pitest.simpletest.TestExecutionException; +import org.pitest.simpletest.TestMethod; +import org.pitest.simpletest.TestStep; +import org.pitest.testapi.Description; + +/** + * @author henry + * + */ +public class CallStep implements TestStep { + + private final TestMethod m; + + public CallStep(final TestMethod m) { + this.m = m; + } + + @Override + public Object execute(final Description testDescription, final Object target) { + try { + + final Method m2 = this.m.getMethod(); + + if (!m2.isAccessible()) { + m2.setAccessible(true); + } + m2.invoke(target); + + return target; + } catch (final InvocationTargetException t) { + throw new TestExecutionException(t.getCause()); + } catch (final Exception e) { + throw new TestExecutionException(e); + } + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/steps/CallStepTest.java b/pitest/src/test/java/org/pitest/simpletest/steps/CallStepTest.java index ba5ddba52..41cc0b11f 100644 --- a/pitest/src/test/java/org/pitest/simpletest/steps/CallStepTest.java +++ b/pitest/src/test/java/org/pitest/simpletest/steps/CallStepTest.java @@ -1,29 +1,29 @@ -package org.pitest.simpletest.steps; - -import static org.junit.Assert.assertSame; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.simpletest.TestMethod; - -public class CallStepTest { - - private TestMethod testMethod; - - @Before - public void setUp() throws Exception { - this.testMethod = new TestMethod(this.getClass().getMethod("testMethod")); - } - - @Test - public void shouldReturnSuppliedObject() { - final CallStep testee = new CallStep(this.testMethod); - assertSame(this, - testee.execute(null, this)); - } - - public void testMethod() { - - }; - -} +package org.pitest.simpletest.steps; + +import static org.junit.Assert.assertSame; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.simpletest.TestMethod; + +public class CallStepTest { + + private TestMethod testMethod; + + @Before + public void setUp() throws Exception { + this.testMethod = new TestMethod(this.getClass().getMethod("testMethod")); + } + + @Test + public void shouldReturnSuppliedObject() { + final CallStep testee = new CallStep(this.testMethod); + assertSame(this, + testee.execute(null, this)); + } + + public void testMethod() { + + }; + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStep.java b/pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStep.java index 923a352ac..7a7aea4fe 100644 --- a/pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStep.java +++ b/pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStep.java @@ -1,86 +1,86 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest.steps; - -import java.lang.reflect.Modifier; - -import org.pitest.simpletest.CanNotCreateTestClassException; -import org.pitest.simpletest.TestStep; -import org.pitest.testapi.Description; - -/** - * @author henry - * - */ -public final class NoArgsInstantiateStep implements TestStep { - - private final Class clazz; - - public static NoArgsInstantiateStep instantiate(final Class clazz) { - return new NoArgsInstantiateStep(clazz); - } - - public NoArgsInstantiateStep(final Class clazz) { - this.clazz = clazz; - } - - @Override - public Object execute(final Description testDescription, final Object target) { - try { - final Class c = this.clazz; - if (Modifier.isAbstract(c.getModifiers())) { - throw new CanNotCreateTestClassException( - "Cannot instantiate the abstract class " + c.getName(), null); - } else { - return c.newInstance(); - } - } catch (final Throwable e) { - e.printStackTrace(); - throw new CanNotCreateTestClassException(e.getMessage(), e); - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) - + ((this.clazz == null) ? 0 : this.clazz.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final NoArgsInstantiateStep other = (NoArgsInstantiateStep) obj; - if (this.clazz == null) { - if (other.clazz != null) { - return false; - } - } else if (!this.clazz.equals(other.clazz)) { - return false; - } - return true; - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest.steps; + +import java.lang.reflect.Modifier; + +import org.pitest.simpletest.CanNotCreateTestClassException; +import org.pitest.simpletest.TestStep; +import org.pitest.testapi.Description; + +/** + * @author henry + * + */ +public final class NoArgsInstantiateStep implements TestStep { + + private final Class clazz; + + public static NoArgsInstantiateStep instantiate(final Class clazz) { + return new NoArgsInstantiateStep(clazz); + } + + public NoArgsInstantiateStep(final Class clazz) { + this.clazz = clazz; + } + + @Override + public Object execute(final Description testDescription, final Object target) { + try { + final Class c = this.clazz; + if (Modifier.isAbstract(c.getModifiers())) { + throw new CanNotCreateTestClassException( + "Cannot instantiate the abstract class " + c.getName(), null); + } else { + return c.newInstance(); + } + } catch (final Throwable e) { + e.printStackTrace(); + throw new CanNotCreateTestClassException(e.getMessage(), e); + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + + ((this.clazz == null) ? 0 : this.clazz.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final NoArgsInstantiateStep other = (NoArgsInstantiateStep) obj; + if (this.clazz == null) { + if (other.clazz != null) { + return false; + } + } else if (!this.clazz.equals(other.clazz)) { + return false; + } + return true; + } + +} diff --git a/pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStepTest.java b/pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStepTest.java index 1253aaf50..411ee6047 100644 --- a/pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStepTest.java +++ b/pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStepTest.java @@ -1,46 +1,46 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.simpletest.steps; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.pitest.util.XStreamCloning; - -public class NoArgsInstantiateStepTest { - - @Test - public void shouldConstructsAnObject() { - final NoArgsInstantiateStep testee = new NoArgsInstantiateStep( - NoArgsInstantiateStepTest.class); - final NoArgsInstantiateStepTest actual = (NoArgsInstantiateStepTest) testee - .execute(null, null); - assertNotNull(actual); - } - - @Test - public void shouldSerializeAndDeserializeByXStreamWithoutError() - throws Exception { - try { - final NoArgsInstantiateStep testee = new NoArgsInstantiateStep( - NoArgsInstantiateStepTest.class); - XStreamCloning.clone(testee); - } catch (final Throwable t) { - fail(); - } - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.simpletest.steps; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.pitest.util.XStreamCloning; + +public class NoArgsInstantiateStepTest { + + @Test + public void shouldConstructsAnObject() { + final NoArgsInstantiateStep testee = new NoArgsInstantiateStep( + NoArgsInstantiateStepTest.class); + final NoArgsInstantiateStepTest actual = (NoArgsInstantiateStepTest) testee + .execute(null, null); + assertNotNull(actual); + } + + @Test + public void shouldSerializeAndDeserializeByXStreamWithoutError() + throws Exception { + try { + final NoArgsInstantiateStep testee = new NoArgsInstantiateStep( + NoArgsInstantiateStepTest.class); + XStreamCloning.clone(testee); + } catch (final Throwable t) { + fail(); + } + } + +} diff --git a/pitest/src/test/java/org/pitest/testapi/DescriptionTest.java b/pitest/src/test/java/org/pitest/testapi/DescriptionTest.java index 262a6ab3c..3c6e47cc2 100644 --- a/pitest/src/test/java/org/pitest/testapi/DescriptionTest.java +++ b/pitest/src/test/java/org/pitest/testapi/DescriptionTest.java @@ -1,28 +1,28 @@ -package org.pitest.testapi; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.junit.Test; -import org.pitest.util.XStreamCloning; - -public class DescriptionTest { - - private Description testee; - - @Test - public void shouldCloneViaXStreamWithoutError() throws Exception { - try { - this.testee = new Description("foo", IOException.class); - final Description actual = (Description) XStreamCloning - .clone(this.testee); - - assertEquals(this.testee, actual); - } catch (final Throwable t) { - fail(t.getMessage()); - } - } - -} +package org.pitest.testapi; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; + +import org.junit.Test; +import org.pitest.util.XStreamCloning; + +public class DescriptionTest { + + private Description testee; + + @Test + public void shouldCloneViaXStreamWithoutError() throws Exception { + try { + this.testee = new Description("foo", IOException.class); + final Description actual = (Description) XStreamCloning + .clone(this.testee); + + assertEquals(this.testee, actual); + } catch (final Throwable t) { + fail(t.getMessage()); + } + } + +} diff --git a/pitest/src/test/java/org/pitest/testapi/execute/ExitingResultCollectorTest.java b/pitest/src/test/java/org/pitest/testapi/execute/ExitingResultCollectorTest.java index 1d88b048c..0870b6cc6 100644 --- a/pitest/src/test/java/org/pitest/testapi/execute/ExitingResultCollectorTest.java +++ b/pitest/src/test/java/org/pitest/testapi/execute/ExitingResultCollectorTest.java @@ -1,78 +1,78 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.testapi.execute; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; - -public class ExitingResultCollectorTest { - - @Mock - ResultCollector rc; - - Description description; - - ExitingResultCollector testee; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.testee = new ExitingResultCollector(this.rc); - this.description = new Description("foo", ExitingResultCollectorTest.class); - } - - @Test - public void shouldNotifyChildOfTestStart() { - this.testee.notifyStart(this.description); - verify(this.rc, times(1)).notifyStart(this.description); - } - - @Test - public void shouldNotifyChildOfTestSkipped() { - this.testee.notifySkipped(this.description); - verify(this.rc, times(1)).notifySkipped(this.description); - } - - @Test - public void shouldNotifyChildOfTestSuccess() { - this.testee.notifyEnd(this.description); - verify(this.rc, times(1)).notifyEnd(this.description); - } - - @Test - public void shouldNotifyChildOfTestFailure() { - final RuntimeException er = new RuntimeException(); - this.testee.notifyEnd(this.description, er); - verify(this.rc, times(1)).notifyEnd(this.description, er); - } - - @Test - public void shouldRequestStopOnTestFailure() { - final RuntimeException er = new RuntimeException(); - assertFalse(this.testee.shouldExit()); - this.testee.notifyEnd(this.description, er); - assertTrue(this.testee.shouldExit()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.testapi.execute; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; + +public class ExitingResultCollectorTest { + + @Mock + ResultCollector rc; + + Description description; + + ExitingResultCollector testee; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.testee = new ExitingResultCollector(this.rc); + this.description = new Description("foo", ExitingResultCollectorTest.class); + } + + @Test + public void shouldNotifyChildOfTestStart() { + this.testee.notifyStart(this.description); + verify(this.rc, times(1)).notifyStart(this.description); + } + + @Test + public void shouldNotifyChildOfTestSkipped() { + this.testee.notifySkipped(this.description); + verify(this.rc, times(1)).notifySkipped(this.description); + } + + @Test + public void shouldNotifyChildOfTestSuccess() { + this.testee.notifyEnd(this.description); + verify(this.rc, times(1)).notifyEnd(this.description); + } + + @Test + public void shouldNotifyChildOfTestFailure() { + final RuntimeException er = new RuntimeException(); + this.testee.notifyEnd(this.description, er); + verify(this.rc, times(1)).notifyEnd(this.description, er); + } + + @Test + public void shouldRequestStopOnTestFailure() { + final RuntimeException er = new RuntimeException(); + assertFalse(this.testee.shouldExit()); + this.testee.notifyEnd(this.description, er); + assertTrue(this.testee.shouldExit()); + } + +} diff --git a/pitest/src/test/java/org/pitest/testapi/execute/MultipleTestGroupTest.java b/pitest/src/test/java/org/pitest/testapi/execute/MultipleTestGroupTest.java index bd639975b..8e888ce72 100644 --- a/pitest/src/test/java/org/pitest/testapi/execute/MultipleTestGroupTest.java +++ b/pitest/src/test/java/org/pitest/testapi/execute/MultipleTestGroupTest.java @@ -1,79 +1,79 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.testapi.execute; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; -import org.pitest.testapi.TestUnit; - -import nl.jqno.equalsverifier.EqualsVerifier; - -public class MultipleTestGroupTest { - - @Mock - private TestUnit emptyTestUnit; - @Mock - private TestUnit emptyTestUnit2; - - @Mock - private ResultCollector rc; - - private MultipleTestGroup testee; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(this.emptyTestUnit.getDescription()).thenReturn( - new Description("foo", String.class)); - when(this.emptyTestUnit2.getDescription()).thenReturn( - new Description("foo2", String.class)); - } - - @Test - public void shouldExecuteAllChildren() { - this.testee = new MultipleTestGroup(Arrays.asList(this.emptyTestUnit, - this.emptyTestUnit2)); - this.testee.execute(this.rc); - verify(this.emptyTestUnit, times(1)).execute(this.rc); - verify(this.emptyTestUnit2, times(1)).execute(this.rc); - } - - @Test - public void shouldStopExecutingWhenResultCollectorRequestsStop() { - when(this.rc.shouldExit()).thenReturn(true); - this.testee = new MultipleTestGroup(Arrays.asList(this.emptyTestUnit, - this.emptyTestUnit2)); - this.testee.execute(this.rc); - verify(this.emptyTestUnit, times(1)).execute(this.rc); - verify(this.emptyTestUnit2, never()).execute(this.rc); - } - - @Test - public void shouldObeyHashcodeEqualsContract() { - EqualsVerifier.forClass(MultipleTestGroup.class).verify(); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.testapi.execute; + +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; +import org.pitest.testapi.TestUnit; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class MultipleTestGroupTest { + + @Mock + private TestUnit emptyTestUnit; + @Mock + private TestUnit emptyTestUnit2; + + @Mock + private ResultCollector rc; + + private MultipleTestGroup testee; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(this.emptyTestUnit.getDescription()).thenReturn( + new Description("foo", String.class)); + when(this.emptyTestUnit2.getDescription()).thenReturn( + new Description("foo2", String.class)); + } + + @Test + public void shouldExecuteAllChildren() { + this.testee = new MultipleTestGroup(Arrays.asList(this.emptyTestUnit, + this.emptyTestUnit2)); + this.testee.execute(this.rc); + verify(this.emptyTestUnit, times(1)).execute(this.rc); + verify(this.emptyTestUnit2, times(1)).execute(this.rc); + } + + @Test + public void shouldStopExecutingWhenResultCollectorRequestsStop() { + when(this.rc.shouldExit()).thenReturn(true); + this.testee = new MultipleTestGroup(Arrays.asList(this.emptyTestUnit, + this.emptyTestUnit2)); + this.testee.execute(this.rc); + verify(this.emptyTestUnit, times(1)).execute(this.rc); + verify(this.emptyTestUnit2, never()).execute(this.rc); + } + + @Test + public void shouldObeyHashcodeEqualsContract() { + EqualsVerifier.forClass(MultipleTestGroup.class).verify(); + } + +} diff --git a/pitest/src/test/java/org/pitest/testapi/execute/ResultTypeTest.java b/pitest/src/test/java/org/pitest/testapi/execute/ResultTypeTest.java index 1108b13d4..522dc4031 100644 --- a/pitest/src/test/java/org/pitest/testapi/execute/ResultTypeTest.java +++ b/pitest/src/test/java/org/pitest/testapi/execute/ResultTypeTest.java @@ -1,66 +1,66 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.testapi.execute; - -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.testapi.Description; -import org.pitest.testapi.TestListener; -import org.pitest.testapi.TestResult; - -public class ResultTypeTest { - - @Mock - private TestListener listener; - - private final TestResult result = new TestResult(new Description("foo"), null); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void shouldCallOnTestSuccessOnListenerWhenTypeIsPass() { - callListenerFunction(ResultType.PASS); - verify(this.listener).onTestSuccess(this.result); - } - - @Test - public void shouldCallOnTestFailureOnListenerWhenTypeIsFail() { - callListenerFunction(ResultType.FAIL); - verify(this.listener).onTestFailure(this.result); - } - - @Test - public void shouldCallOnTestSkippedOnListenerWhenTypeIsSkipped() { - callListenerFunction(ResultType.SKIPPED); - verify(this.listener).onTestSkipped(this.result); - } - - @Test - public void shouldCallOnTestStartOnListenerWhenTypeIsStarted() { - callListenerFunction(ResultType.STARTED); - verify(this.listener).onTestStart(this.result.getDescription()); - } - - private void callListenerFunction(final ResultType testee) { - testee.getListenerFunction(this.result).apply(this.listener); - } -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.testapi.execute; + +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.testapi.Description; +import org.pitest.testapi.TestListener; +import org.pitest.testapi.TestResult; + +public class ResultTypeTest { + + @Mock + private TestListener listener; + + private final TestResult result = new TestResult(new Description("foo"), null); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldCallOnTestSuccessOnListenerWhenTypeIsPass() { + callListenerFunction(ResultType.PASS); + verify(this.listener).onTestSuccess(this.result); + } + + @Test + public void shouldCallOnTestFailureOnListenerWhenTypeIsFail() { + callListenerFunction(ResultType.FAIL); + verify(this.listener).onTestFailure(this.result); + } + + @Test + public void shouldCallOnTestSkippedOnListenerWhenTypeIsSkipped() { + callListenerFunction(ResultType.SKIPPED); + verify(this.listener).onTestSkipped(this.result); + } + + @Test + public void shouldCallOnTestStartOnListenerWhenTypeIsStarted() { + callListenerFunction(ResultType.STARTED); + verify(this.listener).onTestStart(this.result.getDescription()); + } + + private void callListenerFunction(final ResultType testee) { + testee.getListenerFunction(this.result).apply(this.listener); + } +} diff --git a/pitest/src/test/java/org/pitest/testapi/execute/TestPitest.java b/pitest/src/test/java/org/pitest/testapi/execute/TestPitest.java index ce8e7c6de..f7ab0633d 100644 --- a/pitest/src/test/java/org/pitest/testapi/execute/TestPitest.java +++ b/pitest/src/test/java/org/pitest/testapi/execute/TestPitest.java @@ -1,173 +1,173 @@ -/** - * - */ -package org.pitest.testapi.execute; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; - -import java.io.FileNotFoundException; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.simpletest.ConfigurationForTesting; -import org.pitest.simpletest.TestAnnotationForTesting; -import org.pitest.testapi.Description; -import org.pitest.testapi.TestListener; -import org.pitest.testapi.TestResult; -import org.pitest.testapi.execute.containers.UnContainer; - -/** - * @author henry - * - */ - -public class TestPitest { - - private Pitest testee; - private Container container; - - @Mock - private TestListener listener; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.container = new UnContainer(); - this.testee = new Pitest(this.listener); - } - - public static class PassingTest { - @TestAnnotationForTesting - public void shouldPass() { - - } - }; - - @Test - public void shouldNotifyListenerOfRunStart() { - run(PassingTest.class); - verify(this.listener).onRunStart(); - } - - @Test - public void shouldNotifyListenerOfTestStart() { - run(PassingTest.class); - verify(this.listener).onTestStart(any(Description.class)); - } - - @Test - public void shouldNotifyListenerOfTestSuccess() { - run(PassingTest.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - @Test - public void shouldNotifyListenerOfRunEnd() { - run(PassingTest.class); - verify(this.listener).onRunEnd(); - } - - @Test - public void shouldReportsSuccessIfNoExceptionThrown() { - run(PassingTest.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - public static class FailsAssertion { - @TestAnnotationForTesting - public void willFail() { - throw new AssertionError(); - } - }; - - @Test - public void shouldReportedAsFailureIfAssertionThrown() { - run(FailsAssertion.class); - verify(this.listener).onTestFailure(any(TestResult.class)); - } - - public static class ExpectedExceptionThrown { - @TestAnnotationForTesting(expected = NullPointerException.class) - public void expectToThrowNullPointer() { - throw new NullPointerException(); - } - - }; - - @Test - public void shouldReportSuccessIfExpectedExceptionThrown() { - run(ExpectedExceptionThrown.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - public static class ExpectedExceptionNotThrown { - @TestAnnotationForTesting(expected = NullPointerException.class) - public void expectToThrowNullPointer() { - - } - }; - - @Test - public void shouldReportFailureIfExpectedExceptionNotThrown() { - run(ExpectedExceptionNotThrown.class); - verify(this.listener).onTestFailure(any(TestResult.class)); - } - - public static class UnexpectedExceptionThrown { - @TestAnnotationForTesting - public void willFailWithError() throws Exception { - throw new FileNotFoundException(); - } - }; - - @Test - public void shouldReportFailureWhenExceptionThrownAndNoExpectationSet() { - run(UnexpectedExceptionThrown.class); - verify(this.listener).onTestFailure(any(TestResult.class)); - } - - public static class WrongExceptionThrown { - @TestAnnotationForTesting(expected = NullPointerException.class) - public void willFailWithError() throws Exception { - throw new FileNotFoundException(); - } - }; - - @Test - public void shouldReportFailureWhenThrownExceptionDifferentFromExpectedException() { - run(WrongExceptionThrown.class); - verify(this.listener).onTestFailure(any(TestResult.class)); - } - - public static class SubclassOfExpectedExceptionThrown { - @TestAnnotationForTesting(expected = Exception.class) - public void shouldPass() throws Exception { - throw new FileNotFoundException(); - } - }; - - @Test - public void shouldReportSuccessWhenSubclassOfExpectedExceptionThrown() { - run(SubclassOfExpectedExceptionThrown.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - public static class StaticTestCase { - @TestAnnotationForTesting - public static void staticTestMethod() { - } - }; - - @Test - public void shouldBeAbleToCallStaticTestMethods() { - run(StaticTestCase.class); - verify(this.listener).onTestSuccess(any(TestResult.class)); - } - - private void run(final Class clazz) { - this.testee.run(this.container, new ConfigurationForTesting(), clazz); - } +/** + * + */ +package org.pitest.testapi.execute; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; + +import java.io.FileNotFoundException; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.simpletest.ConfigurationForTesting; +import org.pitest.simpletest.TestAnnotationForTesting; +import org.pitest.testapi.Description; +import org.pitest.testapi.TestListener; +import org.pitest.testapi.TestResult; +import org.pitest.testapi.execute.containers.UnContainer; + +/** + * @author henry + * + */ + +public class TestPitest { + + private Pitest testee; + private Container container; + + @Mock + private TestListener listener; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.container = new UnContainer(); + this.testee = new Pitest(this.listener); + } + + public static class PassingTest { + @TestAnnotationForTesting + public void shouldPass() { + + } + }; + + @Test + public void shouldNotifyListenerOfRunStart() { + run(PassingTest.class); + verify(this.listener).onRunStart(); + } + + @Test + public void shouldNotifyListenerOfTestStart() { + run(PassingTest.class); + verify(this.listener).onTestStart(any(Description.class)); + } + + @Test + public void shouldNotifyListenerOfTestSuccess() { + run(PassingTest.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + @Test + public void shouldNotifyListenerOfRunEnd() { + run(PassingTest.class); + verify(this.listener).onRunEnd(); + } + + @Test + public void shouldReportsSuccessIfNoExceptionThrown() { + run(PassingTest.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + public static class FailsAssertion { + @TestAnnotationForTesting + public void willFail() { + throw new AssertionError(); + } + }; + + @Test + public void shouldReportedAsFailureIfAssertionThrown() { + run(FailsAssertion.class); + verify(this.listener).onTestFailure(any(TestResult.class)); + } + + public static class ExpectedExceptionThrown { + @TestAnnotationForTesting(expected = NullPointerException.class) + public void expectToThrowNullPointer() { + throw new NullPointerException(); + } + + }; + + @Test + public void shouldReportSuccessIfExpectedExceptionThrown() { + run(ExpectedExceptionThrown.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + public static class ExpectedExceptionNotThrown { + @TestAnnotationForTesting(expected = NullPointerException.class) + public void expectToThrowNullPointer() { + + } + }; + + @Test + public void shouldReportFailureIfExpectedExceptionNotThrown() { + run(ExpectedExceptionNotThrown.class); + verify(this.listener).onTestFailure(any(TestResult.class)); + } + + public static class UnexpectedExceptionThrown { + @TestAnnotationForTesting + public void willFailWithError() throws Exception { + throw new FileNotFoundException(); + } + }; + + @Test + public void shouldReportFailureWhenExceptionThrownAndNoExpectationSet() { + run(UnexpectedExceptionThrown.class); + verify(this.listener).onTestFailure(any(TestResult.class)); + } + + public static class WrongExceptionThrown { + @TestAnnotationForTesting(expected = NullPointerException.class) + public void willFailWithError() throws Exception { + throw new FileNotFoundException(); + } + }; + + @Test + public void shouldReportFailureWhenThrownExceptionDifferentFromExpectedException() { + run(WrongExceptionThrown.class); + verify(this.listener).onTestFailure(any(TestResult.class)); + } + + public static class SubclassOfExpectedExceptionThrown { + @TestAnnotationForTesting(expected = Exception.class) + public void shouldPass() throws Exception { + throw new FileNotFoundException(); + } + }; + + @Test + public void shouldReportSuccessWhenSubclassOfExpectedExceptionThrown() { + run(SubclassOfExpectedExceptionThrown.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + public static class StaticTestCase { + @TestAnnotationForTesting + public static void staticTestMethod() { + } + }; + + @Test + public void shouldBeAbleToCallStaticTestMethods() { + run(StaticTestCase.class); + verify(this.listener).onTestSuccess(any(TestResult.class)); + } + + private void run(final Class clazz) { + this.testee.run(this.container, new ConfigurationForTesting(), clazz); + } } \ No newline at end of file diff --git a/pitest/src/test/java/org/pitest/testng/TestNGAdapterTest.java b/pitest/src/test/java/org/pitest/testng/TestNGAdapterTest.java index baed6de53..80dc7308d 100644 --- a/pitest/src/test/java/org/pitest/testng/TestNGAdapterTest.java +++ b/pitest/src/test/java/org/pitest/testng/TestNGAdapterTest.java @@ -1,97 +1,97 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.testng; - -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; -import org.testng.ITestNGMethod; -import org.testng.ITestResult; - -public class TestNGAdapterTest { - - private TestNGAdapter testee; - - @Mock - private ResultCollector rc; - - @Mock - private ITestResult result; - - @Mock - private ITestNGMethod method; - - private Description description; - private Class clazz; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.description = new Description("foo"); - this.clazz = TestNGAdapterTest.class; - this.testee = new TestNGAdapter(this.clazz, this.description, this.rc); - when(this.method.getMethodName()).thenReturn("method"); - when(this.result.getMethod()).thenReturn(this.method); - } - - @Test - public void shouldCallNotifyStartWhenTestStarts() { - this.testee.onStart(null); - verify(this.rc, times(1)).notifyStart(this.description); - } - - @Test - public void shouldCallNotifyEndWhenTestEndWithoutError() { - this.testee.onFinish(null); - verify(this.rc, times(1)).notifyEnd(this.description); - } - - @Test - public void shouldCallNotifyEndWithErrorWhenTestEndsFollowingError() { - final Throwable throwable = new RuntimeException(); - when(this.result.getThrowable()).thenReturn(throwable); - this.testee.onTestFailure(this.result); - this.testee.onFinish(null); - verify(this.rc, times(1)).notifyEnd(this.description, throwable); - } - - @Test - public void shouldCallStartAndEndForMethodWhenNoError() { - this.testee.onTestStart(this.result); - this.testee.onTestSuccess(this.result); - verify(this.rc, times(1)) - .notifyStart(new Description("method", this.clazz)); - verify(this.rc, times(1)).notifyEnd(new Description("method", this.clazz)); - } - - @Test - public void shouldCallStartAndEndForMethodWhenError() { - final Throwable throwable = new RuntimeException(); - when(this.result.getThrowable()).thenReturn(throwable); - this.testee.onTestStart(this.result); - this.testee.onTestFailure(this.result); - verify(this.rc, times(1)) - .notifyStart(new Description("method", this.clazz)); - verify(this.rc, times(1)).notifyEnd(new Description("method", this.clazz), - throwable); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.testng; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; +import org.testng.ITestNGMethod; +import org.testng.ITestResult; + +public class TestNGAdapterTest { + + private TestNGAdapter testee; + + @Mock + private ResultCollector rc; + + @Mock + private ITestResult result; + + @Mock + private ITestNGMethod method; + + private Description description; + private Class clazz; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.description = new Description("foo"); + this.clazz = TestNGAdapterTest.class; + this.testee = new TestNGAdapter(this.clazz, this.description, this.rc); + when(this.method.getMethodName()).thenReturn("method"); + when(this.result.getMethod()).thenReturn(this.method); + } + + @Test + public void shouldCallNotifyStartWhenTestStarts() { + this.testee.onStart(null); + verify(this.rc, times(1)).notifyStart(this.description); + } + + @Test + public void shouldCallNotifyEndWhenTestEndWithoutError() { + this.testee.onFinish(null); + verify(this.rc, times(1)).notifyEnd(this.description); + } + + @Test + public void shouldCallNotifyEndWithErrorWhenTestEndsFollowingError() { + final Throwable throwable = new RuntimeException(); + when(this.result.getThrowable()).thenReturn(throwable); + this.testee.onTestFailure(this.result); + this.testee.onFinish(null); + verify(this.rc, times(1)).notifyEnd(this.description, throwable); + } + + @Test + public void shouldCallStartAndEndForMethodWhenNoError() { + this.testee.onTestStart(this.result); + this.testee.onTestSuccess(this.result); + verify(this.rc, times(1)) + .notifyStart(new Description("method", this.clazz)); + verify(this.rc, times(1)).notifyEnd(new Description("method", this.clazz)); + } + + @Test + public void shouldCallStartAndEndForMethodWhenError() { + final Throwable throwable = new RuntimeException(); + when(this.result.getThrowable()).thenReturn(throwable); + this.testee.onTestStart(this.result); + this.testee.onTestFailure(this.result); + verify(this.rc, times(1)) + .notifyStart(new Description("method", this.clazz)); + verify(this.rc, times(1)).notifyEnd(new Description("method", this.clazz), + throwable); + } +} diff --git a/pitest/src/test/java/org/pitest/testng/TestNGConfigurationTest.java b/pitest/src/test/java/org/pitest/testng/TestNGConfigurationTest.java index fb554a35e..13428ccac 100644 --- a/pitest/src/test/java/org/pitest/testng/TestNGConfigurationTest.java +++ b/pitest/src/test/java/org/pitest/testng/TestNGConfigurationTest.java @@ -1,40 +1,40 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.testng; - -import static org.junit.Assert.assertEquals; - -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import java.util.Optional; -import org.pitest.testapi.TestGroupConfig; - -public class TestNGConfigurationTest { - - private TestNGConfiguration testee; - - @Before - public void setUp() { - this.testee = new TestNGConfiguration(new TestGroupConfig(null, null), Collections. emptyList()); - } - - @Test - public void shouldVerifyEnvironmentWithoutError() { - assertEquals(Optional.empty(), this.testee.verifyEnvironment()); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.testng; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import java.util.Optional; +import org.pitest.testapi.TestGroupConfig; + +public class TestNGConfigurationTest { + + private TestNGConfiguration testee; + + @Before + public void setUp() { + this.testee = new TestNGConfiguration(new TestGroupConfig(null, null), Collections. emptyList()); + } + + @Test + public void shouldVerifyEnvironmentWithoutError() { + assertEquals(Optional.empty(), this.testee.verifyEnvironment()); + } + +} diff --git a/pitest/src/test/java/org/pitest/testng/TestNGTestUnitFinderTest.java b/pitest/src/test/java/org/pitest/testng/TestNGTestUnitFinderTest.java index 77bcdfa4b..3db986a6f 100644 --- a/pitest/src/test/java/org/pitest/testng/TestNGTestUnitFinderTest.java +++ b/pitest/src/test/java/org/pitest/testng/TestNGTestUnitFinderTest.java @@ -1,61 +1,61 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.testng; - -import static org.junit.Assert.assertEquals; - -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; -import org.pitest.testapi.TestGroupConfig; - -import com.example.testng.AbstractTestNGClass; -import com.example.testng.AnnotatedAtClassLevel; -import com.example.testng.AnnotatedAtMethodLevel; - -public class TestNGTestUnitFinderTest { - - private TestNGTestUnitFinder testee; - - @Before - public void setUp() { - final TestGroupConfig config = new TestGroupConfig( - Collections. emptyList(), Collections. emptyList()); - this.testee = new TestNGTestUnitFinder(config, Collections. emptyList()); - } - - @Test - public void shouldFindSingleTestUnitForAllPublicMethodsInAnnotatedClass() { - assertEquals(1, this.testee.findTestUnits(AnnotatedAtClassLevel.class) - .size()); - } - - @Test - public void shouldFindSingleTestUnitClassWithAnnotatedMethods() { - assertEquals(1, this.testee.findTestUnits(AnnotatedAtMethodLevel.class) - .size()); - } - - @Test - public void shouldFindNoTestUnitsInUnannotatedClasses() { - assertEquals(0, this.testee.findTestUnits(String.class).size()); - } - - @Test - public void shouldIgnoreAbstractClasses() { - assertEquals(0, this.testee.findTestUnits(AbstractTestNGClass.class).size()); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.testng; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.pitest.testapi.TestGroupConfig; + +import com.example.testng.AbstractTestNGClass; +import com.example.testng.AnnotatedAtClassLevel; +import com.example.testng.AnnotatedAtMethodLevel; + +public class TestNGTestUnitFinderTest { + + private TestNGTestUnitFinder testee; + + @Before + public void setUp() { + final TestGroupConfig config = new TestGroupConfig( + Collections. emptyList(), Collections. emptyList()); + this.testee = new TestNGTestUnitFinder(config, Collections. emptyList()); + } + + @Test + public void shouldFindSingleTestUnitForAllPublicMethodsInAnnotatedClass() { + assertEquals(1, this.testee.findTestUnits(AnnotatedAtClassLevel.class) + .size()); + } + + @Test + public void shouldFindSingleTestUnitClassWithAnnotatedMethods() { + assertEquals(1, this.testee.findTestUnits(AnnotatedAtMethodLevel.class) + .size()); + } + + @Test + public void shouldFindNoTestUnitsInUnannotatedClasses() { + assertEquals(0, this.testee.findTestUnits(String.class).size()); + } + + @Test + public void shouldIgnoreAbstractClasses() { + assertEquals(0, this.testee.findTestUnits(AbstractTestNGClass.class).size()); + } +} diff --git a/pitest/src/test/java/org/pitest/testng/TestNGTestUnitTest.java b/pitest/src/test/java/org/pitest/testng/TestNGTestUnitTest.java index 1d86c63ff..5e5042232 100644 --- a/pitest/src/test/java/org/pitest/testng/TestNGTestUnitTest.java +++ b/pitest/src/test/java/org/pitest/testng/TestNGTestUnitTest.java @@ -1,160 +1,160 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.testng; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.pitest.testapi.Description; -import org.pitest.testapi.ResultCollector; -import org.pitest.testapi.TestGroupConfig; - -import com.example.testng.Fails; -import com.example.testng.HasGroups; -import com.example.testng.Passes; -import com.example.testng.Skips; - -import junit.framework.AssertionFailedError; - -public class TestNGTestUnitTest { - - @Mock - private ResultCollector rc; - - private TestNGTestUnit testee; - private TestGroupConfig config; - private Collection includedTestMethods; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.config = new TestGroupConfig(Collections. emptyList(), - Collections. emptyList()); - this.includedTestMethods = Collections.emptyList(); - } - - @Test - public void shouldReportTestClassStart() { - this.testee = new TestNGTestUnit(Passes.class, this.config, this.includedTestMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)).notifyStart(this.testee.getDescription()); - } - - - @Test - public void shouldReportTestMethodStart() { - this.testee = new TestNGTestUnit(Passes.class, this.config, this.includedTestMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)).notifyStart( - new Description("passes", Passes.class)); - } - - @Test - public void shouldReportTestEndWithoutErorWhenTestRunsSuccessfully() { - this.testee = new TestNGTestUnit(Passes.class, this.config, this.includedTestMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)) - .notifyEnd(new Description("passes", Passes.class)); - } - - @Test - public void shouldReportTestEndWithThrowableWhenTestFails() { - this.testee = new TestNGTestUnit(Fails.class, this.config, this.includedTestMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)).notifyEnd( - eq(new Description("fails", Fails.class)), - any(AssertionFailedError.class)); - } - - @Test - public void shouldSkipPassingTestsAfterAFailure() { - this.testee = new TestNGTestUnit(Fails.class, this.config, this.includedTestMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)).notifySkipped( - eq(new Description("passes", Fails.class))); - } - - // we have static state so history may affect results - @Test - public void shouldRunTestsInNextTestClassAferFailure() { - new TestNGTestUnit(Fails.class, this.config, this.includedTestMethods).execute(Mockito.mock(ResultCollector.class)); - - this.testee = new TestNGTestUnit(Passes.class, this.config, this.includedTestMethods); - this.testee.execute(this.rc); - - verify(this.rc, times(1)) - .notifyEnd(new Description("passes", Passes.class));; - } - - @Test - public void shouldNotRunTestsInExcludedGroups() { - final TestGroupConfig excludeConfig = new TestGroupConfig( - Arrays.asList("exclude"), Collections. emptyList()); - this.testee = new TestNGTestUnit(HasGroups.class, excludeConfig, this.includedTestMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)).notifyEnd( - new Description("includeGroup", HasGroups.class)); - verify(this.rc, times(1)).notifyEnd( - new Description("noGroup", HasGroups.class)); - } - - @Test - public void shouldOnlyRunTestsInIncludedGroups() { - final TestGroupConfig excludeConfig = new TestGroupConfig( - Collections. emptyList(), Arrays.asList("include")); - this.testee = new TestNGTestUnit(HasGroups.class, excludeConfig, this.includedTestMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)).notifyEnd( - new Description("includeGroup", HasGroups.class)); - verify(this.rc, times(1)).notifyEnd( - new Description("includeAndExcludeGroup", HasGroups.class)); - } - - @Test - public void shouldOnlyRunTestsInIncludedTestMethods() { - final List includedMethods = new ArrayList<>(); - includedMethods.add("includeGroup"); - includedMethods.add("excludeGroup"); - - this.testee = new TestNGTestUnit(HasGroups.class, this.config, includedMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)).notifyEnd( - new Description("includeGroup", HasGroups.class)); - verify(this.rc, times(1)).notifyEnd( - new Description("excludeGroup", HasGroups.class)); - } - - @Test - public void shouldReportTestSkipped() { - this.testee = new TestNGTestUnit(Skips.class, this.config, this.includedTestMethods); - this.testee.execute(this.rc); - verify(this.rc, times(1)).notifySkipped( - eq(new Description("skip", Skips.class))); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.testng; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.pitest.testapi.Description; +import org.pitest.testapi.ResultCollector; +import org.pitest.testapi.TestGroupConfig; + +import com.example.testng.Fails; +import com.example.testng.HasGroups; +import com.example.testng.Passes; +import com.example.testng.Skips; + +import junit.framework.AssertionFailedError; + +public class TestNGTestUnitTest { + + @Mock + private ResultCollector rc; + + private TestNGTestUnit testee; + private TestGroupConfig config; + private Collection includedTestMethods; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.config = new TestGroupConfig(Collections. emptyList(), + Collections. emptyList()); + this.includedTestMethods = Collections.emptyList(); + } + + @Test + public void shouldReportTestClassStart() { + this.testee = new TestNGTestUnit(Passes.class, this.config, this.includedTestMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)).notifyStart(this.testee.getDescription()); + } + + + @Test + public void shouldReportTestMethodStart() { + this.testee = new TestNGTestUnit(Passes.class, this.config, this.includedTestMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)).notifyStart( + new Description("passes", Passes.class)); + } + + @Test + public void shouldReportTestEndWithoutErorWhenTestRunsSuccessfully() { + this.testee = new TestNGTestUnit(Passes.class, this.config, this.includedTestMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)) + .notifyEnd(new Description("passes", Passes.class)); + } + + @Test + public void shouldReportTestEndWithThrowableWhenTestFails() { + this.testee = new TestNGTestUnit(Fails.class, this.config, this.includedTestMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)).notifyEnd( + eq(new Description("fails", Fails.class)), + any(AssertionFailedError.class)); + } + + @Test + public void shouldSkipPassingTestsAfterAFailure() { + this.testee = new TestNGTestUnit(Fails.class, this.config, this.includedTestMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)).notifySkipped( + eq(new Description("passes", Fails.class))); + } + + // we have static state so history may affect results + @Test + public void shouldRunTestsInNextTestClassAferFailure() { + new TestNGTestUnit(Fails.class, this.config, this.includedTestMethods).execute(Mockito.mock(ResultCollector.class)); + + this.testee = new TestNGTestUnit(Passes.class, this.config, this.includedTestMethods); + this.testee.execute(this.rc); + + verify(this.rc, times(1)) + .notifyEnd(new Description("passes", Passes.class));; + } + + @Test + public void shouldNotRunTestsInExcludedGroups() { + final TestGroupConfig excludeConfig = new TestGroupConfig( + Arrays.asList("exclude"), Collections. emptyList()); + this.testee = new TestNGTestUnit(HasGroups.class, excludeConfig, this.includedTestMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)).notifyEnd( + new Description("includeGroup", HasGroups.class)); + verify(this.rc, times(1)).notifyEnd( + new Description("noGroup", HasGroups.class)); + } + + @Test + public void shouldOnlyRunTestsInIncludedGroups() { + final TestGroupConfig excludeConfig = new TestGroupConfig( + Collections. emptyList(), Arrays.asList("include")); + this.testee = new TestNGTestUnit(HasGroups.class, excludeConfig, this.includedTestMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)).notifyEnd( + new Description("includeGroup", HasGroups.class)); + verify(this.rc, times(1)).notifyEnd( + new Description("includeAndExcludeGroup", HasGroups.class)); + } + + @Test + public void shouldOnlyRunTestsInIncludedTestMethods() { + final List includedMethods = new ArrayList<>(); + includedMethods.add("includeGroup"); + includedMethods.add("excludeGroup"); + + this.testee = new TestNGTestUnit(HasGroups.class, this.config, includedMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)).notifyEnd( + new Description("includeGroup", HasGroups.class)); + verify(this.rc, times(1)).notifyEnd( + new Description("excludeGroup", HasGroups.class)); + } + + @Test + public void shouldReportTestSkipped() { + this.testee = new TestNGTestUnit(Skips.class, this.config, this.includedTestMethods); + this.testee.execute(this.rc); + verify(this.rc, times(1)).notifySkipped( + eq(new Description("skip", Skips.class))); + } + +} diff --git a/pitest/src/test/java/org/pitest/util/CachingByteArraySourceTest.java b/pitest/src/test/java/org/pitest/util/CachingByteArraySourceTest.java index 273cd6ea6..57097d06f 100644 --- a/pitest/src/test/java/org/pitest/util/CachingByteArraySourceTest.java +++ b/pitest/src/test/java/org/pitest/util/CachingByteArraySourceTest.java @@ -1,46 +1,46 @@ -package org.pitest.util; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.pitest.classinfo.CachingByteArraySource; -import org.pitest.classinfo.ClassByteArraySource; -import java.util.Optional; - -@RunWith(MockitoJUnitRunner.class) -public class CachingByteArraySourceTest { - - @Mock - ClassByteArraySource source; - - @Test - public void shouldReturnBytesFromChild() { - final Optional childResult = Optional.ofNullable(new byte[0]); - - when(this.source.getBytes("someClass")).thenReturn(childResult); - - final CachingByteArraySource testee = new CachingByteArraySource(this.source, 2); - - assertThat(testee.getBytes("someClass")).isSameAs(childResult); - } - - @Test - public void shouldCacheByteFromChild() { - when(this.source.getBytes("someClass")).thenReturn(Optional.ofNullable(new byte[0])); - - final CachingByteArraySource testee = new CachingByteArraySource(this.source, 2); - - testee.getBytes("someClass"); - testee.getBytes("someClass"); - testee.getBytes("someClass"); - - verify(this.source, times(1)).getBytes("someClass"); - } - -} +package org.pitest.util; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.pitest.classinfo.CachingByteArraySource; +import org.pitest.classinfo.ClassByteArraySource; +import java.util.Optional; + +@RunWith(MockitoJUnitRunner.class) +public class CachingByteArraySourceTest { + + @Mock + ClassByteArraySource source; + + @Test + public void shouldReturnBytesFromChild() { + final Optional childResult = Optional.ofNullable(new byte[0]); + + when(this.source.getBytes("someClass")).thenReturn(childResult); + + final CachingByteArraySource testee = new CachingByteArraySource(this.source, 2); + + assertThat(testee.getBytes("someClass")).isSameAs(childResult); + } + + @Test + public void shouldCacheByteFromChild() { + when(this.source.getBytes("someClass")).thenReturn(Optional.ofNullable(new byte[0])); + + final CachingByteArraySource testee = new CachingByteArraySource(this.source, 2); + + testee.getBytes("someClass"); + testee.getBytes("someClass"); + testee.getBytes("someClass"); + + verify(this.source, times(1)).getBytes("someClass"); + } + +} diff --git a/pitest/src/test/java/org/pitest/util/FunctionsTest.java b/pitest/src/test/java/org/pitest/util/FunctionsTest.java index 2423a2e92..ba3e47655 100644 --- a/pitest/src/test/java/org/pitest/util/FunctionsTest.java +++ b/pitest/src/test/java/org/pitest/util/FunctionsTest.java @@ -1,61 +1,61 @@ -/* - * Copyright 2010 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class FunctionsTest { - - @Test - public void classToNameShouldReturnClassName() { - assertEquals(String.class.getName(), - Functions.classToName().apply(String.class)); - } - - @Test - public void startWithShouldReturnTrueIfGivenStringStartsWithParameter() { - assertTrue(Functions.startsWith("foo").test("foobar")); - } - - @Test - public void startWithShouldReturnFalseIfGivenStringDoesNotStartsWithParameter() { - assertFalse(Functions.startsWith("foo").test("barfoo")); - } - - static enum Foo { - A, B, C, Bar; - }; - - @Test - public void stringToEnumShouldConvertStringsToEnumValues() { - assertEquals(Foo.A, Functions.stringToEnum(Foo.class).apply("A")); - assertEquals(Foo.Bar, Functions.stringToEnum(Foo.class).apply("Bar")); - } - - @Test - public void classNameToJVMClassNameShouldConvertDotsToSlashes() { - assertEquals("a/b/c", Functions.classNameToJVMClassName().apply("a.b.c")); - } - - @Test - public void jvmClassToClassNameShouldConvertSlashesToDots() { - assertEquals("a.b.c", Functions.jvmClassToClassName().apply("a/b/c")); - } - -} +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class FunctionsTest { + + @Test + public void classToNameShouldReturnClassName() { + assertEquals(String.class.getName(), + Functions.classToName().apply(String.class)); + } + + @Test + public void startWithShouldReturnTrueIfGivenStringStartsWithParameter() { + assertTrue(Functions.startsWith("foo").test("foobar")); + } + + @Test + public void startWithShouldReturnFalseIfGivenStringDoesNotStartsWithParameter() { + assertFalse(Functions.startsWith("foo").test("barfoo")); + } + + static enum Foo { + A, B, C, Bar; + }; + + @Test + public void stringToEnumShouldConvertStringsToEnumValues() { + assertEquals(Foo.A, Functions.stringToEnum(Foo.class).apply("A")); + assertEquals(Foo.Bar, Functions.stringToEnum(Foo.class).apply("Bar")); + } + + @Test + public void classNameToJVMClassNameShouldConvertDotsToSlashes() { + assertEquals("a/b/c", Functions.classNameToJVMClassName().apply("a.b.c")); + } + + @Test + public void jvmClassToClassNameShouldConvertSlashesToDots() { + assertEquals("a.b.c", Functions.jvmClassToClassName().apply("a/b/c")); + } + +} diff --git a/pitest/src/test/java/org/pitest/util/GlobTest.java b/pitest/src/test/java/org/pitest/util/GlobTest.java index a1604cc09..d8d44e183 100644 --- a/pitest/src/test/java/org/pitest/util/GlobTest.java +++ b/pitest/src/test/java/org/pitest/util/GlobTest.java @@ -1,78 +1,78 @@ -package org.pitest.util; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class GlobTest { - - @Test - public void shouldHandleEmptyStrings() { - final Glob glob = new Glob(""); - assertTrue(glob.matches("")); - } - - @Test - public void shouldFindExactMatches() { - final String value = "org.foo.foo"; - final Glob glob = new Glob(value); - assertTrue(glob.matches(value)); - } - - @Test - public void shouldNotMatchNonMatchingStringWhenNoWildcardsPresent() { - final String value = "org.foo.foo"; - final Glob glob = new Glob("org.foo"); - assertFalse(glob.matches(value)); - } - - @Test - public void shouldMatchEverythingAfterAStar() { - final Glob glob = new Glob("org.foo.*"); - assertTrue(glob.matches("org.foo.foo")); - assertTrue(glob.matches("org.foo.")); - assertTrue(glob.matches("org.foo.bar")); - } - - @Test - public void shouldNotMatchIfContentDiffersBeforeAStar() { - final Glob glob = new Glob("org.foo.*"); - assertFalse(glob.matches("org.fo")); - } - - @Test - public void shouldEscapeDotsInGeneratedRegex() { - final Glob glob = new Glob("org.foo.bar"); - assertFalse(glob.matches("orgafooabar")); - } - - @Test - public void shouldSupportQuestionMarkWildCard() { - final Glob glob = new Glob("org?foo?bar"); - assertTrue(glob.matches("org.foo.bar")); - assertTrue(glob.matches("orgafooabar")); - } - - @Test - public void shouldEscapeEscapesInGeneratedRegex() { - final Glob glob = new Glob("org.\\bar"); - assertTrue(glob.matches("org.\\bar")); - assertFalse(glob.matches("org.bar")); - } - - @Test - public void shouldSupportMultipleWildcards() { - final Glob glob = new Glob("foo*bar*car"); - assertTrue(glob.matches("foo!!!bar!!!car")); - assertFalse(glob.matches("foo!!!!!car")); - } - - @Test - public void shouldBeCaseSensitice() { - final Glob glob = new Glob("foo*bar*car"); - assertTrue(glob.matches("foo!!!bar!!!car")); - assertFalse(glob.matches("foo!!!Bar!!!car")); - } - -} +package org.pitest.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class GlobTest { + + @Test + public void shouldHandleEmptyStrings() { + final Glob glob = new Glob(""); + assertTrue(glob.matches("")); + } + + @Test + public void shouldFindExactMatches() { + final String value = "org.foo.foo"; + final Glob glob = new Glob(value); + assertTrue(glob.matches(value)); + } + + @Test + public void shouldNotMatchNonMatchingStringWhenNoWildcardsPresent() { + final String value = "org.foo.foo"; + final Glob glob = new Glob("org.foo"); + assertFalse(glob.matches(value)); + } + + @Test + public void shouldMatchEverythingAfterAStar() { + final Glob glob = new Glob("org.foo.*"); + assertTrue(glob.matches("org.foo.foo")); + assertTrue(glob.matches("org.foo.")); + assertTrue(glob.matches("org.foo.bar")); + } + + @Test + public void shouldNotMatchIfContentDiffersBeforeAStar() { + final Glob glob = new Glob("org.foo.*"); + assertFalse(glob.matches("org.fo")); + } + + @Test + public void shouldEscapeDotsInGeneratedRegex() { + final Glob glob = new Glob("org.foo.bar"); + assertFalse(glob.matches("orgafooabar")); + } + + @Test + public void shouldSupportQuestionMarkWildCard() { + final Glob glob = new Glob("org?foo?bar"); + assertTrue(glob.matches("org.foo.bar")); + assertTrue(glob.matches("orgafooabar")); + } + + @Test + public void shouldEscapeEscapesInGeneratedRegex() { + final Glob glob = new Glob("org.\\bar"); + assertTrue(glob.matches("org.\\bar")); + assertFalse(glob.matches("org.bar")); + } + + @Test + public void shouldSupportMultipleWildcards() { + final Glob glob = new Glob("foo*bar*car"); + assertTrue(glob.matches("foo!!!bar!!!car")); + assertFalse(glob.matches("foo!!!!!car")); + } + + @Test + public void shouldBeCaseSensitice() { + final Glob glob = new Glob("foo*bar*car"); + assertTrue(glob.matches("foo!!!bar!!!car")); + assertFalse(glob.matches("foo!!!Bar!!!car")); + } + +} diff --git a/pitest/src/test/java/org/pitest/util/PitXmlDriver.java b/pitest/src/test/java/org/pitest/util/PitXmlDriver.java index b9814b6e6..47685c323 100644 --- a/pitest/src/test/java/org/pitest/util/PitXmlDriver.java +++ b/pitest/src/test/java/org/pitest/util/PitXmlDriver.java @@ -1,39 +1,39 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import org.xmlpull.mxp1.MXParser; -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; - -import com.thoughtworks.xstream.io.xml.AbstractXppDriver; -import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder; - -/** - * Pull parser driver that creates hard coded parser type to avoid clashes with - * other pull parser on classpath when code under test uses xstream - */ -public class PitXmlDriver extends AbstractXppDriver { - - public PitXmlDriver() { - super(new XmlFriendlyNameCoder()); - } - - @Override - protected synchronized XmlPullParser createParser() - throws XmlPullParserException { - return new MXParser(); - } -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import org.xmlpull.mxp1.MXParser; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; + +import com.thoughtworks.xstream.io.xml.AbstractXppDriver; +import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder; + +/** + * Pull parser driver that creates hard coded parser type to avoid clashes with + * other pull parser on classpath when code under test uses xstream + */ +public class PitXmlDriver extends AbstractXppDriver { + + public PitXmlDriver() { + super(new XmlFriendlyNameCoder()); + } + + @Override + protected synchronized XmlPullParser createParser() + throws XmlPullParserException { + return new MXParser(); + } +} diff --git a/pitest/src/test/java/org/pitest/util/ResourceFolderByteArraySource.java b/pitest/src/test/java/org/pitest/util/ResourceFolderByteArraySource.java index d834a8888..f46dd8bf0 100644 --- a/pitest/src/test/java/org/pitest/util/ResourceFolderByteArraySource.java +++ b/pitest/src/test/java/org/pitest/util/ResourceFolderByteArraySource.java @@ -1,53 +1,50 @@ -package org.pitest.util; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; - -import org.pitest.classinfo.ClassByteArraySource; -import org.pitest.classpath.ClassPath; -import org.pitest.classpath.ClassPathRoot; -import java.util.Optional; - -public class ResourceFolderByteArraySource implements ClassByteArraySource { - - - @Override - public Optional getBytes(final String classname) { - final ClassPath cp = new ClassPath(new ResourceFolderClassPathroot()); - try { - return Optional.ofNullable(cp.getClassData(classname)); - } catch (final IOException ex) { - throw Unchecked.translateCheckedException(ex); - } - } - -} - -class ResourceFolderClassPathroot implements ClassPathRoot { - - @Override - public URL getResource(final String name) throws MalformedURLException { - return null; - } - - @Override - public InputStream getData(String name) throws IOException { - final String path = "sampleClasses/" + name.replace(".", "/") - + ".class.bin"; - return IsolationUtils.getContextClassLoader().getResourceAsStream(path); - } - - @Override - public Collection classNames() { - return null; - } - - @Override - public Optional cacheLocation() { - return null; - } - +package org.pitest.util; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collection; + +import org.pitest.classinfo.ClassByteArraySource; +import org.pitest.classpath.ClassPath; +import org.pitest.classpath.ClassPathRoot; +import java.util.Optional; + +public class ResourceFolderByteArraySource implements ClassByteArraySource { + @Override + public Optional getBytes(final String classname) { + final ClassPath cp = new ClassPath(new ResourceFolderClassPathroot()); + try { + return Optional.ofNullable(cp.getClassData(classname)); + } catch (final IOException ex) { + throw Unchecked.translateCheckedException(ex); + } + } + +} + +class ResourceFolderClassPathroot implements ClassPathRoot { + + @Override + public URL getResource(final String name) throws MalformedURLException { + return null; + } + + @Override + public InputStream getData(String name) throws IOException { + final String path = "sampleClasses/" + name.replace(".", "/") + ".class.bin"; + return IsolationUtils.getContextClassLoader().getResourceAsStream(path); + } + + @Override + public Collection classNames() { + return null; + } + + @Override + public Optional cacheLocation() { + return null; + } + } \ No newline at end of file diff --git a/pitest/src/test/java/org/pitest/util/SafeDataInputStreamTest.java b/pitest/src/test/java/org/pitest/util/SafeDataInputStreamTest.java index 88fb3ddf3..2e6373220 100644 --- a/pitest/src/test/java/org/pitest/util/SafeDataInputStreamTest.java +++ b/pitest/src/test/java/org/pitest/util/SafeDataInputStreamTest.java @@ -1,46 +1,46 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.Arrays; - -import org.junit.Test; - -public class SafeDataInputStreamTest { - - @Test - public void shouldBeAbletoReadLargeStrings() { - final char[] chars = new char[65536]; - Arrays.fill(chars, '!'); - final String s = new String(chars); - - final ByteArrayOutputStream o = new ByteArrayOutputStream(); - final SafeDataOutputStream dos = new SafeDataOutputStream(o); - dos.writeString(s); - - final ByteArrayInputStream i = new ByteArrayInputStream(o.toByteArray()); - - final SafeDataInputStream dis = new SafeDataInputStream(i); - final String actual = dis.readString(); - - assertEquals(s, actual); - - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; + +import org.junit.Test; + +public class SafeDataInputStreamTest { + + @Test + public void shouldBeAbletoReadLargeStrings() { + final char[] chars = new char[65536]; + Arrays.fill(chars, '!'); + final String s = new String(chars); + + final ByteArrayOutputStream o = new ByteArrayOutputStream(); + final SafeDataOutputStream dos = new SafeDataOutputStream(o); + dos.writeString(s); + + final ByteArrayInputStream i = new ByteArrayInputStream(o.toByteArray()); + + final SafeDataInputStream dis = new SafeDataInputStream(i); + final String actual = dis.readString(); + + assertEquals(s, actual); + + } + +} diff --git a/pitest/src/test/java/org/pitest/util/ServiceLoaderTest.java b/pitest/src/test/java/org/pitest/util/ServiceLoaderTest.java index 7a9b8a2b6..b2f7060dc 100644 --- a/pitest/src/test/java/org/pitest/util/ServiceLoaderTest.java +++ b/pitest/src/test/java/org/pitest/util/ServiceLoaderTest.java @@ -1,30 +1,30 @@ -package org.pitest.util; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.pitest.mutationtest.MutationEngineFactory; - -public class ServiceLoaderTest { - - public static interface AService { - - } - - @Test - public void shouldReturnNoValuesWhenNoServicesFounds() throws Exception { - final Iterable actual = ServiceLoader.load(AService.class, Thread - .currentThread().getContextClassLoader()); - assertFalse(actual.iterator().hasNext()); - } - - @Test - public void shouldReturnValueWhenServiceFound() throws Exception { - final Iterable actual = ServiceLoader.load( - MutationEngineFactory.class, Thread.currentThread() - .getContextClassLoader()); - assertTrue(actual.iterator().hasNext()); - } - -} +package org.pitest.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.pitest.mutationtest.MutationEngineFactory; + +public class ServiceLoaderTest { + + public static interface AService { + + } + + @Test + public void shouldReturnNoValuesWhenNoServicesFounds() throws Exception { + final Iterable actual = ServiceLoader.load(AService.class, Thread + .currentThread().getContextClassLoader()); + assertFalse(actual.iterator().hasNext()); + } + + @Test + public void shouldReturnValueWhenServiceFound() throws Exception { + final Iterable actual = ServiceLoader.load( + MutationEngineFactory.class, Thread.currentThread() + .getContextClassLoader()); + assertTrue(actual.iterator().hasNext()); + } + +} diff --git a/pitest/src/test/java/org/pitest/util/StreamUtilTest.java b/pitest/src/test/java/org/pitest/util/StreamUtilTest.java index 2e7fa7353..e93b3f729 100644 --- a/pitest/src/test/java/org/pitest/util/StreamUtilTest.java +++ b/pitest/src/test/java/org/pitest/util/StreamUtilTest.java @@ -1,35 +1,35 @@ -package org.pitest.util; - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; - -public class StreamUtilTest { - - @Test - public void shouldCopyStreamsToByteArrays() throws IOException { - final byte[] expected = createByteArray(); - final ByteArrayInputStream bis = new ByteArrayInputStream(expected); - final byte[] actual = StreamUtil.streamToByteArray(bis); - assertArrayEquals(expected, actual); - } - - private byte[] createByteArray() { - final byte[] expected = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0xA }; - return expected; - } - - @Test - public void shouldCopyContentsOfOneInputStreamToAnother() throws IOException { - final byte[] expected = createByteArray(); - final InputStream actualStream = StreamUtil - .copyStream(new ByteArrayInputStream(createByteArray())); - final byte[] actualContents = StreamUtil.streamToByteArray(actualStream); - assertArrayEquals(expected, actualContents); - } - -} +package org.pitest.util; + +import static org.junit.Assert.assertArrayEquals; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; + +public class StreamUtilTest { + + @Test + public void shouldCopyStreamsToByteArrays() throws IOException { + final byte[] expected = createByteArray(); + final ByteArrayInputStream bis = new ByteArrayInputStream(expected); + final byte[] actual = StreamUtil.streamToByteArray(bis); + assertArrayEquals(expected, actual); + } + + private byte[] createByteArray() { + final byte[] expected = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0xA }; + return expected; + } + + @Test + public void shouldCopyContentsOfOneInputStreamToAnother() throws IOException { + final byte[] expected = createByteArray(); + final InputStream actualStream = StreamUtil + .copyStream(new ByteArrayInputStream(createByteArray())); + final byte[] actualContents = StreamUtil.streamToByteArray(actualStream); + assertArrayEquals(expected, actualContents); + } + +} diff --git a/pitest/src/test/java/org/pitest/util/StringUtilTest.java b/pitest/src/test/java/org/pitest/util/StringUtilTest.java index fa62b82b2..49b4df2c6 100644 --- a/pitest/src/test/java/org/pitest/util/StringUtilTest.java +++ b/pitest/src/test/java/org/pitest/util/StringUtilTest.java @@ -1,47 +1,47 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package org.pitest.util; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Test; - -public class StringUtilTest { - - @Test - public void shouldCreateEmptyStringWhenJoiningEmptyList() { - assertEquals("", StringUtil.join(Collections. emptyList(), ",")); - } - - @Test - public void shouldIncludeNoSeparatorsWhenJoiningSingleItem() { - assertEquals("foo", StringUtil.join(Collections.singleton("foo"), ",")); - } - - @Test - public void shouldJoinStringWithSeparators() { - assertEquals("foo,bar,car", - StringUtil.join(Arrays.asList("foo", "bar", "car"), ",")); - } - - @Test - public void repeatShouldRepeatGivenCharacter() { - assertEquals("----", StringUtil.repeat('-', 4)); - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.util; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; + +public class StringUtilTest { + + @Test + public void shouldCreateEmptyStringWhenJoiningEmptyList() { + assertEquals("", StringUtil.join(Collections. emptyList(), ",")); + } + + @Test + public void shouldIncludeNoSeparatorsWhenJoiningSingleItem() { + assertEquals("foo", StringUtil.join(Collections.singleton("foo"), ",")); + } + + @Test + public void shouldJoinStringWithSeparators() { + assertEquals("foo,bar,car", + StringUtil.join(Arrays.asList("foo", "bar", "car"), ",")); + } + + @Test + public void repeatShouldRepeatGivenCharacter() { + assertEquals("----", StringUtil.repeat('-', 4)); + } + +} diff --git a/pitest/src/test/java/org/pitest/util/XStreamCloning.java b/pitest/src/test/java/org/pitest/util/XStreamCloning.java index eea891ef1..134d26104 100644 --- a/pitest/src/test/java/org/pitest/util/XStreamCloning.java +++ b/pitest/src/test/java/org/pitest/util/XStreamCloning.java @@ -1,81 +1,81 @@ -package org.pitest.util; - -import static org.pitest.util.Unchecked.translateCheckedException; - -import java.io.StringWriter; -import java.io.Writer; -import java.util.WeakHashMap; - -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.io.xml.CompactWriter; - -public class XStreamCloning { - - private static final XStream XSTREAM_INSTANCE = new XStream( - new PitXmlDriver()); - private static final WeakHashMap CACHE = new WeakHashMap<>(); - - - public static Object cloneForLoader(final Object o, final ClassLoader loader) { - try { - final String xml = toXml(o); - final XStream foreignXstream = getXStreamForLoader(loader); - return foreignXstream.fromXML(xml); - } catch (final Exception ex) { - throw translateCheckedException(ex); - } - - } - - private static XStream getXStreamForLoader(final ClassLoader loader) { - XStream foreginXstream = CACHE.get(loader); - if (foreginXstream == null) { - foreginXstream = new XStream(new PitXmlDriver()); - foreginXstream.setClassLoader(loader); - // possible that more than one instance will be created - // per loader, but probably better than synchronizing the whole method - synchronized (CACHE) { - CACHE.put(loader, foreginXstream); - } - } - return foreginXstream; - } - - public static Class convertForClassLoader(final ClassLoader loader, - final String name) { - try { - return Class.forName(name, false, loader); - } catch (final ClassNotFoundException ex) { - throw translateCheckedException(ex); - } - } - - public static Class convertForClassLoader(final ClassLoader loader, - final Class clazz) { - if (clazz.getClassLoader() != loader) { - return convertForClassLoader(loader, clazz.getName()); - } else { - return clazz; - } - - } - - public static String toXml(final Object o) { - final Writer writer = new StringWriter(); - XSTREAM_INSTANCE.marshal(o, new CompactWriter(writer)); - - return writer.toString(); - } - - public static Object fromXml(final String xml) { - return XSTREAM_INSTANCE.fromXML(xml); - } - - public static Object clone(final Object object) { - return cloneForLoader(object, IsolationUtils.getContextClassLoader()); - } - - public static ClassLoader bootClassLoader() { - return Object.class.getClassLoader(); - } -} +package org.pitest.util; + +import static org.pitest.util.Unchecked.translateCheckedException; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.WeakHashMap; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.io.xml.CompactWriter; + +public class XStreamCloning { + + private static final XStream XSTREAM_INSTANCE = new XStream( + new PitXmlDriver()); + private static final WeakHashMap CACHE = new WeakHashMap<>(); + + + public static Object cloneForLoader(final Object o, final ClassLoader loader) { + try { + final String xml = toXml(o); + final XStream foreignXstream = getXStreamForLoader(loader); + return foreignXstream.fromXML(xml); + } catch (final Exception ex) { + throw translateCheckedException(ex); + } + + } + + private static XStream getXStreamForLoader(final ClassLoader loader) { + XStream foreginXstream = CACHE.get(loader); + if (foreginXstream == null) { + foreginXstream = new XStream(new PitXmlDriver()); + foreginXstream.setClassLoader(loader); + // possible that more than one instance will be created + // per loader, but probably better than synchronizing the whole method + synchronized (CACHE) { + CACHE.put(loader, foreginXstream); + } + } + return foreginXstream; + } + + public static Class convertForClassLoader(final ClassLoader loader, + final String name) { + try { + return Class.forName(name, false, loader); + } catch (final ClassNotFoundException ex) { + throw translateCheckedException(ex); + } + } + + public static Class convertForClassLoader(final ClassLoader loader, + final Class clazz) { + if (clazz.getClassLoader() != loader) { + return convertForClassLoader(loader, clazz.getName()); + } else { + return clazz; + } + + } + + public static String toXml(final Object o) { + final Writer writer = new StringWriter(); + XSTREAM_INSTANCE.marshal(o, new CompactWriter(writer)); + + return writer.toString(); + } + + public static Object fromXml(final String xml) { + return XSTREAM_INSTANCE.fromXML(xml); + } + + public static Object clone(final Object object) { + return cloneForLoader(object, IsolationUtils.getContextClassLoader()); + } + + public static ClassLoader bootClassLoader() { + return Object.class.getClassLoader(); + } +} diff --git a/pitest/src/test/java/sun/pitest/CodeCoverageStoreTest.java b/pitest/src/test/java/sun/pitest/CodeCoverageStoreTest.java index b27dec122..2c27bfe3f 100644 --- a/pitest/src/test/java/sun/pitest/CodeCoverageStoreTest.java +++ b/pitest/src/test/java/sun/pitest/CodeCoverageStoreTest.java @@ -1,340 +1,340 @@ -/* - * Copyright 2011 Henry Coles - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http:www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - */ -package sun.pitest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.verify; - -import java.util.Collection; -import java.util.Collections; -import java.util.ConcurrentModificationException; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.pitest.functional.SideEffect2; - -public class CodeCoverageStoreTest { - - @Mock - private InvokeReceiver receiver; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - CodeCoverageStore.init(this.receiver); - } - - @After - public void cleanUp() { - CodeCoverageStore.resetAllStaticState(); - } - - @Test - public void shouldRegisterNewClassesWithReceiver() { - final int id = CodeCoverageStore.registerClass("Foo"); - verify(this.receiver).registerClass(id, "Foo"); - } - - @Test - public void shouldGenerateNewClassIdForEachClass() { - final int id = CodeCoverageStore.registerClass("Foo"); - final int id2 = CodeCoverageStore.registerClass("Bar"); - assertFalse(id == id2); - } - - @Test - public void shouldCodeAndEncodeWhenClassIdAndLineNumberAreAtMaximum() { - final long value = CodeCoverageStore.encode(Integer.MAX_VALUE, - Integer.MAX_VALUE); - assertEquals(Integer.MAX_VALUE, CodeCoverageStore.decodeClassId(value)); - assertEquals(Integer.MAX_VALUE, CodeCoverageStore.decodeLineId(value)); - } - - @Test - public void shouldCodeAndEncodeWhenClassIdAndLineNumberAreAtMinimum() { - final long value = CodeCoverageStore.encode(Integer.MIN_VALUE, 0); - assertEquals(Integer.MIN_VALUE, CodeCoverageStore.decodeClassId(value)); - assertEquals(0, CodeCoverageStore.decodeLineId(value)); - } - - @Test - public void shouldCodeAndEncodeWhenClassIdAndLineNumberAreZero() { - final long value = CodeCoverageStore.encode(0, 0); - assertEquals(0, CodeCoverageStore.decodeClassId(value)); - assertEquals(0, CodeCoverageStore.decodeLineId(value)); - } - - @Test - public void shouldClearHitCountersWhenReset() { - final int classId = CodeCoverageStore.registerClass("foo"); - CodeCoverageStore.registerClassProbes(classId, 1); - - CodeCoverageStore.visitProbes(classId, 0, new boolean[] { true }); - CodeCoverageStore.reset(); - - final Collection actual = CodeCoverageStore.getHits(); - assertEquals(Collections.emptyList(), actual); - } - - @Test - public void shouldBeSafeToAccessAcrossMultipleThreads() - throws InterruptedException, ExecutionException { - - CodeCoverageStore.registerClass("foo"); - CodeCoverageStore.registerClassProbes(0, 1); - - final Callable read = makeReader(); - - final ExecutorService pool = Executors.newFixedThreadPool(13); - for (int i = 1; i != 13; i++) { - pool.submit(makeWriter(i)); - } - final Future future = pool.submit(read); - pool.shutdown(); - - assertNull(future.get()); - - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation1() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0]); - assertLineCombinations(1, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation2() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1]); - assertLineCombinations(2, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation3() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2]); - assertLineCombinations(3, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation4() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3]); - assertLineCombinations(4, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation5() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4]); - assertLineCombinations(5, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation6() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5]); - assertLineCombinations(6, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation7() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6]); - assertLineCombinations(7, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation8() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6], probes[7]); - assertLineCombinations(8, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation9() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], - probes[8]); - assertLineCombinations(9, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation10() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], - probes[8], probes[9]); - assertLineCombinations(10, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation11() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], - probes[8], probes[9], probes[10]); - assertLineCombinations(11, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation12() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], - probes[8], probes[9], probes[10], probes[11]); - assertLineCombinations(12, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation13() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], - probes[8], probes[9], probes[10], probes[11], probes[12]); - assertLineCombinations(13, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation14() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], - probes[8], probes[9], probes[10], probes[11], probes[12], - probes[13]); - assertLineCombinations(14, se); - } - - @Test - public void shouldReportCorrectCoverageForSpecialisation15() { - final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], - probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], - probes[8], probes[9], probes[10], probes[11], probes[12], - probes[13], probes[14]); - assertLineCombinations(15, se); - } - - private void assertLineCombinations(final int size, - final SideEffect2 function) { - ascendingPermuation(size, function); - CodeCoverageStore.resetAllStaticState(); - descendingPermutation(size, function); - } - - private void ascendingPermuation(final int size, - final SideEffect2 function) { - final int classId = CodeCoverageStore.registerClass("foo"); - CodeCoverageStore.registerClassProbes(classId, 15); - final boolean[] probes = new boolean[size]; - - function.apply(classId, probes); - assertDoesNotHitLine(classId, 1, 2, 3); - - for (int i = 0; i != probes.length; i++) { - probes[i] = true; - function.apply(classId, probes); - for (int j = 0; j <= i; j++) { - assertHitsLine(classId, j); - } - for (int j = i + 1; j != probes.length; j++) { - assertDoesNotHitLine(classId, j); - } - } - } - - private void descendingPermutation(final int size, - final SideEffect2 function) { - final int classId = CodeCoverageStore.registerClass("foo"); - CodeCoverageStore.registerClassProbes(classId, 15); - final boolean[] probes = new boolean[size]; - - for (int i = probes.length - 1; i != 0; i--) { - probes[i] = true; - function.apply(classId, probes); - for (int j = 0; j != i; j++) { - assertDoesNotHitLine(classId, j); - } - for (int j = probes.length; j != i; j--) { - assertHitsLine(classId, j - 1); - } - } - } - - private void assertHitsLine(final int classId, final int... i) { - final Collection actual = CodeCoverageStore.getHits(); - for (final int probe : i) { - assertThat(actual).contains(CodeCoverageStore.encode(classId, probe)); - } - } - - private void assertDoesNotHitLine(final int classId, final int... i) { - final Collection actual = CodeCoverageStore.getHits(); - for (final int probe : i) { - assertThat(actual).doesNotContain( - CodeCoverageStore.encode(classId, probe)); - } - } - - private Callable makeReader() { - final Callable read = new Callable() { - @Override - public ConcurrentModificationException call() throws Exception { - ConcurrentModificationException error = null; - try { - pointlesslyIterateCollection(); - pointlesslyIterateCollection(); - pointlesslyIterateCollection(); - } catch (final ConcurrentModificationException ex) { - error = ex; - } - return error; - } - - private long pointlesslyIterateCollection() { - long total = 0; - for (final Long i : CodeCoverageStore.getHits()) { - total += i; - try { - Thread.sleep(5); - } catch (final InterruptedException e) { - - } - } - return total; - } - }; - return read; - } - - private static Runnable makeWriter(final int sleepPeriod) { - final Runnable write = () -> { - for (int i = 0; i != 1000; i++) { - try { - Thread.sleep(sleepPeriod); - } catch (final InterruptedException e) { - } - final boolean b[] = new boolean[1000]; - CodeCoverageStore.visitProbes(0, 0, b); - } - }; - return write; - } - -} +/* + * Copyright 2011 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http:www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package sun.pitest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.verify; + +import java.util.Collection; +import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.pitest.functional.SideEffect2; + +public class CodeCoverageStoreTest { + + @Mock + private InvokeReceiver receiver; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + CodeCoverageStore.init(this.receiver); + } + + @After + public void cleanUp() { + CodeCoverageStore.resetAllStaticState(); + } + + @Test + public void shouldRegisterNewClassesWithReceiver() { + final int id = CodeCoverageStore.registerClass("Foo"); + verify(this.receiver).registerClass(id, "Foo"); + } + + @Test + public void shouldGenerateNewClassIdForEachClass() { + final int id = CodeCoverageStore.registerClass("Foo"); + final int id2 = CodeCoverageStore.registerClass("Bar"); + assertFalse(id == id2); + } + + @Test + public void shouldCodeAndEncodeWhenClassIdAndLineNumberAreAtMaximum() { + final long value = CodeCoverageStore.encode(Integer.MAX_VALUE, + Integer.MAX_VALUE); + assertEquals(Integer.MAX_VALUE, CodeCoverageStore.decodeClassId(value)); + assertEquals(Integer.MAX_VALUE, CodeCoverageStore.decodeLineId(value)); + } + + @Test + public void shouldCodeAndEncodeWhenClassIdAndLineNumberAreAtMinimum() { + final long value = CodeCoverageStore.encode(Integer.MIN_VALUE, 0); + assertEquals(Integer.MIN_VALUE, CodeCoverageStore.decodeClassId(value)); + assertEquals(0, CodeCoverageStore.decodeLineId(value)); + } + + @Test + public void shouldCodeAndEncodeWhenClassIdAndLineNumberAreZero() { + final long value = CodeCoverageStore.encode(0, 0); + assertEquals(0, CodeCoverageStore.decodeClassId(value)); + assertEquals(0, CodeCoverageStore.decodeLineId(value)); + } + + @Test + public void shouldClearHitCountersWhenReset() { + final int classId = CodeCoverageStore.registerClass("foo"); + CodeCoverageStore.registerClassProbes(classId, 1); + + CodeCoverageStore.visitProbes(classId, 0, new boolean[] { true }); + CodeCoverageStore.reset(); + + final Collection actual = CodeCoverageStore.getHits(); + assertEquals(Collections.emptyList(), actual); + } + + @Test + public void shouldBeSafeToAccessAcrossMultipleThreads() + throws InterruptedException, ExecutionException { + + CodeCoverageStore.registerClass("foo"); + CodeCoverageStore.registerClassProbes(0, 1); + + final Callable read = makeReader(); + + final ExecutorService pool = Executors.newFixedThreadPool(13); + for (int i = 1; i != 13; i++) { + pool.submit(makeWriter(i)); + } + final Future future = pool.submit(read); + pool.shutdown(); + + assertNull(future.get()); + + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation1() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0]); + assertLineCombinations(1, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation2() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1]); + assertLineCombinations(2, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation3() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2]); + assertLineCombinations(3, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation4() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3]); + assertLineCombinations(4, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation5() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4]); + assertLineCombinations(5, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation6() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5]); + assertLineCombinations(6, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation7() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6]); + assertLineCombinations(7, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation8() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6], probes[7]); + assertLineCombinations(8, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation9() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], + probes[8]); + assertLineCombinations(9, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation10() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], + probes[8], probes[9]); + assertLineCombinations(10, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation11() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], + probes[8], probes[9], probes[10]); + assertLineCombinations(11, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation12() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], + probes[8], probes[9], probes[10], probes[11]); + assertLineCombinations(12, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation13() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], + probes[8], probes[9], probes[10], probes[11], probes[12]); + assertLineCombinations(13, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation14() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], + probes[8], probes[9], probes[10], probes[11], probes[12], + probes[13]); + assertLineCombinations(14, se); + } + + @Test + public void shouldReportCorrectCoverageForSpecialisation15() { + final SideEffect2 se = (classId, probes) -> CodeCoverageStore.visitProbes(classId, 0, probes[0], probes[1], + probes[2], probes[3], probes[4], probes[5], probes[6], probes[7], + probes[8], probes[9], probes[10], probes[11], probes[12], + probes[13], probes[14]); + assertLineCombinations(15, se); + } + + private void assertLineCombinations(final int size, + final SideEffect2 function) { + ascendingPermuation(size, function); + CodeCoverageStore.resetAllStaticState(); + descendingPermutation(size, function); + } + + private void ascendingPermuation(final int size, + final SideEffect2 function) { + final int classId = CodeCoverageStore.registerClass("foo"); + CodeCoverageStore.registerClassProbes(classId, 15); + final boolean[] probes = new boolean[size]; + + function.apply(classId, probes); + assertDoesNotHitLine(classId, 1, 2, 3); + + for (int i = 0; i != probes.length; i++) { + probes[i] = true; + function.apply(classId, probes); + for (int j = 0; j <= i; j++) { + assertHitsLine(classId, j); + } + for (int j = i + 1; j != probes.length; j++) { + assertDoesNotHitLine(classId, j); + } + } + } + + private void descendingPermutation(final int size, + final SideEffect2 function) { + final int classId = CodeCoverageStore.registerClass("foo"); + CodeCoverageStore.registerClassProbes(classId, 15); + final boolean[] probes = new boolean[size]; + + for (int i = probes.length - 1; i != 0; i--) { + probes[i] = true; + function.apply(classId, probes); + for (int j = 0; j != i; j++) { + assertDoesNotHitLine(classId, j); + } + for (int j = probes.length; j != i; j--) { + assertHitsLine(classId, j - 1); + } + } + } + + private void assertHitsLine(final int classId, final int... i) { + final Collection actual = CodeCoverageStore.getHits(); + for (final int probe : i) { + assertThat(actual).contains(CodeCoverageStore.encode(classId, probe)); + } + } + + private void assertDoesNotHitLine(final int classId, final int... i) { + final Collection actual = CodeCoverageStore.getHits(); + for (final int probe : i) { + assertThat(actual).doesNotContain( + CodeCoverageStore.encode(classId, probe)); + } + } + + private Callable makeReader() { + final Callable read = new Callable() { + @Override + public ConcurrentModificationException call() throws Exception { + ConcurrentModificationException error = null; + try { + pointlesslyIterateCollection(); + pointlesslyIterateCollection(); + pointlesslyIterateCollection(); + } catch (final ConcurrentModificationException ex) { + error = ex; + } + return error; + } + + private long pointlesslyIterateCollection() { + long total = 0; + for (final Long i : CodeCoverageStore.getHits()) { + total += i; + try { + Thread.sleep(5); + } catch (final InterruptedException e) { + + } + } + return total; + } + }; + return read; + } + + private static Runnable makeWriter(final int sleepPeriod) { + final Runnable write = () -> { + for (int i = 0; i != 1000; i++) { + try { + Thread.sleep(sleepPeriod); + } catch (final InterruptedException e) { + } + final boolean b[] = new boolean[1000]; + CodeCoverageStore.visitProbes(0, 0, b); + } + }; + return write; + } + +} diff --git a/pom.xml b/pom.xml index 232386265..3dbbd74bc 100644 --- a/pom.xml +++ b/pom.xml @@ -1,307 +1,307 @@ - - - 4.0.0 - org.pitest - - org.pitest - - pitest-parent - pom - 1.4.0-SNAPSHOT - pitest-parent - http://pitest.org - Mutation testing system for java - parent project - - https://github.com/hcoles/pitest - scm:git:git@github.com:hcoles/pitest.git - scm:git:git@github.com:hcoles/pitest.git - HEAD - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - https://github.com/hcoles/pitest/issues - GitHub - - - - - henry - Henry Coles - henry@pitest.org - - - - - - Marvin H Froeder - velo dot br at gmail dot com - about.me/velo - - - Rahul Gopinath - rahul@gopinath.org - http://rahul.gopinath.org - - - Artem Khvastunov - contact@artspb.me - https://artspb.me - - - - - pitest-build-config - pitest - pitest-entry - pitest-maven - pitest-ant - pitest-command-line - pitest-html-report - pitest-maven-verification - pitest-aggregator - pitest-java8-verification - - - - 3 - - - - - java8 - - - 1.8 - - - pitest-groovy-verification - - - - release-sign-artifacts - - - performRelease - true - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - - - - - - - - - - junit - junit - ${junit.version} - test - - - org.mockito - mockito-all - 1.9.5 - test - - - org.assertj - assertj-core - 3.9.0 - test - - - org.pitest.quickbuilder - quickbuilder - 1.2 - test - - - - - - - - - - maven-release-plugin - 2.4.2 - - - org.apache.maven.scm - maven-scm-provider-gitexe - 1.9.4 - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.15 - - - org.pitest - pitest-build-config - 1.4.0-SNAPSHOT - - - - - checkstyle - validate - - check - - - true - pitest/checkstyle.xml - ${project.build.sourceDirectory} - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire-plugin.version} - - - org.apache.maven.surefire - surefire-junit47 - ${maven.surefire-plugin.version} - - - - none:none - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven.failsafe-plugin.version} - - - org.apache.maven.surefire - surefire-junit47 - ${maven.surefire-plugin.version} - - - - - org.apache.maven.plugins - maven-source-plugin - 3.0.1 - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - org.apache.maven.plugins - maven-shade-plugin - 3.1.0 - - - org.apache.maven.plugins - maven-clean-plugin - 2.5 - - - org.apache.maven.plugins - maven-install-plugin - 2.5.1 - - - org.apache.maven.plugins - maven-resources-plugin - 2.6 - - - org.apache.maven.plugins - maven-site-plugin - 3.3 - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8 - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.0.0-M1 - - - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - UTF-8 - UTF-8 - - 6.0 - 1.9.4 - 1.3 - 4.11 - 1.5 - 2.2.1 - 1.7.3 - 2.17 - 6.8.21 - 1.7.12 - - ${surefire.version} - ${surefire.version} - - - + + + 4.0.0 + org.pitest + + org.pitest + + pitest-parent + pom + 1.4.0-SNAPSHOT + pitest-parent + http://pitest.org + Mutation testing system for java - parent project + + https://github.com/hcoles/pitest + scm:git:git@github.com:hcoles/pitest.git + scm:git:git@github.com:hcoles/pitest.git + HEAD + + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + https://github.com/hcoles/pitest/issues + GitHub + + + + + henry + Henry Coles + henry@pitest.org + + + + + + Marvin H Froeder + velo dot br at gmail dot com + about.me/velo + + + Rahul Gopinath + rahul@gopinath.org + http://rahul.gopinath.org + + + Artem Khvastunov + contact@artspb.me + https://artspb.me + + + + + pitest-build-config + pitest + pitest-entry + pitest-maven + pitest-ant + pitest-command-line + pitest-html-report + pitest-maven-verification + pitest-aggregator + pitest-java8-verification + + + + 3 + + + + + java8 + + + 1.8 + + + pitest-groovy-verification + + + + release-sign-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + + junit + junit + ${junit.version} + test + + + org.mockito + mockito-all + 1.9.5 + test + + + org.assertj + assertj-core + 3.9.0 + test + + + org.pitest.quickbuilder + quickbuilder + 1.2 + test + + + + + + + + + + maven-release-plugin + 2.4.2 + + + org.apache.maven.scm + maven-scm-provider-gitexe + 1.9.4 + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.15 + + + org.pitest + pitest-build-config + 1.4.0-SNAPSHOT + + + + + checkstyle + validate + + check + + + true + pitest/checkstyle.xml + ${project.build.sourceDirectory} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire-plugin.version} + + + org.apache.maven.surefire + surefire-junit47 + ${maven.surefire-plugin.version} + + + + none:none + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${maven.failsafe-plugin.version} + + + org.apache.maven.surefire + surefire-junit47 + ${maven.surefire-plugin.version} + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + org.apache.maven.plugins + maven-clean-plugin + 2.5 + + + org.apache.maven.plugins + maven-install-plugin + 2.5.1 + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + + org.apache.maven.plugins + maven-site-plugin + 3.3 + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8 + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.0.0-M1 + + + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + UTF-8 + UTF-8 + + 6.0 + 1.9.4 + 1.3 + 4.11 + 1.5 + 2.2.1 + 1.7.3 + 2.17 + 6.8.21 + 1.7.12 + + ${surefire.version} + ${surefire.version} + + + diff --git a/prepare_release.sh b/prepare_release.sh index 0c997041e..df094b739 100755 --- a/prepare_release.sh +++ b/prepare_release.sh @@ -1 +1 @@ -mvn -e -DpreparationGoals=clean release:prepare +mvn -e -DpreparationGoals=clean release:prepare diff --git a/so_you_want_to_build_mutation_testing_system.md b/so_you_want_to_build_mutation_testing_system.md index aec91a6f0..979b7da28 100644 --- a/so_you_want_to_build_mutation_testing_system.md +++ b/so_you_want_to_build_mutation_testing_system.md @@ -2,11 +2,11 @@ ## Introduction -There have been a lot mutation testing systems, but very few have them have seen succesful use in industry. +There have been a lot mutation testing systems, but very few have them have seen succesfull use in industry. This document is a set of notes that might be helpful for anyone thinking of implementing a mutation testing system for another language. -It represents some of the things we learnt while creating pitest. The choices made by pitest are not necessarily the best choices for your system. Some of these choices are appropriate only because of the particular quirks of Java and the JVM, and some of them are simply the first idea that we had. +It represents some of the things we learnt while creating pitest. The choices made by pitest are not neccessarily the best choices for your system. Some of these choices are appropriate only because of the particular quirks of Java and the JVM, and some of them are simply the first idea that we had. ## Things to consider @@ -175,5 +175,3 @@ Schmeta have some nice properties 3. A single linked binary can contain all mutants But will result in large classes - you may hit language limits. - -