├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── groovy │ └── com │ │ └── blogspot │ │ └── toomuchcoding │ │ └── testprofiler │ │ ├── AddTimeoutTask.groovy │ │ ├── BuildBreaker.groovy │ │ ├── DefaultTestExecutionComparator.groovy │ │ ├── ExtensionCreator.groovy │ │ ├── LoggerProxy.groovy │ │ ├── NoOpTask.groovy │ │ ├── ReportMergerTask.groovy │ │ ├── ReportRow.groovy │ │ ├── ReportStorerTask.groovy │ │ ├── TaskCreator.groovy │ │ ├── TestClassesModifier.groovy │ │ ├── TestExecutionResult.groovy │ │ ├── TestExecutionResultSavingTestListener.groovy │ │ ├── TestProfilerPlugin.groovy │ │ ├── TestProfilerPluginExtension.groovy │ │ ├── TestTaskBasedGroovyClassLoader.groovy │ │ └── TestTaskModifier.groovy └── java │ └── com │ └── blogspot │ └── toomuchcoding │ └── testprofiler │ └── spock │ ├── CustomTimeout.java │ └── GlobalTimeoutExtension.java └── test ├── groovy ├── com │ └── blogspot │ │ └── toomuchcoding │ │ └── testprofiler │ │ ├── TaskCreatorSpec.groovy │ │ └── TestExecutionResultSavingTestListenerSpec.groovy └── integration │ ├── BasicFuncSpec.groovy │ └── TimeoutFuncSpec.groovy └── resources ├── META-INF └── gradle-plugins │ └── com.blogspot.toomuchcoding.testprofiler.properties ├── multimodule_project_with_disabled_plugin ├── build.gradle ├── module1 │ └── src │ │ ├── main │ │ └── java │ │ │ └── foo │ │ │ └── Calculator.java │ │ └── test │ │ └── java │ │ └── foo │ │ └── CalculatorTest.java ├── module2 │ ├── build.gradle │ └── src │ │ ├── main │ │ └── java │ │ │ └── foo │ │ │ └── Calculator.java │ │ └── test │ │ └── java │ │ └── foo │ │ └── CalculatorTest.java └── settings.gradle ├── multimodule_project_without_timeout ├── build.gradle ├── module1 │ └── src │ │ ├── main │ │ └── java │ │ │ └── foo │ │ │ └── Calculator.java │ │ └── test │ │ └── java │ │ └── foo │ │ └── CalculatorTest.java ├── module2 │ └── src │ │ ├── main │ │ └── java │ │ │ └── foo │ │ │ └── Calculator.java │ │ └── test │ │ └── java │ │ └── foo │ │ └── CalculatorTest.java └── settings.gradle ├── project_with_disabled_plugin ├── build.gradle └── src │ ├── main │ └── java │ │ └── foo │ │ └── Calculator.java │ └── test │ ├── groovy │ └── foo │ │ └── CalculatorWithoutTimeoutSpec.groovy │ └── java │ └── foo │ └── CalculatorTest.java ├── project_with_multiple_timeouts ├── build.gradle └── src │ └── test │ └── java │ └── foo │ ├── AbstractTest.java │ └── TestWithThreeTimeoutsShould.java ├── project_with_plugin_applied_before_java ├── build.gradle └── src │ ├── main │ └── java │ │ └── foo │ │ └── Calculator.java │ └── test │ └── java │ └── foo │ └── CalculatorTest.java ├── project_with_timeout ├── build.gradle └── src │ └── test │ ├── groovy │ └── foo │ │ └── CalculatorSpec.groovy │ └── java │ └── foo │ └── CalculatorTest.java ├── project_with_timeout_with_regexp ├── build.gradle └── src │ └── test │ ├── groovy │ └── foo │ │ └── CalculatorSpec.groovy │ └── java │ └── foo │ └── CalculatorTest.java ├── project_with_timeout_with_regexp_spock_1 ├── build.gradle └── src │ └── test │ ├── groovy │ └── foo │ │ └── CalculatorSpec.groovy │ └── java │ └── foo │ └── CalculatorTest.java ├── project_with_timeout_with_spock_1 ├── build.gradle └── src │ └── test │ ├── groovy │ └── foo │ │ └── CalculatorSpec.groovy │ └── java │ └── foo │ └── CalculatorTest.java └── project_without_timeout ├── build.gradle └── src ├── main └── java │ └── foo │ └── Calculator.java └── test ├── groovy └── foo │ └── CalculatorWithoutTimeoutSpec.groovy └── java └── foo └── CalculatorTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | build 4 | /bin 5 | .gradle 6 | .poject 7 | .settings 8 | .classpath 9 | commitHash.txt 10 | logs 11 | .log 12 | .zip 13 | /out 14 | *~ 15 | 16 | atlassian-ide-plugin.xml -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: groovy 4 | 5 | jdk: 6 | - oraclejdk7 7 | - oraclejdk8 8 | 9 | cache: 10 | directories: 11 | - $HOME/.gradle 12 | - $HOME/.m2 13 | 14 | env: 15 | - GRADLE_VERSION=2.3 16 | - GRADLE_VERSION=2.4 17 | - GRADLE_VERSION=2.5 18 | 19 | before_install: 20 | - echo -e "\ndistributionUrl=http\://services.gradle.org/distributions/gradle-$GRADLE_VERSION-bin.zip" >> gradle/wrapper/gradle-wrapper.properties 21 | - cat gradle/wrapper/gradle-wrapper.properties 22 | 23 | script: 24 | - ./gradlew clean build 25 | 26 | after_success: 27 | - ./gradlew test jacocoTestReport coveralls -Pcoverage -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/marcingrzejszczak/gradle-test-profiler.svg)](https://travis-ci.org/marcingrzejszczak/gradle-test-profiler) 2 | [ ![Download](https://api.bintray.com/packages/marcingrzejszczak/com-blogspot-toomuchcoding/gradle-test-profiler/images/download.svg) ](https://bintray.com/marcingrzejszczak/com-blogspot-toomuchcoding/gradle-test-profiler/_latestVersion) 3 | [![Coverage Status](https://coveralls.io/repos/marcingrzejszczak/gradle-test-profiler/badge.svg)](https://coveralls.io/r/marcingrzejszczak/gradle-test-profiler) 4 | 5 | # gradle-test-profiler 6 | 7 | Created with @AChudzik 8 | 9 | The idea of this plugin is to perform profiling of your tests. You will be able to see your test 10 | execution times sorted in the descending manner together with an information about a module 11 | and the class name from which the test was executed. 12 | 13 | ## Since version 0.1.0 14 | 15 | ### How to add it 16 | 17 | You have to add `jcenter` to buildscript repositories 18 | 19 | ``` 20 | 21 | buildscript { 22 | repositories { 23 | jcenter() 24 | } 25 | dependencies { 26 | classpath 'com.blogspot.toomuchcoding:gradle-test-profiler:0.3.2' 27 | } 28 | } 29 | 30 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 31 | 32 | ``` 33 | 34 | ### How to run it 35 | 36 | It's enough to execute 37 | 38 | ``` 39 | ./gradlew clean build profileTests 40 | 41 | ``` 42 | 43 | It's important run both *build* and *profileTests* 44 | 45 | ### How does it work 46 | 47 | What this plugin does is: 48 | 49 | - adds TestExecutionListener that 50 | - prints out the time of execution of a test 51 | - creates a report for each module with sorted test execution data 52 | - if `maxThreshold` is passed: 53 | - manipulates the bytcode of tests by adding a JUnit Timeout Rule 54 | - for Spock adds GlobalExtension that times out the tests if needed 55 | - the `profileTests` task merges all the per-module sorted test execution data into one 56 | 57 | 58 | ### How to configure it 59 | 60 | You have a special section called `testprofiler` 61 | 62 | ``` 63 | testprofiler { 64 | 65 | /** 66 | * Should TestProfilerPlugin be enabled? If set to false there will be no modification of any Gradle Test classes 67 | * and the task will simply print a message 68 | */ 69 | enabled = true 70 | 71 | /** 72 | * Separator of columns in the output report 73 | */ 74 | separator = ';' 75 | 76 | /** 77 | * Headers in the report 78 | */ 79 | outputReportHeaders = "module${separator}test class name${separator}test name${separator}test execution time in [s]${separator}test class execution time in [s]\n" 80 | 81 | /** 82 | * Closure that will be converted to a Comparator to compare row entries 83 | */ 84 | comparator = DefaultTestExecutionComparator.DEFAULT_TEST_EXECUTION_COMPARATOR // requires Closure 85 | 86 | /** 87 | * Closure that converts a reporter row entry to a single String 88 | */ 89 | rowFromReport = ReportStorer.DEFAULT_ROW_FROM_REPORT_CONVERTER // requires Closure 90 | 91 | /** 92 | * Relative path to the report for a module. Defaults to {@code /reports/test_profiling/testsProfile.csv} 93 | */ 94 | relativeReportPath = new File(...) // requires File 95 | 96 | /** 97 | * Path to the merged summary of reports. Defaults to {@code project.rootProject.buildDir/reports/test_profiling/summary.csv" 98 | */ 99 | mergedSummaryPath = new File(...) // requires File 100 | 101 | /** 102 | * Milliseconds of test execution above which we will store information about the test. Defaults to 0 103 | */ 104 | minTestThreshold = 0 // requires Integer 105 | 106 | /** 107 | * Additional options for build breaking 108 | */ 109 | buildBreaker { 110 | 111 | /** 112 | * Milliseconds after which test execution will be terminated with a fail 113 | */ 114 | maxTestThreshold = 30_000 // requires Integer 115 | 116 | /** 117 | * List of test class name suffixes (e.g. LoanAmountVerificationTest) 118 | */ 119 | testClassNameSuffixes = ['Test', 'Should', 'Spec'] // requires List 120 | 121 | /** 122 | * A method to add additional suffixes 123 | */ 124 | addTestClassNameSuffix 'SomeOtherSuffix' 125 | 126 | /** 127 | * List of regexps related to FQN of class that if matched will NOT break the test 128 | */ 129 | testClassRegexpsToIgnore = [] // requires List 130 | 131 | /** 132 | * A method to add regexps of classes to ignore 133 | */ 134 | addTestClassRegexpToIgnore('a', 'b', 'c') 135 | 136 | /** 137 | * Section to describe what should happen if tests exceed max threshold 138 | */ 139 | ifTestsExceedMaxThreshold { 140 | breakBuild() 141 | } 142 | } 143 | } 144 | 145 | ``` 146 | 147 | ### Actions if build exceeds max threshold 148 | 149 | #### Display default warning message 150 | 151 | If provided as follows then the build will display a default warning message if the test execution time exceeds the provided max one 152 | 153 | ``` 154 | testprofiler { 155 | 156 | buildBreaker { 157 | maxTestThreshold = 30_000 158 | 159 | ifTestsExceedMaxThreshold { 160 | displayWarning() 161 | } 162 | } 163 | } 164 | } 165 | ``` 166 | 167 | #### Display custom warning message 168 | 169 | If provided as follows then the build will display a custom warning message if the test execution time exceeds the provided max one 170 | 171 | ``` 172 | testprofiler { 173 | 174 | buildBreaker { 175 | maxTestThreshold = 30_000 176 | 177 | ifTestsExceedMaxThreshold { 178 | displayWarning { TestDescriptor testDescriptor, TestExecutionResult testExecutionResult -> 179 | "return some string with [$testDescriptor] and [$testExecutionResult] that will be logged" 180 | } 181 | } 182 | } 183 | } 184 | } 185 | ``` 186 | 187 | #### Break the build 188 | 189 | If provided as follows then the will break the build if the test takes too long too run. 190 | 191 | ``` 192 | testprofiler { 193 | 194 | buildBreaker { 195 | maxTestThreshold = 30_000 196 | 197 | ifTestsExceedMaxThreshold { 198 | breakBuild() 199 | } 200 | } 201 | } 202 | } 203 | ``` 204 | 205 | #### Perform custom logic 206 | 207 | If provided as follows then the custom logic will be executed if the test execution time exceeds the provided max one 208 | 209 | ``` 210 | testprofiler { 211 | 212 | buildBreaker { 213 | maxTestThreshold = 30_000 214 | 215 | ifTestsExceedMaxThreshold { 216 | act { com.blogspot.toomuchcoding.testprofiler.LoggerProxy, 217 | TestDescriptor testDescriptor, 218 | TestExecutionResult testExecutionResult -> 219 | // do whatever you want to... 220 | } 221 | } 222 | } 223 | } 224 | } 225 | ``` 226 | 227 | ## Deprecated (up till version 0.0.4) 228 | 229 | ### How to add it 230 | 231 | For the time being just enter in your project 232 | 233 | ``` 234 | if (project.hasProperty('testsProfiling')) { 235 | apply from: 'https://raw.githubusercontent.com/marcingrzejszczak/gradle-test-profiler/0.0.4/test_profiling.gradle' 236 | } 237 | ``` 238 | 239 | ### How to run it? 240 | 241 | Execute 242 | 243 | ``` 244 | ./gradlew clean build testsProfileSummaryReport -PtestsProfiling 245 | ``` 246 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenLocal() 4 | jcenter() 5 | } 6 | dependencies { 7 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:+' 8 | classpath 'com.ofg:uptodate-gradle-plugin:1.5.2' 9 | if (project.hasProperty('coverage')) { 10 | classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:1.0.2' 11 | } 12 | classpath 'nu.studer:gradle-plugindev-plugin:1.0.3' 13 | } 14 | } 15 | 16 | apply plugin: 'com.jfrog.bintray' 17 | apply plugin: 'com.ofg.uptodate' 18 | apply plugin: 'maven-publish' 19 | apply plugin: 'groovy' 20 | apply plugin: 'nu.studer.plugindev' 21 | 22 | sourceCompatibility = 1.7 23 | targetCompatibility = 1.7 24 | 25 | repositories { 26 | mavenLocal() 27 | jcenter() 28 | } 29 | 30 | dependencies { 31 | compile gradleApi() 32 | compile localGroovy() 33 | compile "org.slf4j:slf4j-api:1.7.12" 34 | compile 'org.javassist:javassist:3.20.0-GA' 35 | compile('org.spockframework:spock-core:1.0-groovy-2.3') { 36 | exclude module: 'groovy-all' 37 | } 38 | 39 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.12' 40 | testRuntime 'cglib:cglib-nodep:3.1' 41 | testRuntime 'org.objenesis:objenesis:2.1' 42 | testCompile('com.netflix.nebula:nebula-test:2.2.2') { 43 | exclude group: 'org.codehaus.groovy', module: 'groovy-all' 44 | } 45 | } 46 | 47 | uptodate { 48 | addExcludedVersionPatterns '^1.*-groovy-2.[3-4]$' 49 | } 50 | 51 | sourceSets.main.java.srcDirs = [] 52 | sourceSets.main.groovy.srcDirs += ["src/main/java"] 53 | 54 | test { 55 | maxParallelForks = 8 56 | testLogging { 57 | exceptionFormat = 'full' 58 | } 59 | } 60 | 61 | bintrayUpload.dependsOn 'build' 62 | 63 | plugindev { 64 | pluginId ='com.blogspot.toomuchcoding.testprofiler' 65 | pluginImplementationClass 'com.blogspot.toomuchcoding.testprofiler.TestProfilerPlugin' 66 | pluginDescription 'Gradle plugin that profiles your tests. Gives you a CSV file sorted by tests execution time.' 67 | pluginLicenses 'Apache-2.0' 68 | pluginTags 'gradle', 'plugin', 'testing' 69 | authorId 'marcingrzejszczak' 70 | authorName 'Marcin Grzejszczak' 71 | authorEmail 'marcin@grzejszczak.pl' 72 | projectUrl 'https://github.com/marcingrzejszczak/gradle-test-profiler' 73 | projectInceptionYear '2015' 74 | done() // do not omit this 75 | } 76 | 77 | 78 | bintray { 79 | user = System.getProperty('bintrayUser') 80 | key = System.getProperty('bintrayKey') 81 | pkg.repo = 'com-blogspot-toomuchcoding' 82 | } 83 | if (project.hasProperty('coverage')) { 84 | apply plugin: 'jacoco' 85 | apply plugin: 'com.github.kt3k.coveralls' 86 | 87 | jacoco { 88 | toolVersion = '0.7.1.201405082137' 89 | } 90 | 91 | jacocoTestReport { 92 | reports { 93 | xml.enabled = true // coveralls plugin depends on xml format report 94 | html.enabled = true 95 | } 96 | } 97 | test { 98 | ignoreFailures = true 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | group=com.blogspot.toomuchcoding 2 | version=0.3.3-SNAPSHOT 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcingrzejszczak/gradle-test-profiler/e683cb96df08d5fbe342e55a778e65a5799eeaf9/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jan 08 13:54:43 CET 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-all.zip -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/AddTimeoutTask.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | import com.blogspot.toomuchcoding.testprofiler.TestProfilerPluginExtension.BuildBreakerOptions 3 | import com.blogspot.toomuchcoding.testprofiler.spock.CustomTimeout 4 | import com.blogspot.toomuchcoding.testprofiler.spock.GlobalTimeoutExtension 5 | import groovy.transform.CompileDynamic 6 | import groovy.transform.CompileStatic 7 | import groovy.transform.PackageScope 8 | import groovy.transform.TypeCheckingMode 9 | import groovy.util.logging.Slf4j 10 | import javassist.ClassClassPath 11 | import javassist.ClassPool 12 | import javassist.CtClass 13 | import org.gradle.api.DefaultTask 14 | import org.gradle.api.Task 15 | import org.gradle.api.plugins.JavaPlugin 16 | import org.gradle.api.tasks.OutputDirectory 17 | import org.gradle.api.tasks.TaskAction 18 | import org.gradle.api.tasks.testing.Test 19 | 20 | @PackageScope 21 | @CompileStatic 22 | @Slf4j 23 | class AddTimeoutTask extends DefaultTask { 24 | 25 | TestProfilerPluginExtension testProfilerPluginExtension 26 | @OutputDirectory File outputDir 27 | 28 | @TaskAction 29 | void testsProfileSummaryReport() { 30 | Integer maxThreshold = getTestProfilerPluginExtension().buildBreakerOptions.maxTestThreshold 31 | if (!getTestProfilerPluginExtension().enabled) { 32 | log.info("Can't add timeout since the testprofiler extension is disabled") 33 | return 34 | } 35 | if (maxThreshold == null) { 36 | log.info("No max test threshold has been provided thus no global timeout will be " + 37 | "applied for project [$project.name]. Provided threshold was [$maxThreshold]") 38 | return 39 | } 40 | if (!getTestProfilerPluginExtension().buildBreakerOptions.shouldBreakBuild()) { 41 | log.debug("Won't add global timeout - user picked other approach") 42 | return 43 | } 44 | addTimeouts(maxThreshold) 45 | } 46 | 47 | private void addTimeouts(int maxThreshold) { 48 | log.info("Adding global Timeout rule for project [$project.name]") 49 | this.project.plugins.withType(JavaPlugin) { 50 | this.project.tasks.withType(Test) { Task task -> 51 | Test testTask = (Test) task 52 | BuildBreakerOptions buildBreakerOptions = getTestProfilerPluginExtension().buildBreakerOptions 53 | appendTimeoutRule(buildBreakerOptions, testTask) 54 | addGlobalExtensionToSpock(testTask, maxThreshold, buildBreakerOptions) 55 | } 56 | } 57 | } 58 | 59 | private void appendTimeoutRule(BuildBreakerOptions buildBreakerOptions, Test testTask) { 60 | new TestClassesModifier(project, buildBreakerOptions).appendRule(testTask) 61 | } 62 | 63 | @CompileDynamic 64 | private void addGlobalExtensionToSpock(Test test, Integer maxThreshold, BuildBreakerOptions buildBreakerOptions) { 65 | if (!project.plugins.findPlugin('groovy')) { 66 | log.debug("The project doesn't have Groovy plugin - skipping Spock extension adding") 67 | return 68 | } 69 | if (!test.classpath.files.any { it.absolutePath.contains('spock') }) { 70 | log.debug("Spock is not on classpath - skipping Spock extension adding") 71 | return 72 | } 73 | addEntryInMetaInf() 74 | addCompiledGlobalExtensionToTests(test) 75 | test.jvmArgs( 76 | "-D${TestProfilerPlugin.DEFAULT_TEST_TIMEOUT_PROPERTY}=${maxThreshold.toString()}", 77 | "-D${TestProfilerPlugin.TEST_CLASSES_TO_IGNORE}=${buildBreakerOptions.testClassRegexpsToIgnore.join(',')}" 78 | ) 79 | } 80 | 81 | private void addCompiledGlobalExtensionToTests(Test test) { 82 | ClassPool pool = ClassPool.getDefault() 83 | pool.insertClassPath(new ClassClassPath(GlobalTimeoutExtension)) 84 | pool.insertClassPath(new ClassClassPath(CustomTimeout)) 85 | writeClass(GlobalTimeoutExtension, pool, test) 86 | writeClass(CustomTimeout, pool, test) 87 | } 88 | 89 | private void writeClass(Class clazz, ClassPool pool, Test test) { 90 | CtClass ctClass = pool.get(clazz.name) 91 | String outputDirectory = test.testClassesDir.absolutePath 92 | ctClass.writeFile(outputDirectory) 93 | log.debug("Wrote global extension to [$outputDirectory]") 94 | } 95 | 96 | @CompileStatic(TypeCheckingMode.SKIP) 97 | private void addEntryInMetaInf() { 98 | File spockServices = new File(project.sourceSets.main.output.resourcesDir, '/META-INF/services') 99 | log.debug("Will create a meta-inf entry in [$spockServices]") 100 | spockServices.mkdirs() 101 | File globalExtensions = new File(spockServices, 'org.spockframework.runtime.extension.IGlobalExtension') 102 | if (globalExtensions.exists()) { 103 | globalExtensions.append("${System.getProperty("line.separator")}$GlobalTimeoutExtension.name") 104 | } else { 105 | globalExtensions.text = GlobalTimeoutExtension.name 106 | } 107 | log.debug("GlobalExtension in META-INF [$globalExtensions.text]") 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/BuildBreaker.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | import groovy.transform.CompileDynamic 3 | import groovy.transform.CompileStatic 4 | import groovy.transform.PackageScope 5 | import org.gradle.api.Project 6 | import org.gradle.api.Task 7 | import org.gradle.api.plugins.JavaPlugin 8 | 9 | @PackageScope 10 | @CompileStatic 11 | class BuildBreaker { 12 | 13 | private static final String COMPILE_TEST_GROOVY = 'compileTestGroovy' 14 | 15 | private final Project project 16 | private final TestProfilerPluginExtension pluginExtension 17 | private final LoggerProxy loggerProxy 18 | 19 | BuildBreaker(Project project, TestProfilerPluginExtension pluginExtension, LoggerProxy loggerProxy) { 20 | this.project = project 21 | this.pluginExtension = pluginExtension 22 | this.loggerProxy = loggerProxy 23 | } 24 | 25 | void performBuildBreakingLogic() { 26 | createAfterCompilationTestTaskModifier() 27 | } 28 | 29 | @CompileDynamic 30 | private Task createAfterCompilationTestTaskModifier() { 31 | AddTimeoutTask addTimeoutTask = project.tasks.create(TestProfilerPlugin.TIMEOUT_ADDER_TESTS_TASK_NAME, AddTimeoutTask) 32 | addTimeoutTask.dependsOn(testCompilationTask(project)) 33 | project.tasks.getByName(JavaPlugin.TEST_TASK_NAME).dependsOn(addTimeoutTask) 34 | addTimeoutTask.conventionMapping.with { 35 | testProfilerPluginExtension = { pluginExtension } 36 | outputDir = { project.sourceSets.test.output.classesDir } 37 | } 38 | return addTimeoutTask 39 | } 40 | 41 | private Object testCompilationTask(Project project) { 42 | List testCompilationTasks = [JavaPlugin.COMPILE_TEST_JAVA_TASK_NAME] 43 | if (project.plugins.findPlugin('groovy')) { 44 | testCompilationTasks << COMPILE_TEST_GROOVY 45 | } 46 | return testCompilationTasks 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/DefaultTestExecutionComparator.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.CompileStatic 4 | import groovy.util.logging.Slf4j 5 | 6 | @CompileStatic 7 | @Slf4j 8 | class DefaultTestExecutionComparator implements Comparator { 9 | 10 | protected static final Closure DEFAULT_TEST_EXECUTION_COMPARATOR = { ReportRow o1, ReportRow o2 -> 11 | if (o1.testExecutionResult.testExecutionTime <=> o2.testExecutionResult.testExecutionTime != 0) { 12 | return o2.testExecutionResult.testExecutionTime <=> o1.testExecutionResult.testExecutionTime 13 | } 14 | if (o1.testExecutionResult.testClassName <=> o2.testExecutionResult.testClassName != 0) { 15 | return o2.testExecutionResult.testClassName <=> o1.testExecutionResult.testClassName 16 | } 17 | if (o1.testExecutionResult.testName <=> o2.testExecutionResult.testName != 0) { 18 | return o2.testExecutionResult.testName <=> o1.testExecutionResult.testName 19 | } 20 | if (o1.testClassExecutionTime <=> o2.testClassExecutionTime != 0) { 21 | return o2.testClassExecutionTime <=> o1.testClassExecutionTime 22 | } 23 | return o2.module <=> o1.module 24 | } 25 | 26 | @Override 27 | int compare(ReportRow o1, ReportRow o2) { 28 | return DEFAULT_TEST_EXECUTION_COMPARATOR(o1, o2) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/ExtensionCreator.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.PackageScope 4 | import org.gradle.api.Project 5 | 6 | @PackageScope 7 | class ExtensionCreator { 8 | 9 | protected static final String TEST_PROFILER_EXTENSION = "testprofiler" 10 | 11 | TestProfilerPluginExtension createExtension(Project project) { 12 | return project.extensions.create(TEST_PROFILER_EXTENSION, TestProfilerPluginExtension) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/LoggerProxy.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.CompileStatic 4 | import groovy.util.logging.Slf4j 5 | 6 | @CompileStatic 7 | @Slf4j 8 | class LoggerProxy { 9 | 10 | void debug(String message) { 11 | log.debug(message) 12 | } 13 | 14 | void info(String message) { 15 | log.info(message) 16 | } 17 | 18 | void warn(String message) { 19 | log.warn(message) 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/NoOpTask.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.PackageScope 4 | import groovy.transform.CompileStatic 5 | import org.gradle.api.DefaultTask 6 | import org.gradle.api.tasks.TaskAction 7 | 8 | @PackageScope 9 | @CompileStatic 10 | class NoOpTask extends DefaultTask { 11 | private final LoggerProxy loggerProxy 12 | 13 | NoOpTask() { 14 | this.loggerProxy = new LoggerProxy() 15 | } 16 | 17 | @TaskAction 18 | void logThatTaskIsDisabled() { 19 | loggerProxy.info("Task is disabled - please enable it via the extension") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/ReportMergerTask.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | import groovy.transform.CompileStatic 3 | import groovy.transform.PackageScope 4 | import groovy.util.logging.Slf4j 5 | import org.gradle.api.DefaultTask 6 | import org.gradle.api.Project 7 | import org.gradle.api.tasks.TaskAction 8 | 9 | @PackageScope 10 | @CompileStatic 11 | @Slf4j 12 | class ReportMergerTask extends DefaultTask { 13 | 14 | TestProfilerPluginExtension testProfilerPluginExtension 15 | File mergedTestProfilingSummaryFile 16 | 17 | @TaskAction 18 | void testsProfileSummaryReport() { 19 | if (!getTestProfilerPluginExtension().enabled) { 20 | log.debug("The plugin is disabled so no merging will take place") 21 | return 22 | } 23 | log.debug("Will store merged test profiling summary in [${getMergedTestProfilingSummaryFile()}]") 24 | Project rootProject = project.rootProject 25 | String fileContent = rootProject.getAllprojects().collect { 26 | File report = new File(it.buildDir, getTestProfilerPluginExtension().relativeReportPath.toString()) 27 | log.debug("Report to collect [$report]") 28 | return report 29 | }.findAll { 30 | it.exists() 31 | }.collect { 32 | it.text - getTestProfilerPluginExtension().outputReportHeaders 33 | }.join('\n') 34 | if (!fileContent) { 35 | log.info("The reports were empty - sth went wrong") 36 | return 37 | } 38 | storeCollectedReport(fileContent) 39 | } 40 | 41 | private void storeCollectedReport(String fileContent) { 42 | log.info("Saving file [${getMergedTestProfilingSummaryFile()}] content [$fileContent]") 43 | getMergedTestProfilingSummaryFile().text = getTestProfilerPluginExtension().outputReportHeaders 44 | Set reportRows = new TreeSet(getTestProfilerPluginExtension().comparator as Comparator) 45 | appendReportRow(fileContent, reportRows) 46 | getMergedTestProfilingSummaryFile() << reportRows.collect(rowFromReport()).join('\n') 47 | println "Your combined report is available here [${getMergedTestProfilingSummaryFile()}]" 48 | } 49 | 50 | private void appendReportRow(String fileContent, Set reportRows) { 51 | fileContent.split('\n') 52 | .findAll { it } 53 | .each { String string -> 54 | String[] row = string.split(getTestProfilerPluginExtension().separator) 55 | log.debug("Converting row $row") 56 | try { 57 | reportRows << new ReportRow(row[0], new TestExecutionResult(row[1], row[2], row[3] as Double), row[4] as Double) 58 | } catch (NumberFormatException e) { 59 | log.warn("Exception occurred while trying to parse a report row with value [$string]", e) 60 | } 61 | } 62 | } 63 | 64 | Closure rowFromReport() { 65 | return getTestProfilerPluginExtension().rowFromReport.curry(getTestProfilerPluginExtension()) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/ReportRow.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.CompileStatic 4 | import groovy.transform.Immutable 5 | 6 | /** 7 | * @author Adam Chudzik 8 | * @author Marcin Grzejszczak 9 | */ 10 | @CompileStatic 11 | @Immutable(knownImmutableClasses = [TestExecutionResult]) 12 | class ReportRow { 13 | String module 14 | TestExecutionResult testExecutionResult 15 | Double testClassExecutionTime 16 | } 17 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/ReportStorerTask.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.PackageScope 4 | import groovy.transform.CompileStatic 5 | import groovy.util.logging.Slf4j 6 | import org.gradle.api.Project 7 | 8 | @PackageScope 9 | @CompileStatic 10 | @Slf4j 11 | class ReportStorerTask { 12 | 13 | protected static final Closure DEFAULT_ROW_FROM_REPORT_CONVERTER = { TestProfilerPluginExtension testProfilerPluginExtension , ReportRow reportRow -> 14 | "${reportRow.module}${testProfilerPluginExtension.separator}${reportRow.testExecutionResult.testClassName}${testProfilerPluginExtension.separator}${reportRow.testExecutionResult.testName}${testProfilerPluginExtension.separator}${reportRow.testExecutionResult.testExecutionTime}${testProfilerPluginExtension.separator}${reportRow.testClassExecutionTime}".toString() 15 | } 16 | 17 | private final TestProfilerPluginExtension testProfilerPluginExtension 18 | private final Project project 19 | 20 | ReportStorerTask(TestProfilerPluginExtension testProfilerPluginExtension, Project project) { 21 | this.testProfilerPluginExtension = testProfilerPluginExtension 22 | this.project = project 23 | } 24 | 25 | public void storeReport(Set testExecutionResults) { 26 | if (!testProfilerPluginExtension.enabled) { 27 | log.debug("The plugin is disabled so no test results will be recorded") 28 | return 29 | } 30 | log.debug("All test execution results [$testExecutionResults]") 31 | File report = createNewReportFile() 32 | addHeadersToFile(report) 33 | Map classExecutionTime = calculateClassExecutionTime(testExecutionResults) 34 | log.debug("Calculated class execution time [$classExecutionTime]") 35 | String testExecutionResult = buildTestExecutionResult(classExecutionTime, testExecutionResults) 36 | log.debug("Test execution result [$testExecutionResult]") 37 | appendTestExecutionResultToFile(report, testExecutionResult) 38 | println "Your tests report is ready at [$report.absolutePath]" 39 | appendTestExecutionResultToMergedTestSummary(testExecutionResult) 40 | } 41 | 42 | private File createNewReportFile() { 43 | File report = new File(project.buildDir, testProfilerPluginExtension.relativeReportPath.toString()) 44 | log.debug("Creating a new file [$report]") 45 | report.delete() 46 | report.parentFile.mkdirs() 47 | report.createNewFile() 48 | return report 49 | } 50 | 51 | private File addHeadersToFile(File report) { 52 | return report << testProfilerPluginExtension.outputReportHeaders 53 | } 54 | 55 | private File appendTestExecutionResultToFile(File report, String testExecutionResult) { 56 | return report << testExecutionResult 57 | } 58 | 59 | private void appendTestExecutionResultToMergedTestSummary(String testExecutionResult) { 60 | File mergedTestProfilingSummary = testProfilerPluginExtension.mergedSummaryPath 61 | mergedTestProfilingSummary.parentFile.mkdirs() 62 | mergedTestProfilingSummary << testExecutionResult << '\n' 63 | log.debug("Stored [$testExecutionResult] in [$mergedTestProfilingSummary]") 64 | } 65 | 66 | private String buildTestExecutionResult(Map classExecutionTime, Set testExecutionResults) { 67 | return testExecutionResults.collect { 68 | new ReportRow(project.path, it, classExecutionTime[it.testClassName]) 69 | }.sort(testProfilerPluginExtension.comparator) 70 | .collect(rowFromReport()).join('\n') 71 | } 72 | 73 | private Map calculateClassExecutionTime(Set testExecutionResults) { 74 | return testExecutionResults.groupBy { 75 | TestExecutionResult testExecutionResult -> testExecutionResult.testClassName 76 | }.collectEntries { 77 | [it.key, (it.value.sum { TestExecutionResult testExecutionResult -> testExecutionResult.testExecutionTime } as Double).round(3)] 78 | } as Map 79 | } 80 | 81 | Closure rowFromReport() { 82 | return testProfilerPluginExtension.rowFromReport.curry(testProfilerPluginExtension) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/TaskCreator.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | import groovy.transform.PackageScope 3 | import groovy.util.logging.Slf4j 4 | import org.gradle.api.Project 5 | import org.gradle.api.Task 6 | 7 | import static com.blogspot.toomuchcoding.testprofiler.TestProfilerPlugin.PROFILE_TESTS_TASK_NAME 8 | 9 | @PackageScope 10 | @Slf4j 11 | class TaskCreator { 12 | 13 | Task buildReportMergerForProject(Project project, TestProfilerPluginExtension extension) { 14 | Task task = createTask(extension, project) 15 | if (!task) { 16 | return null 17 | } 18 | task.group = 'Verification' 19 | task.description = "Creates a report of tests execution time" 20 | return task 21 | } 22 | 23 | private Task createTask(TestProfilerPluginExtension extension, Project project) { 24 | if (extension.enabled) { 25 | return createReportMerger(project, extension) 26 | } else { 27 | return createNoOpTask(project) 28 | } 29 | } 30 | 31 | private ReportMergerTask createReportMerger(Project project, TestProfilerPluginExtension extension) { 32 | if (taskShouldntBeAdded(project)) { 33 | return null 34 | } 35 | ReportMergerTask reportMerger = project.tasks.create(PROFILE_TESTS_TASK_NAME, ReportMergerTask) 36 | project.gradle.afterProject { Project proj -> 37 | reportMerger.mustRunAfter(proj.getTasksByName('build', true)) 38 | } 39 | log.info("Created a task [$PROFILE_TESTS_TASK_NAME] in root project") 40 | reportMerger.conventionMapping.with { 41 | testProfilerPluginExtension = { extension } 42 | mergedTestProfilingSummaryFile = { extension.mergedSummaryPath } 43 | } 44 | return reportMerger 45 | } 46 | 47 | private boolean taskShouldntBeAdded(Project project) { 48 | return project != project.rootProject 49 | } 50 | 51 | private NoOpTask createNoOpTask(Project project) { 52 | return project.tasks.create(PROFILE_TESTS_TASK_NAME, NoOpTask) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/TestClassesModifier.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import com.blogspot.toomuchcoding.testprofiler.TestProfilerPluginExtension.BuildBreakerOptions 4 | import groovy.io.FileType 5 | import groovy.transform.CompileStatic 6 | import groovy.transform.PackageScope 7 | import groovy.util.logging.Slf4j 8 | import javassist.* 9 | import javassist.bytecode.AnnotationsAttribute 10 | import javassist.bytecode.ClassFile 11 | import javassist.bytecode.ConstPool 12 | import javassist.bytecode.annotation.Annotation 13 | import org.gradle.api.Project 14 | import org.gradle.api.tasks.testing.Test 15 | 16 | import static javassist.bytecode.AnnotationsAttribute.visibleTag 17 | 18 | @PackageScope 19 | @Slf4j 20 | @CompileStatic 21 | class TestClassesModifier { 22 | 23 | private static final String CLASS_FILE_EXTENSION = 'class' 24 | private static final String JUNIT_RULE_FQN = "org.junit.Rule" 25 | 26 | private final Project project 27 | private final BuildBreakerOptions buildBreakerOptions 28 | 29 | TestClassesModifier(Project project, BuildBreakerOptions buildBreakerOptions) { 30 | this.project = project 31 | this.buildBreakerOptions = buildBreakerOptions 32 | } 33 | 34 | void appendRule(Test test) { 35 | log.debug("Appending Timeout rule to test [$test]") 36 | List pathsToLoad = retrieveFqnsOfClasses(test) 37 | log.debug("PathsToLoad $pathsToLoad") 38 | Collection nonIgnorableClasses = findAllNonIgnorableClasses(pathsToLoad) 39 | log.debug("NonIgnorableClasses $nonIgnorableClasses") 40 | GroovyClassLoader groovyClassLoader = new TestTaskBasedGroovyClassLoader(test) 41 | overwriteExistingTestClasses(nonIgnorableClasses, groovyClassLoader, test) 42 | } 43 | 44 | private List retrieveFqnsOfClasses(Test test) { 45 | List pathsToLoad = [] 46 | log.debug("TestClassNameSuffixes [$buildBreakerOptions.testClassNameSuffixes], test classes dir [$test.testClassesDir]") 47 | test.testClassesDir.eachFileRecurse(FileType.FILES) { File file -> 48 | log.debug("TestFileName [$file.name]") 49 | if ( buildBreakerOptions.testClassNameSuffixes.any { file.name.endsWith("${it}.${CLASS_FILE_EXTENSION}") }) { 50 | pathsToLoad << createFQNFromFiles(file, test.testClassesDir) 51 | } 52 | } 53 | return pathsToLoad 54 | } 55 | 56 | private Collection findAllNonIgnorableClasses(List pathsToLoad) { 57 | List regexpsToIgnore = buildBreakerOptions.testClassRegexpsToIgnore 58 | log.debug("Ignoring the following test classes matching the regexps [${regexpsToIgnore}]") 59 | return pathsToLoad.findAll { String path -> !regexpsToIgnore.any { path.matches(it) } } 60 | } 61 | 62 | private String createFQNFromFiles(File testClass, File testClassesDir) { 63 | return (testClass.absolutePath - testClassesDir.absolutePath - File.separator - ".$CLASS_FILE_EXTENSION").replaceAll(File.separator, '.') 64 | } 65 | 66 | private CtField createTimeoutField(CtClass testClass) { 67 | String rule = "public org.junit.rules.Timeout ${getGeneratedFieldName(testClass)} = new org.junit.rules.Timeout($buildBreakerOptions.maxTestThreshold);" 68 | log.debug("Trying to append the following code [$rule] to test class [$testClass]") 69 | return CtField.make(rule, testClass) 70 | } 71 | 72 | private String getGeneratedFieldName(CtClass testClass) { 73 | return "${testClass.simpleName}_timeout_${createUuidAcceptableAsJavaFieldName()}" 74 | } 75 | 76 | private String createUuidAcceptableAsJavaFieldName() { 77 | return UUID.randomUUID().toString().replaceAll('-', '_') 78 | } 79 | 80 | private void wrapFieldWithRuleAnnotation(ConstPool constpool, CtField field) { 81 | AnnotationsAttribute attr = new AnnotationsAttribute(constpool, visibleTag) 82 | Annotation annot = new Annotation(JUNIT_RULE_FQN, constpool) 83 | attr.addAnnotation(annot) 84 | field.fieldInfo.addAttribute(attr) 85 | } 86 | 87 | private void overwriteExistingTestClasses(Collection pathsToLoad, ClassLoader classLoader, Test test) { 88 | pathsToLoad.collect { classLoader.loadClass(it) }.each { writeFile(it, test) } 89 | } 90 | 91 | private void writeFile(Class clazz, Test test) { 92 | log.debug("I'm in class [$clazz] and test [$test]") 93 | ClassPool pool = createClassPoolWithSystemPath() 94 | ConstPool constpool = createConstPool(clazz, pool) 95 | CtClass testClass = pool.get(clazz.name) 96 | if (theFieldHasBeenAlreadyCreated(testClass)) { 97 | log.debug("The field has already been created...") 98 | return 99 | } 100 | CtField field = createTimeoutField(testClass) 101 | log.debug("Created timeout field") 102 | wrapFieldWithRuleAnnotation(constpool, field) 103 | log.debug("Wrapped field with rule annotation") 104 | testClass.addField(field) 105 | log.debug("Added field to test class") 106 | testClass.writeFile(test.testClassesDir.absolutePath) 107 | log.debug("Writing test class to path [${test.testClassesDir.absolutePath}]") 108 | } 109 | 110 | private ClassPool createClassPoolWithSystemPath() { 111 | ClassPool pool = new ClassPool() 112 | pool.appendSystemPath() 113 | return pool 114 | } 115 | 116 | private boolean theFieldHasBeenAlreadyCreated(CtClass testClass) { 117 | try { 118 | String fieldToRetrieve = getGeneratedFieldName(testClass) 119 | log.debug("Field to retrieve is [$fieldToRetrieve]") 120 | return testClass.getField(fieldToRetrieve) 121 | } catch (NotFoundException exception) { 122 | log.error("Exception occurred while tyring to find the field", exception) 123 | return false 124 | } 125 | } 126 | 127 | private ConstPool createConstPool(Class clazz, ClassPool pool) { 128 | log.debug("Class is located at [${clazz.getProtectionDomain().getCodeSource().getLocation()}]") 129 | ClassClassPath classClassPath = new ClassClassPath(clazz) 130 | pool.insertClassPath(classClassPath) 131 | CtClass ctClass = pool.getCtClass(clazz.name) 132 | ctClass.defrost() 133 | ClassFile ccFile = ctClass.getClassFile() 134 | return ccFile.getConstPool() 135 | } 136 | 137 | } 138 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/TestExecutionResult.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.CompileStatic 4 | import groovy.transform.Immutable 5 | import groovy.transform.ToString 6 | 7 | /** 8 | * @author Adam Chudzik 9 | * @author Marcin Grzejszczak 10 | */ 11 | @CompileStatic 12 | @Immutable 13 | @ToString(includePackage = false, includeNames = true) 14 | class TestExecutionResult { 15 | String testClassName 16 | String testName 17 | Double testExecutionTime 18 | } 19 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/TestExecutionResultSavingTestListener.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | import groovy.transform.CompileStatic 3 | import groovy.transform.PackageScope 4 | import org.gradle.api.Project 5 | import org.gradle.api.tasks.testing.TestDescriptor 6 | import org.gradle.api.tasks.testing.TestListener 7 | import org.gradle.api.tasks.testing.TestResult 8 | 9 | @PackageScope 10 | @CompileStatic 11 | class TestExecutionResultSavingTestListener implements TestListener { 12 | 13 | private static final String DEFAULT_WARN_MSG = "[TEST-PROFILER] For project [%s] test [%s] from class [%s] took too long to run. Test execution time [%s]. Threshold [%s]." 14 | 15 | private final Set testExecutionResults 16 | private final TestProfilerPluginExtension testProfilerPluginExtension 17 | private final LoggerProxy loggerProxy 18 | private final Project project 19 | 20 | TestExecutionResultSavingTestListener(Set testExecutionResults, 21 | TestProfilerPluginExtension testProfilerPluginExtension, 22 | Project project, 23 | LoggerProxy loggerProxy = new LoggerProxy()) { 24 | this.testExecutionResults = testExecutionResults 25 | this.testProfilerPluginExtension = testProfilerPluginExtension 26 | this.loggerProxy = loggerProxy 27 | this.project = project 28 | } 29 | 30 | @Override 31 | void beforeSuite(TestDescriptor suite) { } 32 | 33 | @Override 34 | void afterSuite(TestDescriptor suite, TestResult result) { } 35 | 36 | @Override 37 | void beforeTest(TestDescriptor testDescriptor) { } 38 | 39 | @Override 40 | void afterTest(TestDescriptor testDescriptor, TestResult result) { 41 | if (!testProfilerPluginExtension.enabled) { 42 | loggerProxy.debug("The plugin is disabled so no test results will be recorded") 43 | return 44 | } 45 | long executionTimeInMs = result.endTime - result.startTime 46 | TestExecutionResult testExecutionResult = new TestExecutionResult(testDescriptor.className, testDescriptor.name, (executionTimeInMs / 1000) as Double) 47 | loggerProxy.info("[TEST-PROFILER] Gathered Test Execution Result [$testExecutionResult] with result [$result]") 48 | if (minThresholdIsNotSet() || testExecutionTimeIsBelowMinThreshold(executionTimeInMs)) { 49 | loggerProxy.debug("Min threshold equals [$testProfilerPluginExtension.minTestThreshold] ms and execution time [$executionTimeInMs] ms. Will store the result in the report") 50 | storeResult(testExecutionResult) 51 | } 52 | if (testExecutionTimeIsBelowMaxThreshold(executionTimeInMs)) { 53 | loggerProxy.debug("Test execution time [$executionTimeInMs] ms if above the max threshold [$testProfilerPluginExtension.minTestThreshold]. Will perform additional logic") 54 | performAdditionalLogic(testDescriptor, testExecutionResult, executionTimeInMs) 55 | } 56 | } 57 | 58 | private void storeResult(TestExecutionResult testExecutionResult) { 59 | testExecutionResults << testExecutionResult 60 | } 61 | 62 | private boolean minThresholdIsNotSet() { 63 | return testProfilerPluginExtension.minTestThreshold == null 64 | } 65 | 66 | private boolean testExecutionTimeIsBelowMinThreshold(long executionTimeInMs) { 67 | return executionTimeInMs >= testProfilerPluginExtension.minTestThreshold 68 | } 69 | 70 | private boolean testExecutionTimeIsBelowMaxThreshold(long executionTimeInMs) { 71 | return getMaxTestThreshold() != null && executionTimeInMs >= getMaxTestThreshold() 72 | } 73 | 74 | private Integer getMaxTestThreshold() { 75 | return testProfilerPluginExtension.buildBreakerOptions.maxTestThreshold 76 | } 77 | 78 | private void performAdditionalLogic(TestDescriptor testDescriptor, TestExecutionResult testExecutionResult, long executionTimeInMs) { 79 | TestProfilerPluginExtension.BuildBreakerOptions buildBreakerOptions = testProfilerPluginExtension.buildBreakerOptions 80 | TestProfilerPluginExtension.BuildBreakerOptions.WhatToDo whatToDo = buildBreakerOptions.ifTestsExceedMaxThreshold.whatToDo 81 | Closure action = whatToDo.action 82 | if (buildBreakerOptions.shouldDisplayWarning()) { 83 | loggerProxy.warn( whatToDo.doNothing() ? 84 | String.format(DEFAULT_WARN_MSG, project.path, testExecutionResult.testName, testExecutionResult.testClassName, executionTimeInMs, testProfilerPluginExtension.buildBreakerOptions.maxTestThreshold) : 85 | action.curry(testDescriptor, testExecutionResult).call() as String) 86 | } else if (buildBreakerOptions.shouldAct()) { 87 | loggerProxy.debug("Test execution time was exceeded - will perform custom logic defined by the user") 88 | action.curry(loggerProxy, testDescriptor, testExecutionResult).call() 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/TestProfilerPlugin.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | import groovy.transform.CompileStatic 3 | import groovy.transform.PackageScope 4 | import groovy.util.logging.Slf4j 5 | import org.gradle.api.Plugin 6 | import org.gradle.api.Project 7 | 8 | import javax.inject.Inject 9 | 10 | @CompileStatic 11 | @Slf4j 12 | class TestProfilerPlugin implements Plugin { 13 | 14 | public static final String PROFILE_TESTS_TASK_NAME = "profileTests" 15 | public static final String TIMEOUT_ADDER_TESTS_TASK_NAME = "addTimeout" 16 | 17 | @PackageScope static final String DEFAULT_TEST_TIMEOUT_PROPERTY = 'default.test.timeout' 18 | @PackageScope static final String TEST_CLASSES_TO_IGNORE = 'test.classes.to.ignore' 19 | 20 | private static final String DEFAULT_REPORTS_FOLDER = '/reports/test_profiling' 21 | private static final String DEFAULT_SINGLE_REPORT_RELATIVE_PATH = "$DEFAULT_REPORTS_FOLDER/testsProfile.csv" 22 | private static final String DEFAULT_MERGED_REPORTS_RELATIVE_PATH = "$DEFAULT_REPORTS_FOLDER/summary.csv" 23 | 24 | private TestTaskModifier testTaskModifier 25 | private final LoggerProxy loggerProxy 26 | private final ExtensionCreator extensionCreator 27 | private final TaskCreator taskCreator 28 | 29 | @Inject 30 | TestProfilerPlugin() { 31 | this.loggerProxy = new LoggerProxy() 32 | this.extensionCreator = new ExtensionCreator() 33 | this.taskCreator = new TaskCreator() 34 | } 35 | 36 | protected TestProfilerPlugin(TestTaskModifier testTaskModifier, LoggerProxy loggerProxy, ExtensionCreator extensionCreator) { 37 | this.testTaskModifier = testTaskModifier 38 | this.loggerProxy = loggerProxy 39 | this.extensionCreator = extensionCreator 40 | this.taskCreator = new TaskCreator() 41 | } 42 | 43 | void apply(Project project) { 44 | TestProfilerPluginExtension extension = extensionCreator.createExtension(project) 45 | setDefaults(project, extension) 46 | printExtensionValues(extension) 47 | project.afterEvaluate { 48 | modifyTestTasks(project, extension) 49 | createSummaryReportTask(project, extension) 50 | performBuildBreakingLogic(project, extension) 51 | } 52 | } 53 | 54 | private void printExtensionValues(TestProfilerPluginExtension testProfilerPluginExtension) { 55 | loggerProxy.debug("Setting up profiling with the following default parameters [$testProfilerPluginExtension]") 56 | } 57 | 58 | private void setDefaults(Project project, TestProfilerPluginExtension testProfilerPluginExtension) { 59 | testProfilerPluginExtension.relativeReportPath = new File(DEFAULT_SINGLE_REPORT_RELATIVE_PATH) 60 | testProfilerPluginExtension.mergedSummaryPath = new File(project.rootProject.buildDir, DEFAULT_MERGED_REPORTS_RELATIVE_PATH) 61 | } 62 | 63 | private void modifyTestTasks(Project project, TestProfilerPluginExtension extension) { 64 | File mergedTestProfilingSummaryDir = mergedTestProfilingSummaryDir(extension) 65 | new TestTaskModifier(mergedTestProfilingSummaryDir, project, extension).modifyCurrentTestTasks() 66 | } 67 | 68 | private void createSummaryReportTask(Project project, TestProfilerPluginExtension extension) { 69 | taskCreator.buildReportMergerForProject(project, extension) 70 | } 71 | 72 | private File mergedTestProfilingSummaryDir(TestProfilerPluginExtension extension) { 73 | File mergedTestProfilingSummaryDir = extension.mergedSummaryPath.parentFile 74 | mergedTestProfilingSummaryDir.mkdirs() 75 | return mergedTestProfilingSummaryDir 76 | } 77 | 78 | private performBuildBreakingLogic(Project project, TestProfilerPluginExtension extension) { 79 | new BuildBreaker(project, extension, loggerProxy).performBuildBreakingLogic() 80 | } 81 | } -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/TestProfilerPluginExtension.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.CompileStatic 4 | import groovy.transform.ToString 5 | 6 | import static com.blogspot.toomuchcoding.testprofiler.TestProfilerPluginExtension.BuildBreakerOptions.WhatToDo.* 7 | import static com.blogspot.toomuchcoding.testprofiler.TestProfilerPluginExtension.BuildBreakerOptions.WhatToDo.Type.ACT 8 | import static com.blogspot.toomuchcoding.testprofiler.TestProfilerPluginExtension.BuildBreakerOptions.WhatToDo.Type.BREAK_BUILD 9 | import static com.blogspot.toomuchcoding.testprofiler.TestProfilerPluginExtension.BuildBreakerOptions.WhatToDo.Type.DISPLAY_WARNING 10 | 11 | @CompileStatic 12 | @ToString(includePackage = false, includeNames = true) 13 | class TestProfilerPluginExtension { 14 | 15 | /** 16 | * Should TestProfilerPlugin be enabled? If set to false there will be no modification of any Gradle Test classes 17 | * and the task will simply print a message 18 | */ 19 | boolean enabled = true 20 | 21 | /** 22 | * Separator of columns in the output report 23 | */ 24 | String separator = ';' 25 | 26 | /** 27 | * Headers in the report 28 | */ 29 | String outputReportHeaders = ['module', 'test class name', 'test name', 'test execution time in [s]', 'test class execution time in [s]'].join(separator).concat('\n') 30 | 31 | /** 32 | * Closure that will be converted to a Comparator to compare row entries - needed to sort rows 33 | */ 34 | Closure comparator = DefaultTestExecutionComparator.DEFAULT_TEST_EXECUTION_COMPARATOR 35 | 36 | /** 37 | * Closure that converts a reporter row entry to a single String 38 | */ 39 | Closure rowFromReport = ReportStorerTask.DEFAULT_ROW_FROM_REPORT_CONVERTER 40 | 41 | /** 42 | * Path to the report for a module. Defaults to {@code project.buildDir/reports/test_profiling/testsProfile.csv} 43 | */ 44 | File relativeReportPath 45 | 46 | /** 47 | * Path to the merged summary of reports. Defaults to {@code project.rootProject.buildDir/reports/test_profiling/summary.csv" 48 | */ 49 | File mergedSummaryPath 50 | 51 | /** 52 | * Milliseconds of test execution above which we will store information about the test. Defaults to 0 53 | */ 54 | Integer minTestThreshold = 0 55 | 56 | BuildBreakerOptions buildBreakerOptions = new BuildBreakerOptions() 57 | 58 | void buildBreaker(@DelegatesTo(BuildBreakerOptions) Closure closure) { 59 | closure.delegate = buildBreakerOptions 60 | closure() 61 | } 62 | 63 | /** 64 | * Options for build breaking 65 | */ 66 | @ToString(includePackage = false, includeNames = true) 67 | static class BuildBreakerOptions { 68 | 69 | /** 70 | * Milliseconds after which test execution will be terminated with a fail 71 | */ 72 | Integer maxTestThreshold 73 | 74 | /** 75 | * List of test class name suffixes (e.g. LoanAmountVerificationTest) 76 | */ 77 | List testClassNameSuffixes = ['Test', 'Should', 'Spec'] 78 | 79 | /** 80 | * A method to add additional suffixes 81 | */ 82 | void addTestClassNameSuffix(String... testClassNameSuffix) { 83 | testClassNameSuffixes.addAll(testClassNameSuffix) 84 | } 85 | 86 | /** 87 | * List of regexps related to FQN of class that if matched will NOT break the test 88 | */ 89 | List testClassRegexpsToIgnore = [] 90 | 91 | /** 92 | * A method to add regexps of classes to ignore 93 | */ 94 | void addTestClassRegexpToIgnore(String... testClassRegexpToIgnore) { 95 | testClassRegexpsToIgnore.addAll(testClassRegexpToIgnore) 96 | } 97 | 98 | IfTestsExceedMaxThreshold ifTestsExceedMaxThreshold = new IfTestsExceedMaxThreshold() 99 | 100 | void ifTestsExceedMaxThreshold(@DelegatesTo(IfTestsExceedMaxThreshold) Closure closure) { 101 | closure.delegate = ifTestsExceedMaxThreshold 102 | closure() 103 | } 104 | 105 | protected boolean shouldBreakBuild() { 106 | return ifTestsExceedMaxThreshold.whatToDo.type == BREAK_BUILD 107 | } 108 | 109 | protected boolean shouldDisplayWarning() { 110 | return ifTestsExceedMaxThreshold.whatToDo.type == DISPLAY_WARNING 111 | } 112 | 113 | protected boolean shouldAct() { 114 | return ifTestsExceedMaxThreshold.whatToDo.type == ACT 115 | } 116 | 117 | static class WhatToDo { 118 | public static final Closure DO_NOTHING = Closure.IDENTITY 119 | 120 | static enum Type { 121 | BREAK_BUILD, DISPLAY_WARNING, ACT 122 | } 123 | 124 | final Type type 125 | final Closure action 126 | 127 | WhatToDo(Type type, Closure action) { 128 | this.type = type 129 | this.action = action 130 | } 131 | 132 | boolean doNothing() { 133 | return action == DO_NOTHING 134 | } 135 | } 136 | 137 | 138 | static class IfTestsExceedMaxThreshold { 139 | /** 140 | * What type of action and what exactly should happen when build fails. Defaults to logging a warning 141 | */ 142 | WhatToDo whatToDo = new WhatToDo(DISPLAY_WARNING, DO_NOTHING) 143 | 144 | /** 145 | * The build will be broken 146 | */ 147 | void breakBuild() { 148 | whatToDo = new WhatToDo(BREAK_BUILD, DO_NOTHING) 149 | } 150 | 151 | /** 152 | * The warning will be displayed with default message 153 | */ 154 | void displayWarning() { 155 | whatToDo = new WhatToDo(DISPLAY_WARNING, DO_NOTHING) 156 | } 157 | 158 | /** 159 | * The warning will be displayed basing on the result of closure 160 | */ 161 | void displayWarning(Closure closure) { 162 | whatToDo = new WhatToDo(DISPLAY_WARNING, closure) 163 | } 164 | 165 | /** 166 | * Custom action will take place 167 | */ 168 | void act(Closure closure) { 169 | whatToDo = new WhatToDo(ACT, closure) 170 | } 171 | } 172 | 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/TestTaskBasedGroovyClassLoader.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.PackageScope 4 | import groovy.transform.CompileStatic 5 | import org.gradle.api.tasks.testing.Test 6 | 7 | @PackageScope 8 | @CompileStatic 9 | class TestTaskBasedGroovyClassLoader extends GroovyClassLoader { 10 | 11 | TestTaskBasedGroovyClassLoader(Test test) { 12 | super(test.class.classLoader) 13 | addURL(test.testClassesDir.toURI().toURL()) 14 | test.classpath.files.each { 15 | addURL(it.toURI().toURL()) 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/groovy/com/blogspot/toomuchcoding/testprofiler/TestTaskModifier.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import groovy.transform.CompileStatic 4 | import groovy.transform.PackageScope 5 | import groovy.util.logging.Slf4j 6 | import org.gradle.api.Project 7 | import org.gradle.api.Task 8 | import org.gradle.api.plugins.JavaPlugin 9 | import org.gradle.api.tasks.testing.Test 10 | 11 | import java.util.concurrent.ConcurrentHashMap 12 | 13 | @PackageScope 14 | @CompileStatic 15 | @Slf4j 16 | class TestTaskModifier { 17 | 18 | private final TestProfilerPluginExtension testProfilerPluginExtension 19 | private final Project project 20 | private final File mergedTestProfilingSummaryDir 21 | 22 | TestTaskModifier(File mergedTestProfilingSummaryDir,Project project, TestProfilerPluginExtension testProfilerPluginExtension) { 23 | this.mergedTestProfilingSummaryDir = mergedTestProfilingSummaryDir 24 | this.project = project 25 | this.testProfilerPluginExtension = testProfilerPluginExtension 26 | } 27 | 28 | void modifyCurrentTestTasks() { 29 | log.debug("Adding test listener and report storer for project [$project.name]") 30 | this.project.plugins.withType(JavaPlugin) { 31 | this.project.tasks.withType(Test) { Task task -> 32 | if (task.name == JavaPlugin.TEST_TASK_NAME) { 33 | Set testExecutionResults = Collections.newSetFromMap(new ConcurrentHashMap()) 34 | Test testTask = (Test) task 35 | testTask.addTestListener(new TestExecutionResultSavingTestListener(testExecutionResults, testProfilerPluginExtension, project)) 36 | testTask.doLast { 37 | new ReportStorerTask(testProfilerPluginExtension, project).storeReport(testExecutionResults) 38 | } 39 | log.debug("Added test listener and report storer for task [$testTask.name]") 40 | } 41 | } 42 | } 43 | } 44 | 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/blogspot/toomuchcoding/testprofiler/spock/CustomTimeout.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler.spock; 2 | 3 | import spock.lang.Timeout; 4 | 5 | import java.lang.annotation.Annotation; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | public class CustomTimeout implements Timeout { 9 | 10 | private final Integer timeout; 11 | 12 | public CustomTimeout(int timeout) { 13 | this.timeout = timeout; 14 | } 15 | 16 | @Override 17 | public int value() { 18 | return timeout; 19 | } 20 | 21 | @Override 22 | public TimeUnit unit() { 23 | return TimeUnit.MILLISECONDS; 24 | } 25 | 26 | @Override 27 | public Class annotationType() { 28 | return Timeout.class; 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "CustomTimeout{" + 34 | "timeout=" + timeout + 35 | '}'; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/blogspot/toomuchcoding/testprofiler/spock/GlobalTimeoutExtension.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler.spock; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.spockframework.runtime.extension.IGlobalExtension; 6 | import org.spockframework.runtime.extension.builtin.TimeoutInterceptor; 7 | import org.spockframework.runtime.model.SpecInfo; 8 | 9 | import java.util.Arrays; 10 | import java.util.List; 11 | 12 | public class GlobalTimeoutExtension implements IGlobalExtension { 13 | 14 | private static final Logger log = LoggerFactory.getLogger(GlobalTimeoutExtension.class); 15 | 16 | public void start() { 17 | 18 | } 19 | 20 | @Override 21 | public void visitSpec(SpecInfo spec) { 22 | final Integer defaultTestTimeout = Integer.valueOf(System.getProperty("default.test.timeout", "9999")); 23 | String testClassesToIgnoreProp = System.getProperty("test.classes.to.ignore", ""); 24 | List testClassesToIgnore = Arrays.asList(testClassesToIgnoreProp.split(",")); 25 | log.info("Applying global timeout extension with value [" + defaultTestTimeout + "] " + 26 | "for classes not matching regexp [" + testClassesToIgnore + "]"); 27 | boolean specNameMatchesRegexp = checkIfSpecNameMatchesRegexpToIgnore(spec, testClassesToIgnore); 28 | if (specNameMatchesRegexp) { 29 | log.info("Spec with name [" + spec.getName() + "] will be ignored since it matches the regexp"); 30 | return; 31 | } 32 | spec.getInterceptors().add(new TimeoutInterceptor(new CustomTimeout(defaultTestTimeout))); 33 | } 34 | 35 | private boolean checkIfSpecNameMatchesRegexpToIgnore(SpecInfo spec, List testClassesToIgnore) { 36 | boolean specNameMatchesRegexp = false; 37 | for(String testClassRegexp : testClassesToIgnore) { 38 | if(spec.getDescription().getClassName().matches(testClassRegexp)) { 39 | specNameMatchesRegexp = true; 40 | break; 41 | } 42 | } 43 | return specNameMatchesRegexp; 44 | } 45 | 46 | public void stop() { 47 | 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/test/groovy/com/blogspot/toomuchcoding/testprofiler/TaskCreatorSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import org.gradle.api.Project 4 | import org.gradle.api.Task 5 | import org.gradle.testfixtures.ProjectBuilder 6 | import spock.lang.Specification 7 | 8 | class TaskCreastorSpec extends Specification { 9 | 10 | TaskCreator taskCreator = new TaskCreator() 11 | Project project = ProjectBuilder.builder().build() 12 | 13 | def 'should build NoOpTask when plugin is disabled'() { 14 | when: 15 | Task task = taskCreator.buildReportMergerForProject(project, new TestProfilerPluginExtension(enabled: false)) 16 | then: 17 | task instanceof NoOpTask 18 | } 19 | 20 | def 'should build ReportMerger when plugin is enabled'() { 21 | when: 22 | Task task = taskCreator.buildReportMergerForProject(project, new TestProfilerPluginExtension()) 23 | then: 24 | task instanceof ReportMergerTask 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/groovy/com/blogspot/toomuchcoding/testprofiler/TestExecutionResultSavingTestListenerSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.blogspot.toomuchcoding.testprofiler 2 | 3 | import org.gradle.api.Project 4 | import org.gradle.api.tasks.testing.TestDescriptor 5 | import org.gradle.api.tasks.testing.TestResult 6 | import spock.lang.Specification 7 | import spock.lang.Unroll 8 | 9 | class TestExecutionResultSavingTestListenerSpec extends Specification { 10 | 11 | Project project = Stub() 12 | TestDescriptor testDescriptor = Stub() 13 | LoggerProxy loggerProxy = Mock() 14 | 15 | @Unroll 16 | def "should store [#expectedStoredElements] results if min threshold is [#minThreshold]"() { 17 | given: 18 | TestResult testResult = stubbedTestResult() 19 | and: 20 | Set results = [] 21 | TestExecutionResultSavingTestListener listener = new TestExecutionResultSavingTestListener(results, new TestProfilerPluginExtension(minTestThreshold: minThreshold), project) 22 | when: 23 | listener.afterTest(testDescriptor, testResult) 24 | then: 25 | results.size() == expectedStoredElements 26 | where: 27 | minThreshold || expectedStoredElements 28 | 10 || 0 29 | 0 || 1 30 | } 31 | 32 | def 'should display warning if test time execution was too long and user selected that option'() { 33 | given: 34 | TestResult testResult = stubbedTestResult() 35 | and: 36 | TestProfilerPluginExtension extension = new TestProfilerPluginExtension() 37 | extension.buildBreaker { 38 | maxTestThreshold = 1 39 | ifTestsExceedMaxThreshold { 40 | displayWarning() 41 | } 42 | } 43 | and: 44 | Set results = [] 45 | TestExecutionResultSavingTestListener listener = new TestExecutionResultSavingTestListener(results, extension, project, loggerProxy) 46 | when: 47 | listener.afterTest(testDescriptor, testResult) 48 | then: 49 | 1 * loggerProxy.warn({ it.contains('took too long to run')}) 50 | } 51 | 52 | def 'should display warning with custom message if test time execution was too long and user selected that option'() { 53 | given: 54 | TestResult testResult = stubbedTestResult() 55 | and: 56 | TestProfilerPluginExtension extension = new TestProfilerPluginExtension() 57 | extension.buildBreaker { 58 | maxTestThreshold = 1 59 | ifTestsExceedMaxThreshold { 60 | displayWarning { TestDescriptor testDescriptor, TestExecutionResult testExecutionResult -> 61 | 'some text' 62 | } 63 | } 64 | } 65 | and: 66 | Set results = [] 67 | TestExecutionResultSavingTestListener listener = new TestExecutionResultSavingTestListener(results, extension, project, loggerProxy) 68 | when: 69 | listener.afterTest(testDescriptor, testResult) 70 | then: 71 | 1 * loggerProxy.warn({ it == 'some text'}) 72 | } 73 | 74 | def 'should perform custom logic if test time execution was too long and user selected option to act'() { 75 | given: 76 | TestResult testResult = stubbedTestResult() 77 | and: 78 | TestProfilerPluginExtension extension = new TestProfilerPluginExtension() 79 | boolean closureHasBeenCalled = false 80 | extension.buildBreaker { 81 | maxTestThreshold = 1 82 | ifTestsExceedMaxThreshold { 83 | act { LoggerProxy log, TestDescriptor testDescriptor, TestExecutionResult testExecutionResult -> 84 | closureHasBeenCalled = true 85 | } 86 | } 87 | } 88 | and: 89 | Set results = [] 90 | TestExecutionResultSavingTestListener listener = new TestExecutionResultSavingTestListener(results, extension, project, loggerProxy) 91 | when: 92 | listener.afterTest(testDescriptor, testResult) 93 | then: 94 | closureHasBeenCalled 95 | } 96 | 97 | private TestResult stubbedTestResult() { 98 | TestResult testResult = Stub() 99 | testResult.endTime >> 3 100 | testResult.startTime >> 1 101 | return testResult 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/test/groovy/integration/BasicFuncSpec.groovy: -------------------------------------------------------------------------------- 1 | package integration 2 | import nebula.test.IntegrationSpec 3 | import nebula.test.functional.ExecutionResult 4 | import org.gradle.api.logging.LogLevel 5 | 6 | class BasicFuncSpec extends IntegrationSpec { 7 | 8 | void setup() { 9 | fork = true //to make stdout assertion work with Gradle 2.x - http://forums.gradle.org/gradle/topics/unable-to-catch-stdout-stderr-when-using-tooling-api-i-gradle-2-x#reply_15357743 10 | logLevel = LogLevel.DEBUG 11 | } 12 | 13 | def "should not do anything if plugin is disabled"() { 14 | given: 15 | copyResources("project_with_disabled_plugin", "") 16 | when: 17 | ExecutionResult result = runTasksSuccessfully('build', "profileTests") 18 | then: 19 | !taskHasBeenExecuted(result) 20 | and: 21 | !reportsHaveBeenCreated() 22 | } 23 | 24 | def "should create a report and summary for a module that has plugin enabled"() { 25 | given: 26 | copyResources("multimodule_project_with_disabled_plugin", "") 27 | when: 28 | ExecutionResult result = runTasksSuccessfully('build', "profileTests") 29 | then: 30 | taskHasBeenExecuted(result) 31 | and: 32 | !reportExistsForModule('module1') 33 | reportExistsForModule('module2') 34 | and: 35 | reportSummaryHasBeenCreated() 36 | reportSummaryHasNoStatsFromModule1() 37 | 38 | } 39 | 40 | def "should create a summary file with report summary"() { 41 | given: 42 | copyResources("project_without_timeout", "") 43 | when: 44 | ExecutionResult result = runTasksSuccessfully('build', "profileTests") 45 | then: 46 | taskHasBeenExecuted(result) 47 | and: 48 | reportsHaveBeenCreated() 49 | } 50 | 51 | def "should create a summary file with report summary even if pluin was applied before Java plugin"() { 52 | given: 53 | copyResources("project_with_plugin_applied_before_java", "") 54 | when: 55 | ExecutionResult result = runTasksSuccessfully('build', "profileTests") 56 | then: 57 | taskHasBeenExecuted(result) 58 | and: 59 | reportsHaveBeenCreated() 60 | } 61 | 62 | def 'should merge two reports for two separate modules'() { 63 | given: 64 | copyResources("multimodule_project_without_timeout", "") 65 | when: 66 | ExecutionResult result = runTasksSuccessfully('build', "profileTests") 67 | then: 68 | taskHasBeenExecuted(result) 69 | and: 70 | reportExistsForModule('module1') 71 | reportExistsForModule('module2') 72 | and: 73 | reportSummaryHasBeenCreated() 74 | summaryReportContainsMergedValues(file('build/reports/test_profiling/summary.csv').text) 75 | } 76 | 77 | private boolean reportSummaryHasBeenCreated() { 78 | return fileExists("build/reports/test_profiling/summary.csv") 79 | } 80 | 81 | private boolean reportExistsForModule(String module) { 82 | return fileExists("$module/build/reports/test_profiling/testsProfile.csv") 83 | } 84 | 85 | private boolean reportsHaveBeenCreated() { 86 | return fileExists("build/reports/test_profiling/summary.csv") && 87 | fileExists("build/reports/test_profiling/testsProfile.csv") 88 | } 89 | 90 | 91 | private void reportSummaryHasNoStatsFromModule1() { 92 | assert !file('build/reports/test_profiling/summary.csv').text.contains('module1') 93 | } 94 | 95 | private boolean taskHasBeenExecuted(ExecutionResult result) { 96 | return result.standardOutput.contains("Your tests report is ready") 97 | } 98 | 99 | private void summaryReportContainsMergedValues(String reportText) { 100 | summaryReportContainsValuesFromModule('module1', reportText) 101 | summaryReportContainsValuesFromModule('module2', reportText) 102 | } 103 | 104 | private void summaryReportContainsValuesFromModule(String moduleName, String reportText) { 105 | assert reportText.contains(":$moduleName;foo.CalculatorTest;should_add_two_numbers") 106 | assert reportText.contains(":$moduleName;foo.CalculatorTest;should_subtract_a_number_from_another") 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/test/groovy/integration/TimeoutFuncSpec.groovy: -------------------------------------------------------------------------------- 1 | package integration 2 | 3 | import nebula.test.IntegrationSpec 4 | import nebula.test.functional.ExecutionResult 5 | import org.gradle.api.logging.LogLevel 6 | import spock.lang.Unroll 7 | 8 | import java.text.DecimalFormatSymbols 9 | 10 | class TimeoutFuncSpec extends IntegrationSpec { 11 | 12 | void setup() { 13 | fork = true //to make stdout assertion work with Gradle 2.x - http://forums.gradle.org/gradle/topics/unable-to-catch-stdout-stderr-when-using-tooling-api-i-gradle-2-x#reply_15357743 14 | logLevel = LogLevel.DEBUG 15 | } 16 | 17 | @Unroll 18 | def "should fail the tests in project [#projectName] due to timeout"() { 19 | given: 20 | copyResources(projectName, "") 21 | when: 22 | ExecutionResult result = runTasksWithFailure("build", "profileTests") 23 | then: 24 | String stdout = result.standardOutput.toString() 25 | assertThatTestFailed(stdout, 'foo.CalculatorTest') 26 | assertThatTestFailed(stdout, 'foo.CalculatorSpec') 27 | assertThatStandardOutputContains(stdout, 'test timed out after 1 milliseconds') 28 | assertThatStandardOutputContains(stdout, "Method timed out after 0${DecimalFormatSymbols.getInstance().decimalSeparator}00 seconds") 29 | where: 30 | projectName << ['project_with_timeout', 'project_with_timeout_with_spock_1'] 31 | } 32 | 33 | @Unroll 34 | def "should not fail the tests in project [#projectName] due to timeout because of regexps"() { 35 | given: 36 | copyResources(projectName, "") 37 | when: 38 | ExecutionResult result = runTasksWithFailure("build", "profileTests") 39 | then: 40 | String stdout = result.standardOutput.toString() 41 | assertThatTestDidntFail(stdout, 'foo.CalculatorTest') 42 | assertThatTestDidntFail(stdout, 'foo.CalculatorSpec') 43 | assertThatStandardOutputDoesntContain(stdout, 'test timed out after 1 milliseconds') 44 | assertThatStandardOutputDoesntContain(stdout, "Method timed out after 0${DecimalFormatSymbols.getInstance().decimalSeparator}00 seconds") 45 | where: 46 | projectName << ['project_with_timeout_with_regexp', 'project_with_timeout_with_regexp_spock_1'] 47 | } 48 | 49 | void assertThatTestFailed(String standardOutput, String className) { 50 | assert testFailed(standardOutput, className) 51 | } 52 | 53 | void assertThatStandardOutputContains(String standardOutput, String text) { 54 | assert logsContain(standardOutput, text) 55 | } 56 | 57 | void assertThatTestDidntFail(String standardOutput, String className) { 58 | assert !testFailed(standardOutput, className) 59 | } 60 | 61 | void assertThatStandardOutputDoesntContain(String standardOutput, String text) { 62 | assert !logsContain(standardOutput, text) 63 | } 64 | 65 | private boolean testFailed(String standardOutput, String className) { 66 | standardOutput.contains("$className > should_add_two_numbers FAILED") 67 | } 68 | 69 | private boolean logsContain(String standardOutput, String text) { 70 | standardOutput.contains(text) 71 | } 72 | 73 | def "should fail the tests due to timeout even though there already is a timeout set"() { 74 | given: 75 | copyResources("project_with_multiple_timeouts", "") 76 | when: 77 | ExecutionResult result = runTasksWithFailure("build", "profileTests") 78 | then: 79 | result.standardOutput.toString().contains("java.lang.Exception: test timed out after 1 milliseconds") 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/test/resources/META-INF/gradle-plugins/com.blogspot.toomuchcoding.testprofiler.properties: -------------------------------------------------------------------------------- 1 | implementation-class=com.blogspot.toomuchcoding.testprofiler.TestProfilerPlugin 2 | -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_with_disabled_plugin/build.gradle: -------------------------------------------------------------------------------- 1 | allprojects { 2 | apply plugin: 'groovy' 3 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 4 | 5 | repositories { 6 | mavenLocal() 7 | jcenter() 8 | } 9 | 10 | dependencies { 11 | compile "org.codehaus.groovy:groovy-all:2.3.9" 12 | compile "org.slf4j:slf4j-api:1.7.10" 13 | 14 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 15 | testCompile('org.spockframework:spock-core:0.7-groovy-2.0') { 16 | exclude module: 'groovy-all' 17 | } 18 | testRuntime 'cglib:cglib-nodep:2.2.2' 19 | testRuntime 'org.objenesis:objenesis:1.2' 20 | } 21 | 22 | testprofiler { 23 | enabled = false 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_with_disabled_plugin/module1/src/main/java/foo/Calculator.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | public class Calculator { 4 | int add(int first, int second) { 5 | return first + second; 6 | } 7 | 8 | int subtract(int first, int second) { 9 | return first - second; 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_with_disabled_plugin/module1/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Test; 4 | 5 | public class CalculatorTest { 6 | 7 | @Test 8 | public void should_add_two_numbers() { 9 | assert 5 == new foo.Calculator().add(2, 3); 10 | } 11 | 12 | @Test 13 | public void should_subtract_a_number_from_another() { 14 | assert 2 == new foo.Calculator().subtract(3, 1); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_with_disabled_plugin/module2/build.gradle: -------------------------------------------------------------------------------- 1 | testprofiler { 2 | enabled = true 3 | } 4 | -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_with_disabled_plugin/module2/src/main/java/foo/Calculator.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | public class Calculator { 4 | int add(int first, int second) { 5 | return first + second; 6 | } 7 | 8 | int subtract(int first, int second) { 9 | return first - second; 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_with_disabled_plugin/module2/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Test; 4 | 5 | public class CalculatorTest { 6 | 7 | @Test 8 | public void should_add_two_numbers() { 9 | assert 5 == new foo.Calculator().add(2, 3); 10 | } 11 | 12 | @Test 13 | public void should_subtract_a_number_from_another() { 14 | assert 2 == new foo.Calculator().subtract(3, 1); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_with_disabled_plugin/settings.gradle: -------------------------------------------------------------------------------- 1 | include 'module1' 2 | include 'module2' -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_without_timeout/build.gradle: -------------------------------------------------------------------------------- 1 | allprojects { 2 | apply plugin: 'groovy' 3 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 4 | 5 | repositories { 6 | mavenLocal() 7 | jcenter() 8 | } 9 | 10 | dependencies { 11 | compile "org.codehaus.groovy:groovy-all:2.3.9" 12 | compile "org.slf4j:slf4j-api:1.7.10" 13 | 14 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 15 | testCompile('org.spockframework:spock-core:0.7-groovy-2.0') { 16 | exclude module: 'groovy-all' 17 | } 18 | testRuntime 'cglib:cglib-nodep:2.2.2' 19 | testRuntime 'org.objenesis:objenesis:1.2' 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_without_timeout/module1/src/main/java/foo/Calculator.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | public class Calculator { 4 | int add(int first, int second) { 5 | return first + second; 6 | } 7 | 8 | int subtract(int first, int second) { 9 | return first - second; 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_without_timeout/module1/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Test; 4 | 5 | public class CalculatorTest { 6 | 7 | @Test 8 | public void should_add_two_numbers() { 9 | assert 5 == new foo.Calculator().add(2, 3); 10 | } 11 | 12 | @Test 13 | public void should_subtract_a_number_from_another() { 14 | assert 2 == new foo.Calculator().subtract(3, 1); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_without_timeout/module2/src/main/java/foo/Calculator.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | public class Calculator { 4 | int add(int first, int second) { 5 | return first + second; 6 | } 7 | 8 | int subtract(int first, int second) { 9 | return first - second; 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_without_timeout/module2/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Test; 4 | 5 | public class CalculatorTest { 6 | 7 | @Test 8 | public void should_add_two_numbers() { 9 | assert 5 == new foo.Calculator().add(2, 3); 10 | } 11 | 12 | @Test 13 | public void should_subtract_a_number_from_another() { 14 | assert 2 == new foo.Calculator().subtract(3, 1); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/resources/multimodule_project_without_timeout/settings.gradle: -------------------------------------------------------------------------------- 1 | include 'module1' 2 | include 'module2' -------------------------------------------------------------------------------- /src/test/resources/project_with_disabled_plugin/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 3 | 4 | repositories { 5 | mavenLocal() 6 | jcenter() 7 | } 8 | 9 | dependencies { 10 | compile "org.codehaus.groovy:groovy-all:2.3.9" 11 | compile "org.slf4j:slf4j-api:1.7.10" 12 | 13 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 14 | testCompile('org.spockframework:spock-core:0.7-groovy-2.0') { 15 | exclude module: 'groovy-all' 16 | } 17 | testRuntime 'cglib:cglib-nodep:2.2.2' 18 | testRuntime 'org.objenesis:objenesis:1.2' 19 | } 20 | 21 | testprofiler { 22 | enabled = false 23 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_disabled_plugin/src/main/java/foo/Calculator.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | public class Calculator { 4 | int add(int first, int second) { 5 | return first + second; 6 | } 7 | 8 | int subtract(int first, int second) { 9 | return first - second; 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_disabled_plugin/src/test/groovy/foo/CalculatorWithoutTimeoutSpec.groovy: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | import spock.lang.Specification 4 | 5 | class CalculatorWithoutTimeoutSpec extends Specification { 6 | 7 | def 'should add two numbers'() throws Exception { 8 | expect: 9 | Thread.sleep(100) 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_disabled_plugin/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Test; 4 | 5 | public class CalculatorTest { 6 | 7 | @Test 8 | public void should_add_two_numbers() { 9 | assert 5 == new foo.Calculator().add(2, 3); 10 | } 11 | 12 | @Test 13 | public void should_subtract_a_number_from_another() { 14 | assert 2 == new foo.Calculator().subtract(3, 1); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_multiple_timeouts/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 3 | 4 | repositories { 5 | mavenLocal() 6 | jcenter() 7 | } 8 | 9 | dependencies { 10 | compile "org.codehaus.groovy:groovy-all:2.3.9" 11 | compile "org.slf4j:slf4j-api:1.7.10" 12 | 13 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 14 | testCompile('org.spockframework:spock-core:0.7-groovy-2.0') { 15 | exclude module: 'groovy-all' 16 | } 17 | testRuntime 'cglib:cglib-nodep:2.2.2' 18 | testRuntime 'org.objenesis:objenesis:1.2' 19 | } 20 | 21 | testprofiler { 22 | buildBreaker { 23 | maxTestThreshold = 1 24 | ifTestsExceedMaxThreshold { 25 | breakBuild() 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/resources/project_with_multiple_timeouts/src/test/java/foo/AbstractTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Rule; 4 | import org.junit.rules.Timeout; 5 | 6 | public abstract class AbstractTest { 7 | 8 | public @Rule Timeout timeout = new Timeout(10000); 9 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_multiple_timeouts/src/test/java/foo/TestWithThreeTimeoutsShould.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Test; 4 | 5 | public class TestWithThreeTimeoutsShould extends AbstractTest { 6 | 7 | @Test 8 | public void should_fail_because_of_timeout() throws Exception { 9 | Thread.sleep(100); 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_plugin_applied_before_java/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 2 | apply plugin: 'java' 3 | 4 | repositories { 5 | mavenLocal() 6 | jcenter() 7 | } 8 | 9 | dependencies { 10 | compile "org.codehaus.groovy:groovy-all:2.3.9" 11 | compile "org.slf4j:slf4j-api:1.7.10" 12 | 13 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 14 | testCompile('org.spockframework:spock-core:0.7-groovy-2.0') { 15 | exclude module: 'groovy-all' 16 | } 17 | testRuntime 'cglib:cglib-nodep:2.2.2' 18 | testRuntime 'org.objenesis:objenesis:1.2' 19 | } 20 | -------------------------------------------------------------------------------- /src/test/resources/project_with_plugin_applied_before_java/src/main/java/foo/Calculator.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | public class Calculator { 4 | int add(int first, int second) { 5 | return first + second; 6 | } 7 | 8 | int subtract(int first, int second) { 9 | return first - second; 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_plugin_applied_before_java/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Test; 4 | 5 | public class CalculatorTest { 6 | 7 | @Test 8 | public void should_add_two_numbers() { 9 | assert 5 == new foo.Calculator().add(2, 3); 10 | } 11 | 12 | @Test 13 | public void should_subtract_a_number_from_another() { 14 | assert 2 == new foo.Calculator().subtract(3, 1); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 3 | 4 | repositories { 5 | mavenLocal() 6 | jcenter() 7 | } 8 | 9 | dependencies { 10 | compile "org.codehaus.groovy:groovy-all:2.3.9" 11 | compile "org.slf4j:slf4j-api:1.7.10" 12 | 13 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 14 | testCompile('org.spockframework:spock-core:0.7-groovy-2.0') { 15 | exclude module: 'groovy-all' 16 | } 17 | testRuntime 'cglib:cglib-nodep:2.2.2' 18 | testRuntime 'org.objenesis:objenesis:1.2' 19 | } 20 | 21 | testprofiler { 22 | buildBreaker { 23 | maxTestThreshold = 1 24 | ifTestsExceedMaxThreshold { 25 | breakBuild() 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout/src/test/groovy/foo/CalculatorSpec.groovy: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | import spock.lang.Specification 4 | 5 | class CalculatorSpec extends Specification { 6 | 7 | def 'should_add_two_numbers'() { 8 | expect: 9 | Thread.sleep(100) 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Ignore; 4 | import org.junit.Test; 5 | 6 | public class CalculatorTest { 7 | 8 | @Test 9 | public void should_add_two_numbers() throws Exception { 10 | Thread.sleep(100); 11 | } 12 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_regexp/build.gradle: -------------------------------------------------------------------------------- 1 | package project_with_timeout_with_regexp 2 | 3 | apply plugin: 'groovy' 4 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 5 | 6 | repositories { 7 | mavenLocal() 8 | jcenter() 9 | } 10 | 11 | dependencies { 12 | compile "org.codehaus.groovy:groovy-all:2.3.9" 13 | compile "org.slf4j:slf4j-api:1.7.10" 14 | 15 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 16 | testCompile('org.spockframework:spock-core:0.7-groovy-2.0') { 17 | exclude module: 'groovy-all' 18 | } 19 | testRuntime 'cglib:cglib-nodep:2.2.2' 20 | testRuntime 'org.objenesis:objenesis:1.2' 21 | } 22 | 23 | testprofiler { 24 | buildBreaker { 25 | maxTestThreshold = 1 26 | addTestClassRegexpToIgnore 'Calc.*' 27 | ifTestsExceedMaxThreshold { 28 | breakBuild() 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_regexp/src/test/groovy/foo/CalculatorSpec.groovy: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | import spock.lang.Specification 4 | 5 | class CalculatorSpec extends Specification { 6 | 7 | def 'should_add_two_numbers'() { 8 | expect: 9 | Thread.sleep(100) 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_regexp/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Ignore; 4 | import org.junit.Test; 5 | 6 | public class CalculatorTest { 7 | 8 | @Test 9 | public void should_add_two_numbers() throws Exception { 10 | Thread.sleep(100); 11 | } 12 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_regexp_spock_1/build.gradle: -------------------------------------------------------------------------------- 1 | package project_with_timeout_with_regexp_spock_1 2 | 3 | apply plugin: 'groovy' 4 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 5 | 6 | repositories { 7 | mavenLocal() 8 | jcenter() 9 | } 10 | 11 | dependencies { 12 | compile "org.codehaus.groovy:groovy-all:2.4.1" 13 | compile "org.slf4j:slf4j-api:1.7.10" 14 | 15 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 16 | testCompile "org.spockframework:spock-core:1.0-groovy-2.4" 17 | testRuntime 'cglib:cglib-nodep:2.2.2' 18 | testRuntime 'org.objenesis:objenesis:1.2' 19 | } 20 | 21 | testprofiler { 22 | buildBreaker { 23 | maxTestThreshold = 1 24 | addTestClassRegexpToIgnore 'Calc.*' 25 | ifTestsExceedMaxThreshold { 26 | breakBuild() 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_regexp_spock_1/src/test/groovy/foo/CalculatorSpec.groovy: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | import spock.lang.Specification 4 | 5 | class CalculatorSpec extends Specification { 6 | 7 | def 'should_add_two_numbers'() { 8 | expect: 9 | Thread.sleep(100) 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_regexp_spock_1/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Ignore; 4 | import org.junit.Test; 5 | 6 | public class CalculatorTest { 7 | 8 | @Test 9 | public void should_add_two_numbers() throws Exception { 10 | Thread.sleep(100); 11 | } 12 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_spock_1/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 3 | 4 | repositories { 5 | mavenLocal() 6 | jcenter() 7 | } 8 | 9 | dependencies { 10 | compile "org.codehaus.groovy:groovy-all:2.4.1" 11 | compile "org.slf4j:slf4j-api:1.7.10" 12 | 13 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 14 | testCompile "org.spockframework:spock-core:1.0-groovy-2.4" 15 | testRuntime 'cglib:cglib-nodep:2.2.2' 16 | testRuntime 'org.objenesis:objenesis:1.2' 17 | } 18 | 19 | testprofiler { 20 | buildBreaker { 21 | maxTestThreshold = 1 22 | ifTestsExceedMaxThreshold { 23 | breakBuild() 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_spock_1/src/test/groovy/foo/CalculatorSpec.groovy: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | import spock.lang.Specification 4 | 5 | class CalculatorSpec extends Specification { 6 | 7 | def 'should_add_two_numbers'() { 8 | expect: 9 | Thread.sleep(100) 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_with_timeout_with_spock_1/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Ignore; 4 | import org.junit.Test; 5 | 6 | public class CalculatorTest { 7 | 8 | @Test 9 | public void should_add_two_numbers() throws Exception { 10 | Thread.sleep(100); 11 | } 12 | } -------------------------------------------------------------------------------- /src/test/resources/project_without_timeout/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | apply plugin: 'com.blogspot.toomuchcoding.testprofiler' 3 | 4 | repositories { 5 | mavenLocal() 6 | jcenter() 7 | } 8 | 9 | dependencies { 10 | compile "org.codehaus.groovy:groovy-all:2.3.9" 11 | compile "org.slf4j:slf4j-api:1.7.10" 12 | 13 | testRuntime 'org.slf4j:slf4j-log4j12:1.7.10' 14 | testCompile('org.spockframework:spock-core:0.7-groovy-2.0') { 15 | exclude module: 'groovy-all' 16 | } 17 | testRuntime 'cglib:cglib-nodep:2.2.2' 18 | testRuntime 'org.objenesis:objenesis:1.2' 19 | } 20 | -------------------------------------------------------------------------------- /src/test/resources/project_without_timeout/src/main/java/foo/Calculator.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | public class Calculator { 4 | int add(int first, int second) { 5 | return first + second; 6 | } 7 | 8 | int subtract(int first, int second) { 9 | return first - second; 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_without_timeout/src/test/groovy/foo/CalculatorWithoutTimeoutSpec.groovy: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | import spock.lang.Specification 4 | 5 | class CalculatorWithoutTimeoutSpec extends Specification { 6 | 7 | def 'should add two numbers'() throws Exception { 8 | expect: 9 | Thread.sleep(100) 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/project_without_timeout/src/test/java/foo/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package foo; 2 | 3 | import org.junit.Test; 4 | 5 | public class CalculatorTest { 6 | 7 | @Test 8 | public void should_add_two_numbers() { 9 | assert 5 == new foo.Calculator().add(2, 3); 10 | } 11 | 12 | @Test 13 | public void should_subtract_a_number_from_another() { 14 | assert 2 == new foo.Calculator().subtract(3, 1); 15 | } 16 | } --------------------------------------------------------------------------------