├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle ├── buildtools │ └── ColoredOutput.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── com │ └── maxondev │ └── jsif │ ├── Config.java │ ├── FakeServer.java │ ├── ProxyContainer.java │ ├── Recorder.java │ ├── SelfInitializedFake.java │ └── builder │ ├── Build.java │ ├── ListenOnPort.java │ ├── Mode.java │ ├── ProxyTo.java │ ├── RecordTo.java │ ├── SelfInitializingFakeBuilder.java │ └── SelfInitializingFakeSettings.java └── test └── java └── e2e ├── FilesUtils.java └── SelfInitializingFakeE2E.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | ### JetBrains template 4 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 5 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 6 | 7 | # User-specific stuff: 8 | .idea/ 9 | .idea/**/workspace.xml 10 | *.iml 11 | .idea/**/tasks.xml 12 | .idea/dictionaries 13 | # Sensitive or high-churn files: 14 | .idea/**/dataSources/ 15 | .idea/**/dataSources.ids 16 | .idea/**/dataSources.xml 17 | .idea/**/dataSources.local.xml 18 | .idea/**/sqlDataSources.xml 19 | .idea/**/dynamic.xml 20 | .idea/**/uiDesigner.xml 21 | 22 | # Gradle: 23 | .idea/**/gradle.xml 24 | .idea/**/libraries 25 | 26 | # CMake 27 | cmake-build-debug/ 28 | 29 | # Mongo Explorer plugin: 30 | .idea/**/mongoSettings.xml 31 | 32 | ## File-based project format: 33 | *.iws 34 | 35 | ## Plugin-specific files: 36 | 37 | # IntelliJ 38 | out/ 39 | 40 | # mpeltonen/sbt-idea plugin 41 | .idea_modules/ 42 | 43 | # JIRA plugin 44 | atlassian-ide-plugin.xml 45 | 46 | # Cursive Clojure plugin 47 | .idea/replstate.xml 48 | 49 | # Crashlytics plugin (for Android Studio and IntelliJ) 50 | com_crashlytics_export_strings.xml 51 | crashlytics.properties 52 | crashlytics-build.properties 53 | fabric.properties 54 | ### Gradle template 55 | .gradle 56 | /build/ 57 | 58 | # Ignore Gradle GUI config 59 | gradle-app.setting 60 | 61 | # Cache of project 62 | .gradletasknamecache 63 | 64 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 65 | # gradle/wrapper/gradle-wrapper.properties 66 | ### Java template 67 | # Compiled class file 68 | *.class 69 | 70 | # Log file 71 | *.log 72 | 73 | # BlueJ files 74 | *.ctxt 75 | 76 | # Mobile Tools for Java (J2ME) 77 | .mtj.tmp/ 78 | 79 | # Package Files # 80 | *.jar 81 | *.war 82 | *.ear 83 | *.zip 84 | *.tar.gz 85 | *.rar 86 | 87 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 88 | hs_err_pid* 89 | 90 | ### macOS template 91 | # General 92 | .DS_Store 93 | .AppleDouble 94 | .LSOverride 95 | 96 | # Icon must end with two \r 97 | Icon 98 | 99 | # Thumbnails 100 | ._* 101 | 102 | # Files that might appear in the root of a volume 103 | .DocumentRevisions-V100 104 | .fseventsd 105 | .Spotlight-V100 106 | .TemporaryItems 107 | .Trashes 108 | .VolumeIcon.icns 109 | .com.apple.timemachine.donotpresent 110 | 111 | # Directories potentially created on remote AFP share 112 | .AppleDB 113 | .AppleDesktop 114 | Network Trash Folder 115 | Temporary Items 116 | .apdisk 117 | 118 | 119 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 120 | !gradle-wrapper.jar 121 | 122 | # Created when running the tests 123 | src/test/resources/record_then_playback 124 | src/test/resources/sif_recordings 125 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/maximn/jsif.svg?branch=master)](https://travis-ci.org/maximn/jsif) 2 | 3 | 4 | # jsif 5 | Self Initializing Fake library for the JVM (inspired by [https://martinfowler.com/bliki/SelfInitializingFake.html](https://martinfowler.com/bliki/SelfInitializingFake.html)) 6 | 7 | ## What does it do? 8 | It creates a self initialized fake based on a communication with a real server. 9 | On the first time that you run it, it runs in a `Recording` mode, means that it proxies the communication to a real server and at the same time saves the communication in to a file. 10 | On consecutive runs it'll start up in a `Playback` mode, means that it loads the data from the recorded run and behaves like the real server. 11 | 12 | 13 | Let's see a real life example, we have this very basic `Weather` class that communicates with an external Weather service (https://www.metaweather.com/). 14 | This class should have **`Integration Test`** to make sure that it functions correctly. 15 | 16 | 17 | #### *Weather.java* 18 | ``` java 19 | package com.maxondev.sample.app; 20 | 21 | import org.apache.http.client.fluent.Request; 22 | 23 | import java.io.IOException; 24 | import java.net.URLEncoder; 25 | import java.nio.charset.StandardCharsets; 26 | 27 | public class Weather { 28 | 29 | private final String baseUrl; 30 | 31 | public Weather(String baseUrl) { 32 | this.baseUrl = baseUrl; 33 | } 34 | 35 | public String forCity(String city) throws IOException { 36 | String encodedCity = URLEncoder.encode(city, StandardCharsets.UTF_8.name()); 37 | return Request 38 | .Get(baseUrl + "/api/location/search/?query=" + encodedCity) 39 | .execute() 40 | .returnContent() 41 | .asString(); 42 | } 43 | } 44 | ``` 45 | 46 | 47 | That's how the test will look With `jsif` (Java SelfInitializingFake) 48 | 49 | 50 | #### *WeatherIT.java* 51 | ``` java 52 | package com.maxondev.sample.app; 53 | 54 | import com.maxondev.jsif.SelfInitializedFake; 55 | import org.hamcrest.CoreMatchers; 56 | import org.junit.AfterClass; 57 | import org.junit.Assert; 58 | import org.junit.BeforeClass; 59 | import org.junit.Test; 60 | 61 | import java.io.IOException; 62 | 63 | public class WeatherIT { 64 | private static final int fakePort = 8087; 65 | private static final SelfInitializedFake fake = 66 | SelfInitializedFake 67 | .builder() 68 | .proxyTo("https://www.metaweather.com") 69 | .recordTo("weather_recordings") 70 | .listenOnPort(fakePort) 71 | .asAutoMode(); 72 | 73 | @BeforeClass 74 | public static void setUpBeforeClass() { 75 | fake.start(); 76 | } 77 | 78 | @AfterClass 79 | public static void tearDownAfterClass() { 80 | fake.stop(); 81 | } 82 | 83 | @Test 84 | public void forCity_success() throws IOException { 85 | Weather weather = new Weather("http://localhost:" + fakePort); 86 | 87 | String res = weather.forCity("london"); 88 | 89 | Assert.assertThat(res, CoreMatchers.containsString("\"latt_long\":\"51.506321,-0.12714\"")); 90 | } 91 | 92 | @Test 93 | public void forCity_wrongCity_emptyResult() throws IOException { 94 | Weather weather = new Weather("http://localhost:" + fakePort); 95 | 96 | String res = weather.forCity("london"); 97 | 98 | Assert.assertThat(res, CoreMatchers.containsString("\"latt_long\":\"51.506321,-0.12714\"")); 99 | } 100 | } 101 | ``` 102 | 103 | 104 | 105 | ### How does it work? 106 | When running for the first time, you'll see in the log 107 | ``[main] INFO com.maxondev.jsif.SelfInitializedFake - Starting in `Record` mode`` 108 | And the `Fake` will initialize itself - It'll proxy the communication to the real external server and record it. The communication will be persisted in into a json file (under test/resources/weather_recordings) 109 | 110 | 111 | The next time that you'll run it, you'll see in the log 112 | ``[main] INFO com.maxondev.jsif.SelfInitializedFake - Starting in `Play` mode`` 113 | The `Fake` will run in `Play` mode now and it'll interact in the same way, but this time instead of proxying the traffic to the real server it'll use the persisted communication from the first run. 114 | 115 | 116 | 117 | 118 | #### Under the hood? 119 | This library uses `WireMock` library ([http://wiremock.org/](http://wiremock.org/)) for the recording & playback. 120 | It wraps `WireMock` and allows an easy `Self Initializing Fake`. -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply from: 'gradle/buildtools/ColoredOutput.gradle' 2 | project.ext.set("TRAVIS_FOLDING", true) 3 | 4 | apply plugin: 'java-library' 5 | 6 | apply plugin: 'maven' 7 | 8 | task javadocJar(type: Jar) { 9 | classifier = 'javadoc' 10 | from javadoc 11 | } 12 | 13 | task sourcesJar(type: Jar) { 14 | classifier = 'sources' 15 | from sourceSets.main.allSource 16 | } 17 | 18 | artifacts { 19 | archives javadocJar, sourcesJar 20 | } 21 | 22 | if (project.hasProperty("signing.keyId")) { 23 | apply plugin: 'signing' 24 | signing { 25 | sign configurations.archives 26 | } 27 | } 28 | 29 | group = "com.maxondev.jsif" 30 | archivesBaseName = "jsif" 31 | version = "0.1.3" 32 | 33 | if (hasProperty('ossrhUsername')) 34 | uploadArchives { 35 | repositories { 36 | mavenDeployer { 37 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 38 | 39 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 40 | authentication(userName: ossrhUsername, password: ossrhPassword) 41 | } 42 | 43 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 44 | authentication(userName: ossrhUsername, password: ossrhPassword) 45 | } 46 | 47 | pom.project { 48 | name 'JVM Self Initializing Fake' 49 | packaging 'jar' 50 | // optionally artifactId can be defined here 51 | description 'Self Initializing Fake library for the JVM (inspired by https://martinfowler.com/bliki/SelfInitializingFake.html)' 52 | url 'https://github.com/maximn/jsif' 53 | 54 | scm { 55 | connection 'scm:git:https://github.com/maximn/jsif.git' 56 | developerConnection 'scm:git:https://github.com/maximn/jsif.git' 57 | url 'https://github.com/maximn/jsif.git' 58 | } 59 | 60 | licenses { 61 | license { 62 | name 'The Apache License, Version 2.0' 63 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 64 | } 65 | } 66 | 67 | developers { 68 | developer { 69 | id 'maxim' 70 | name 'Maxim Novak' 71 | email 'maxim.novak@gmail.com' 72 | } 73 | } 74 | } 75 | } 76 | } 77 | } 78 | 79 | repositories { 80 | jcenter() 81 | } 82 | 83 | dependencies { 84 | testImplementation 'junit:junit:4.12' 85 | 86 | compile group: 'com.github.tomakehurst', name: 'wiremock', version: '2.24.1' 87 | testCompile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.4' 88 | testCompile group: 'org.apache.httpcomponents', name: 'fluent-hc', version: '4.5.4' 89 | testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25' 90 | } 91 | 92 | -------------------------------------------------------------------------------- /gradle/buildtools/ColoredOutput.gradle: -------------------------------------------------------------------------------- 1 | //https://github.com/mendhak/Gradle-Travis-Colored-Output 2 | tasks.withType(Test) { 3 | 4 | boolean TRAVIS_FOLDING = project.hasProperty('TRAVIS_FOLDING') ? project.TRAVIS_FOLDING : false 5 | String ANSI_BOLD_WHITE = "\u001B[0;1m"; 6 | String ANSI_RESET = "\u001B[0m"; 7 | String ANSI_BLACK = "\u001B[30m"; 8 | String ANSI_RED = "\u001B[31m"; 9 | String ANSI_GREEN = "\u001B[32m"; 10 | String ANSI_YELLOW = "\u001B[33m"; 11 | String ANSI_BLUE = "\u001B[34m"; 12 | String ANSI_PURPLE = "\u001B[35m"; 13 | String ANSI_CYAN = "\u001B[36m"; 14 | String ANSI_WHITE = "\u001B[37m"; 15 | String CHECK_MARK = "\u2713"; 16 | String NEUTRAL_FACE = "\u0CA0_\u0CA0"; 17 | String X_MARK = "\u274C"; 18 | 19 | beforeSuite { suite -> 20 | if (suite.name.startsWith("Test Run") || suite.name.startsWith("Gradle Worker")) return 21 | 22 | if(suite.parent != null && suite.className != null){ 23 | if(TRAVIS_FOLDING){ out.println("travis_fold:start:" + suite.name +"\r"); } 24 | out.println(ANSI_BOLD_WHITE + suite.name + ANSI_RESET ) 25 | } 26 | 27 | } 28 | afterTest { descriptor, result -> 29 | def indicator = ANSI_WHITE 30 | 31 | if (result.failedTestCount > 0) indicator = ANSI_RED + X_MARK 32 | else if (result.skippedTestCount > 0) indicator = ANSI_YELLOW + NEUTRAL_FACE 33 | else indicator = ANSI_GREEN + CHECK_MARK 34 | 35 | out.println(' ' + indicator + ANSI_RESET + " " + descriptor.name); 36 | 37 | if (result.failedTestCount > 0) { out.println(' ') } 38 | 39 | } 40 | 41 | afterSuite { desc, result -> 42 | if(desc.parent != null && desc.className != null){ 43 | 44 | if(TRAVIS_FOLDING && result.failedTestCount==0) { out.println("travis_fold:end:" + desc.name +"\r"); } 45 | out.println("") 46 | } 47 | 48 | 49 | if (!desc.parent) { // will match the outermost suite 50 | def failStyle = ANSI_RED 51 | def skipStyle = ANSI_YELLOW 52 | def summaryStyle = ANSI_WHITE 53 | if(result.failedTestCount>0){ failStyle = ANSI_RED } 54 | if(result.skippedTestCount > 0) { skipStyle = ANSI_YELLOW } 55 | 56 | switch(result.resultType){ 57 | case TestResult.ResultType.SUCCESS: 58 | summaryStyle = ANSI_GREEN; 59 | break; 60 | case TestResult.ResultType.FAILURE: 61 | summaryStyle = ANSI_RED; 62 | break; 63 | } 64 | 65 | out.println( "--------------------------------------------------------------------------"); 66 | out.println( "Results: " + summaryStyle + "${result.resultType}" + ANSI_RESET 67 | + " (${result.testCount} tests, " 68 | + ANSI_GREEN + "${result.successfulTestCount} passed" + ANSI_RESET 69 | + ", " + failStyle + "${result.failedTestCount} failed" + ANSI_RESET 70 | + ", " + skipStyle + "${result.skippedTestCount} skipped" + ANSI_RESET 71 | + ")"); 72 | out.println( "--------------------------------------------------------------------------"); 73 | } 74 | } 75 | 76 | } 77 | 78 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maximn/jsif/1cdc1b56e4c394eb07dd66d15bae735975e83e25/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Aug 25 21:37:59 IDT 2019 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-5.6-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin, switch paths to Windows format before running java 129 | if $cygwin ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=$((i+1)) 158 | done 159 | case $i in 160 | (0) set -- ;; 161 | (1) set -- "$args0" ;; 162 | (2) set -- "$args0" "$args1" ;; 163 | (3) set -- "$args0" "$args1" "$args2" ;; 164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=$(save "$@") 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 185 | cd "$(dirname "$0")" 186 | fi 187 | 188 | exec "$JAVACMD" "$@" 189 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * In a single project build this file can be empty or even removed. 6 | * 7 | * Detailed information about configuring a multi-project build in Gradle can be found 8 | * in the user guide at https://docs.gradle.org/4.4/userguide/multi_project_builds.html 9 | */ 10 | 11 | /* 12 | // To declare projects as part of a multi-project build use the 'include' method 13 | include 'shared' 14 | include 'api' 15 | include 'services:webservice' 16 | */ 17 | 18 | rootProject.name = 'jsif' 19 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/Config.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif; 2 | 3 | class Config { 4 | final static String ROOT_PATH ="src/test/resources/"; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/FakeServer.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif; 2 | 3 | import com.github.tomakehurst.wiremock.WireMockServer; 4 | import com.github.tomakehurst.wiremock.common.SingleRootFileSource; 5 | 6 | class FakeServer { 7 | private final WireMockServer wireMockServer; 8 | 9 | FakeServer(int port, String pathToLoad) { 10 | this.wireMockServer = 11 | new WireMockServer(port, 12 | new SingleRootFileSource(Config.ROOT_PATH + pathToLoad), 13 | false); 14 | } 15 | 16 | void start() { 17 | wireMockServer.start(); 18 | } 19 | 20 | void stop() { 21 | wireMockServer.stop(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/ProxyContainer.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif; 2 | 3 | class ProxyContainer { 4 | 5 | private final Object proxy; 6 | 7 | ProxyContainer(Object proxy) { 8 | this.proxy = proxy; 9 | } 10 | 11 | void stop() { 12 | if (proxy instanceof Recorder) { 13 | ((Recorder) proxy).stop(); 14 | } else if (proxy instanceof FakeServer) { 15 | ((FakeServer) proxy).stop(); 16 | } else { 17 | throw new IllegalStateException("Proxy is of unknown type : " + proxy.getClass().getName()); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/Recorder.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif; 2 | 3 | import com.github.tomakehurst.wiremock.WireMockServer; 4 | import com.github.tomakehurst.wiremock.common.Slf4jNotifier; 5 | import com.github.tomakehurst.wiremock.core.Options; 6 | import com.github.tomakehurst.wiremock.core.WireMockApp; 7 | import com.github.tomakehurst.wiremock.core.WireMockConfiguration; 8 | 9 | import java.io.File; 10 | 11 | import static com.maxondev.jsif.Config.ROOT_PATH; 12 | 13 | class Recorder { 14 | final private WireMockServer wireMockServer; 15 | final private String proxyTo; 16 | final private String recordingPath; 17 | 18 | Recorder(int port, String proxyTo, String pathToSave) { 19 | this.proxyTo = proxyTo; 20 | 21 | this.recordingPath = ROOT_PATH + pathToSave; 22 | Options options = new WireMockConfiguration() 23 | .port(port) 24 | .withRootDirectory(recordingPath) 25 | .notifier(new Slf4jNotifier(true)); 26 | this.wireMockServer = new WireMockServer(options); 27 | 28 | Runtime.getRuntime().addShutdownHook(new Thread(() -> { 29 | if (wireMockServer.isRunning()) 30 | this.stop(); 31 | })); 32 | } 33 | 34 | void record() { 35 | File recordingRoot = new File(recordingPath); 36 | if (!(new File(recordingRoot, WireMockApp.MAPPINGS_ROOT)).mkdirs()) 37 | throw new RuntimeException("Couldn't create directory : " + recordingRoot.toString()); 38 | 39 | wireMockServer.startRecording(proxyTo); 40 | wireMockServer.start(); 41 | } 42 | 43 | void stop() { 44 | wireMockServer.stopRecording(); 45 | wireMockServer.stop(); 46 | } 47 | } -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/SelfInitializedFake.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif; 2 | 3 | import com.maxondev.jsif.builder.Mode; 4 | import com.maxondev.jsif.builder.ProxyTo; 5 | import com.maxondev.jsif.builder.SelfInitializingFakeBuilder; 6 | import com.maxondev.jsif.builder.SelfInitializingFakeSettings; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import java.io.File; 11 | 12 | import static com.maxondev.jsif.Config.ROOT_PATH; 13 | 14 | public final class SelfInitializedFake { 15 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 16 | private boolean started; 17 | private ProxyContainer proxyContainer; 18 | private final SelfInitializingFakeSettings settings; 19 | 20 | public SelfInitializedFake(SelfInitializingFakeSettings settings) { 21 | this.started = false; 22 | 23 | this.settings = settings; 24 | } 25 | 26 | public void start() { 27 | if (started) { 28 | throw new IllegalStateException("Already started"); 29 | } 30 | 31 | Mode mode = evaluateRunningMode(); 32 | 33 | switch (mode) { 34 | case RECORDER: 35 | record(); 36 | break; 37 | case FAKE_SERVER: 38 | play(); 39 | break; 40 | } 41 | } 42 | 43 | private void play() { 44 | logger.info("Starting in `Play` mode"); 45 | FakeServer fake = new FakeServer(settings.getPort(), settings.getRecordDirectory()); 46 | this.proxyContainer = new ProxyContainer(fake); 47 | fake.start(); 48 | } 49 | 50 | private void record() { 51 | logger.info("Starting in `Recorder` mode"); 52 | Recorder recorder = new Recorder(settings.getPort(), settings.getProxyToUrl(), settings.getRecordDirectory()); 53 | this.proxyContainer = new ProxyContainer(recorder); 54 | recorder.record(); 55 | } 56 | 57 | private Mode evaluateRunningMode() { 58 | Mode actualMode = settings.getMode(); 59 | if (Mode.AUTO == actualMode) 60 | if (recordingExists()) 61 | actualMode = Mode.FAKE_SERVER; 62 | else 63 | actualMode = Mode.RECORDER; 64 | return actualMode; 65 | } 66 | 67 | private boolean recordingExists() { 68 | return new File(ROOT_PATH + settings.getRecordDirectory()).exists(); 69 | } 70 | 71 | public void stop() { 72 | proxyContainer.stop(); 73 | started = false; 74 | proxyContainer = null; 75 | } 76 | 77 | public static ProxyTo builder() { 78 | return SelfInitializingFakeBuilder.builder(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/builder/Build.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif.builder; 2 | 3 | import com.maxondev.jsif.SelfInitializedFake; 4 | 5 | public interface Build { 6 | SelfInitializedFake asAutoMode(); 7 | SelfInitializedFake asFakeServer(); 8 | SelfInitializedFake asRecorder(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/builder/ListenOnPort.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif.builder; 2 | 3 | public interface ListenOnPort { 4 | Build listenOnPort(int port); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/builder/Mode.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif.builder; 2 | 3 | public enum Mode { 4 | AUTO, RECORDER, FAKE_SERVER; 5 | 6 | Mode() { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/builder/ProxyTo.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif.builder; 2 | 3 | public interface ProxyTo { 4 | RecordTo proxyTo(String url); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/builder/RecordTo.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif.builder; 2 | 3 | public interface RecordTo { 4 | ListenOnPort recordTo(String directoryName); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/builder/SelfInitializingFakeBuilder.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif.builder; 2 | 3 | import com.maxondev.jsif.SelfInitializedFake; 4 | 5 | public final class SelfInitializingFakeBuilder implements ProxyTo, RecordTo, ListenOnPort, Build { 6 | private final SelfInitializingFakeSettings settings = new SelfInitializingFakeSettings(); 7 | 8 | 9 | private SelfInitializingFakeBuilder() { 10 | } 11 | 12 | public static ProxyTo builder() { 13 | return new SelfInitializingFakeBuilder(); 14 | } 15 | 16 | @Override 17 | public ListenOnPort recordTo(String directoryName) { 18 | settings.setRecordDirectory(directoryName); 19 | return this; 20 | } 21 | 22 | 23 | @Override 24 | public RecordTo proxyTo(String url) { 25 | settings.setProxyToUrl(url); 26 | return this; 27 | } 28 | 29 | @Override 30 | public Build listenOnPort(int port) { 31 | settings.setPort(port); 32 | return this; 33 | } 34 | 35 | @Override 36 | public SelfInitializedFake asAutoMode() { 37 | settings.setMode(Mode.AUTO); 38 | return new SelfInitializedFake(settings); 39 | } 40 | 41 | @Override 42 | public SelfInitializedFake asFakeServer() { 43 | settings.setMode(Mode.FAKE_SERVER); 44 | return new SelfInitializedFake(settings); 45 | } 46 | 47 | @Override 48 | public SelfInitializedFake asRecorder() { 49 | settings.setMode(Mode.RECORDER); 50 | return new SelfInitializedFake(settings); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/maxondev/jsif/builder/SelfInitializingFakeSettings.java: -------------------------------------------------------------------------------- 1 | package com.maxondev.jsif.builder; 2 | 3 | public final class SelfInitializingFakeSettings { 4 | private String proxyToUrl; 5 | private String recordDirectory; 6 | private int port; 7 | private Mode mode; 8 | 9 | public String getProxyToUrl() { 10 | return proxyToUrl; 11 | } 12 | 13 | public Mode getMode() { 14 | return mode; 15 | } 16 | 17 | void setMode(Mode mode) { 18 | this.mode = mode; 19 | } 20 | 21 | void setProxyToUrl(String proxyToUrl) { 22 | this.proxyToUrl = proxyToUrl; 23 | } 24 | 25 | public String getRecordDirectory() { 26 | return recordDirectory; 27 | } 28 | 29 | void setRecordDirectory(String recordDirectory) { 30 | this.recordDirectory = recordDirectory; 31 | } 32 | 33 | public int getPort() { 34 | return port; 35 | } 36 | 37 | void setPort(int port) { 38 | this.port = port; 39 | } 40 | 41 | SelfInitializingFakeSettings() { 42 | } 43 | } -------------------------------------------------------------------------------- /src/test/java/e2e/FilesUtils.java: -------------------------------------------------------------------------------- 1 | package e2e; 2 | 3 | import java.io.File; 4 | import java.util.Objects; 5 | 6 | class FilesUtils { 7 | static boolean deleteRecursive(File path) { 8 | boolean deletedSuccessfully = true; 9 | if (path.isDirectory()) { 10 | for (File f : Objects.requireNonNull(path.listFiles())) { 11 | deletedSuccessfully = deletedSuccessfully && deleteRecursive(f); 12 | } 13 | } 14 | return deletedSuccessfully && path.delete(); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/java/e2e/SelfInitializingFakeE2E.java: -------------------------------------------------------------------------------- 1 | package e2e; 2 | 3 | import com.github.tomakehurst.wiremock.WireMockServer; 4 | import com.maxondev.jsif.SelfInitializedFake; 5 | import org.apache.http.client.fluent.Content; 6 | import org.apache.http.client.fluent.Request; 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.util.UUID; 13 | 14 | import static com.github.tomakehurst.wiremock.client.WireMock.*; 15 | 16 | public class SelfInitializingFakeE2E { 17 | private final static int dummyPort = 7088; 18 | private final static int proxyPort = 7089; 19 | private final String baseUrl = "http://localhost"; 20 | private final String httpPath = "/some/thing"; 21 | private final String proxyTo = baseUrl + ":" + dummyPort; 22 | 23 | private WireMockServer setUpDummyRemoteServer() { 24 | WireMockServer dummy = new WireMockServer(dummyPort); 25 | dummy.stubFor(get(urlEqualTo(httpPath)) 26 | .willReturn(aResponse() 27 | .withBody("Hello world!" + UUID.randomUUID().toString()))); 28 | dummy.start(); 29 | return dummy; 30 | } 31 | 32 | private String doHttpCall(int port) throws IOException { 33 | Content content = Request.Get(baseUrl + ":" + port + httpPath) 34 | .execute().returnContent(); 35 | return content.asString(); 36 | } 37 | 38 | @Test 39 | public void selfInitializedFake() throws IOException { 40 | String path = "sif_recordings"; 41 | cleanUpRecordings(path); 42 | 43 | SelfInitializedFake fake = SelfInitializedFake 44 | .builder() 45 | .proxyTo(proxyTo) 46 | .recordTo(path) 47 | .listenOnPort(proxyPort) 48 | .asAutoMode(); 49 | 50 | fake.start(); // no recording yet, so will start in `recorder mode` 51 | WireMockServer dummy = setUpDummyRemoteServer(); 52 | 53 | String resultFromRemote = doHttpCall(proxyPort); 54 | 55 | fake.stop(); 56 | dummy.stop(); 57 | 58 | fake.start(); // this time it should start up in `Player` mode 59 | 60 | String recordedResult = doHttpCall(proxyPort); 61 | fake.stop(); 62 | 63 | Assert.assertEquals(resultFromRemote, recordedResult); 64 | } 65 | 66 | @Test 67 | public void recordThenPlayback() throws IOException { 68 | String recordingsPath = "record_then_playback"; 69 | cleanUpRecordings(recordingsPath); 70 | 71 | // Start up recorder 72 | SelfInitializedFake recorder = SelfInitializedFake 73 | .builder() 74 | .proxyTo(proxyTo) 75 | .recordTo(recordingsPath) 76 | .listenOnPort(proxyPort) 77 | .asRecorder(); 78 | recorder.start(); 79 | 80 | // set up dummy server 81 | WireMockServer dummy = setUpDummyRemoteServer(); 82 | 83 | // do call proxying via jisf proxy (test -> recorder -> dummy -> recorder -> test) 84 | String resultFromRemote = doHttpCall(proxyPort); 85 | 86 | // Now we can stop both remote server & recorder proxy 87 | recorder.stop(); 88 | dummy.stop(); 89 | 90 | // Let's load recorded data and start the fake 91 | SelfInitializedFake fake = SelfInitializedFake 92 | .builder() 93 | .proxyTo(proxyTo) 94 | .recordTo(recordingsPath) 95 | .listenOnPort(proxyPort) 96 | .asFakeServer(); 97 | 98 | fake.start(); 99 | 100 | // This call will go to the recorded fake 101 | String recordedResult = doHttpCall(proxyPort); 102 | 103 | fake.stop(); 104 | 105 | Assert.assertEquals(resultFromRemote, recordedResult); 106 | } 107 | 108 | private void cleanUpRecordings(String path) { 109 | FilesUtils.deleteRecursive(new File("src/test/resources/", path)); 110 | } 111 | 112 | } --------------------------------------------------------------------------------