├── javabank.gpg.enc
├── javabank-core
├── src
│ ├── test
│ │ ├── resources
│ │ │ └── response.json
│ │ └── java
│ │ │ └── org
│ │ │ └── mbtest
│ │ │ └── javabank
│ │ │ ├── fluent
│ │ │ ├── IsBuilderTest.java
│ │ │ ├── InjectBuilderTest.java
│ │ │ ├── ResponseTypeBuilderTest.java
│ │ │ ├── ResponseBuilderTest.java
│ │ │ └── ImposterBuilderTest.java
│ │ │ ├── http
│ │ │ ├── responses
│ │ │ │ └── InjectTest.java
│ │ │ ├── core
│ │ │ │ ├── StubTest.java
│ │ │ │ └── IsTest.java
│ │ │ ├── imposters
│ │ │ │ └── ImposterTest.java
│ │ │ └── predicates
│ │ │ │ └── PredicateTest.java
│ │ │ └── ImposterParserTest.java
│ └── main
│ │ ├── java
│ │ └── org
│ │ │ └── mbtest
│ │ │ └── javabank
│ │ │ ├── fluent
│ │ │ ├── FluentBuilder.java
│ │ │ ├── ResponseTypeBuilder.java
│ │ │ ├── InjectBuilder.java
│ │ │ ├── ResponseBuilder.java
│ │ │ ├── ImposterBuilder.java
│ │ │ ├── PredicateValueBuilder.java
│ │ │ ├── StubBuilder.java
│ │ │ ├── IsBuilder.java
│ │ │ └── PredicateTypeBuilder.java
│ │ │ ├── http
│ │ │ ├── responses
│ │ │ │ ├── Inject.java
│ │ │ │ ├── Response.java
│ │ │ │ └── Is.java
│ │ │ ├── predicates
│ │ │ │ ├── PredicateType.java
│ │ │ │ └── Predicate.java
│ │ │ ├── core
│ │ │ │ └── Stub.java
│ │ │ └── imposters
│ │ │ │ └── Imposter.java
│ │ │ └── ImposterParser.java
│ │ └── config
│ │ └── settings.xml.example
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── settings.gradle
├── .gitignore
├── javabank-client
├── build.gradle
└── src
│ ├── main
│ └── java
│ │ └── org
│ │ └── mbtest
│ │ └── javabank
│ │ └── Client.java
│ └── test
│ └── java
│ └── org
│ └── mbtest
│ └── javabank
│ └── ClientTest.java
├── .travis.yml
├── increment_version.sh
├── LICENSE
├── README.md
├── gradlew.bat
└── gradlew
/javabank.gpg.enc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thejamesthomas/javabank/HEAD/javabank.gpg.enc
--------------------------------------------------------------------------------
/javabank-core/src/test/resources/response.json:
--------------------------------------------------------------------------------
1 | {
2 | "name1": "value1",
3 | "name2": "value2"
4 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thejamesthomas/javabank/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | org.gradle.daemon=true
2 | org.gradle.parallel=true
3 |
4 | majorVersion=0
5 | minorVersion=4
6 | patchVersion=11
7 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'javabank-all'
2 |
3 | include 'javabank-client', 'javabank-core'
4 |
5 | enableFeaturePreview('STABLE_PUBLISHING')
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | .gradle/
3 | target/
4 | build/
5 | *.iml
6 | *.imr
7 | *.iws
8 | *.patch
9 | *.token
10 | *.key
11 | *.versionsBackup
12 | .DS_Store
13 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/FluentBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | public interface FluentBuilder {
4 | Object end();
5 | }
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Jun 19 20:55:19 CDT 2018
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-4.8-all.zip
7 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/http/responses/Inject.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.responses;
2 |
3 | public class Inject extends Response {
4 | private static final String INJECT = "inject";
5 |
6 | public Inject() {
7 | this.put(INJECT, "");
8 | }
9 |
10 | public Inject withFunction(String function) {
11 | this.put(INJECT, function);
12 | return this;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/http/responses/Response.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.responses;
2 |
3 | import org.json.simple.JSONObject;
4 |
5 | import java.util.HashMap;
6 |
7 | public abstract class Response extends HashMap {
8 |
9 | public JSONObject getJSON() {
10 | return new JSONObject(this);
11 | }
12 |
13 | public String toString() {
14 | return getJSON().toJSONString();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/javabank-core/build.gradle:
--------------------------------------------------------------------------------
1 | dependencies {
2 | annotationProcessor 'org.projectlombok:lombok:1.18.2'
3 | compileOnly 'org.projectlombok:lombok:1.18.2'
4 | compile 'com.google.guava:guava:25.1-jre'
5 | compile 'com.googlecode.json-simple:json-simple:1.1.1'
6 | compile 'org.apache.httpcomponents:httpclient:4.5.5'
7 |
8 | testCompile 'junit:junit:4.12'
9 | testCompile 'org.mockito:mockito-core:2.19.0'
10 | testCompile 'org.assertj:assertj-core:3.6.2'
11 | }
--------------------------------------------------------------------------------
/javabank-client/build.gradle:
--------------------------------------------------------------------------------
1 | dependencies {
2 | compile project(':javabank-core')
3 | compile 'com.mashape.unirest:unirest-java:1.4.9'
4 |
5 | testCompile 'junit:junit:4.12'
6 | testCompile 'org.mockito:mockito-core:2.19.0'
7 | testCompile 'org.powermock:powermock-api-mockito2:2.0.0-beta.5'
8 | testCompile 'org.powermock:powermock-core:2.0.0-beta.5'
9 | testCompile 'org.powermock:powermock-module-junit4:2.0.0-beta.5'
10 | testCompile 'org.assertj:assertj-core:3.6.2'
11 | }
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/ImposterParser.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank;
2 |
3 | import org.json.simple.JSONObject;
4 | import org.json.simple.parser.JSONParser;
5 | import org.json.simple.parser.ParseException;
6 | import org.mbtest.javabank.http.imposters.Imposter;
7 |
8 | public class ImposterParser {
9 |
10 | public static Imposter parse(String json) throws ParseException {
11 | JSONObject parsedJson = (JSONObject) new JSONParser().parse(json);
12 |
13 | return Imposter.fromJSON(parsedJson);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/ResponseTypeBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.mbtest.javabank.http.responses.Response;
4 |
5 | public abstract class ResponseTypeBuilder implements FluentBuilder {
6 | private ResponseBuilder parent;
7 |
8 | protected ResponseTypeBuilder(ResponseBuilder parent) {
9 | this.parent = parent;
10 | }
11 |
12 | @Override
13 | public ResponseBuilder end() {
14 | return parent;
15 | }
16 |
17 | abstract protected Response build();
18 | }
19 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jobs:
3 | include:
4 | - stage: test
5 | script: ./gradlew test
6 | - stage: publish
7 | script: ./gradlew publish -PossrhUsername="${OSSRH_USERNAME}" -PossrhPassword="${OSSRH_PASSWORD}" -Psigning.keyId="${SIGNING_KEY}" -Psigning.password="${SIGNING_PASSWORD}" -Psigning.secretKeyRingFile="`pwd`/javabank.gpg"
8 |
9 | stages:
10 | - test
11 | - name: publish
12 | if: branch = master
13 | before_install:
14 | - openssl aes-256-cbc -K $encrypted_676823bf0942_key -iv $encrypted_676823bf0942_iv
15 | -in javabank.gpg.enc -out javabank.gpg -d
16 | - gpg --import javabank.gpg
17 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/http/predicates/PredicateType.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.predicates;
2 |
3 | import lombok.Getter;
4 |
5 | public enum PredicateType {
6 | EQUALS("equals"),
7 | DEEP_EQUALS("deepEquals"),
8 | CONTAINS("contains"),
9 | STARTS_WITH("startsWith"),
10 | ENDS_WITH("endsWith"),
11 | MATCHES("matches"),
12 | EXISTS("exists"),
13 | NOT("not"),
14 | OR("or"),
15 | AND("and"),
16 | INJECT("inject");
17 |
18 | @Getter
19 | private String value;
20 |
21 | PredicateType(String value) {
22 |
23 | this.value = value;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/InjectBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.mbtest.javabank.http.responses.Inject;
4 |
5 | public class InjectBuilder extends ResponseTypeBuilder {
6 | private String function = "";
7 |
8 | public InjectBuilder(ResponseBuilder responseBuilder) {
9 | super(responseBuilder);
10 | }
11 |
12 | public InjectBuilder function(String function) {
13 | this.function = function;
14 | return this;
15 | }
16 |
17 | @Override
18 | protected Inject build() {
19 | return new Inject().withFunction(function);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/fluent/IsBuilderTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.junit.Test;
4 | import org.mbtest.javabank.http.responses.Is;
5 |
6 | import java.io.File;
7 |
8 | import static org.assertj.core.api.Assertions.assertThat;
9 |
10 | public class IsBuilderTest {
11 |
12 | @Test
13 | public void testBuildWithFileBody() throws Exception {
14 | IsBuilder testSubject = new IsBuilder(null);
15 | final Is is = testSubject.body(new File("src/test/resources/response.json")).build();
16 |
17 | assertThat(is.getBody()).contains("name1", "value1", "name2", "value2");
18 | }
19 | }
--------------------------------------------------------------------------------
/javabank-core/src/main/config/settings.xml.example:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ossrh
6 | ${jira.username}
7 | ${jira.password}
8 |
9 |
10 |
11 |
12 | ossrh
13 |
14 | true
15 |
16 |
17 | gpg
18 | ${gpg.passphrase}
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/increment_version.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | MAJOR="$(grep majorVersion gradle.properties | cut -d = -f2)"
4 | MINOR="$(grep minorVersion gradle.properties | cut -d = -f2)"
5 | PATCH="$(grep patchVersion gradle.properties | cut -d = -f2)"
6 | NEW_PATCH=$((PATCH + 1))
7 |
8 | if hash gsed 2>/dev/null; then
9 | #The default version of sed on OSX is not good, so use gsed (which can be installed via
10 | #homebrew with 'brew install gnu-sed') if it's available. I'll want to make this
11 | #a little more robust later on
12 | gsed -i s/patchVersion=$PATCH/patchVersion=$NEW_PATCH/g gradle.properties
13 | else
14 | #I'm assuming that this will be gnu-sed. I'll need to make this a little more
15 | #strict at some point
16 | sed -i s/patchVersion=$PATCH/patchVersion=$NEW_PATCH/g gradle.properties
17 | fi
18 |
19 | git add gradle.properties
20 | git commit --author "CI " -m "Updating to version $MAJOR.$MINOR.$NEW_PATCH [skip ci]"
21 | git push origin master
22 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/ResponseBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.mbtest.javabank.http.responses.Response;
4 |
5 | public class ResponseBuilder implements FluentBuilder {
6 | private StubBuilder parent;
7 | private ResponseTypeBuilder builder;
8 |
9 | protected ResponseBuilder(StubBuilder stubBuilder) {
10 | this.parent = stubBuilder;
11 | }
12 |
13 | public IsBuilder is() {
14 | builder = new IsBuilder(this);
15 | return (IsBuilder) builder;
16 | }
17 |
18 | public InjectBuilder inject() {
19 | builder = new InjectBuilder(this);
20 | return (InjectBuilder) builder;
21 | }
22 |
23 | @Override
24 | public StubBuilder end() {
25 | return parent;
26 | }
27 |
28 | protected Response build() {
29 | if(builder != null) return builder.build();
30 |
31 | return new IsBuilder(this).build();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/fluent/InjectBuilderTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 | import org.mbtest.javabank.http.responses.Inject;
6 |
7 | import static org.hamcrest.MatcherAssert.assertThat;
8 | import static org.hamcrest.core.Is.is;
9 | import static org.mockito.Mockito.mock;
10 |
11 | public class InjectBuilderTest {
12 |
13 | private InjectBuilder injectBuilder;
14 |
15 | @Before
16 | public void setUp() throws Exception {
17 | injectBuilder = new InjectBuilder(mock(ResponseBuilder.class));
18 | }
19 |
20 | @Test
21 | public void shouldBuildAnInjectWithAFunction() throws Exception {
22 | String injection = "some function";
23 | Inject expectedInject = new Inject().withFunction(injection);
24 | Inject actualInject = injectBuilder.function(injection).build();
25 |
26 | assertThat(actualInject, is(expectedInject));
27 | }
28 | }
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.mbtest.javabank.http.imposters.Imposter;
4 |
5 | import java.util.List;
6 |
7 | import static com.google.common.collect.Lists.newArrayList;
8 |
9 | public class ImposterBuilder {
10 | private int port;
11 | private List stubBuilders = newArrayList();
12 |
13 | public static ImposterBuilder anImposter() {
14 | return new ImposterBuilder();
15 | }
16 |
17 | public ImposterBuilder onPort(int port) {
18 | this.port = port;
19 | return this;
20 | }
21 |
22 | public StubBuilder stub() {
23 | StubBuilder child = new StubBuilder(this);
24 | stubBuilders.add(child);
25 | return child;
26 | }
27 |
28 | public Imposter build() {
29 | Imposter imposter = new Imposter().onPort(port);
30 | for (StubBuilder stubBuilder : stubBuilders) {
31 | imposter.addStub(stubBuilder.build());
32 | }
33 | return imposter;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/http/responses/InjectTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.responses;
2 |
3 | import org.json.simple.JSONObject;
4 | import org.junit.Test;
5 |
6 | import static org.hamcrest.core.Is.is;
7 | import static org.junit.Assert.*;
8 |
9 | public class InjectTest {
10 |
11 | public static final String FUNCTION = "some javascript function to be eval'd";
12 |
13 | @Test
14 | public void shouldCreateAJsonObject() throws Exception {
15 | JSONObject expectedJson = new JSONObject();
16 | expectedJson.put("inject", FUNCTION);
17 |
18 | Inject inject = new Inject()
19 | .withFunction(FUNCTION);
20 |
21 | assertThat(inject.getJSON(), is(expectedJson));
22 | }
23 |
24 | @Test
25 | public void shouldCreateAJsonString() throws Exception {
26 | JSONObject expectedJson = new JSONObject();
27 | expectedJson.put("inject", FUNCTION);
28 |
29 | Inject inject = new Inject()
30 | .withFunction(FUNCTION);
31 |
32 | assertThat(inject.toString(), is(expectedJson.toJSONString()));
33 | }
34 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 javabank
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/fluent/ResponseTypeBuilderTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 | import org.mbtest.javabank.http.responses.Response;
6 |
7 | import static org.hamcrest.core.Is.is;
8 | import static org.junit.Assert.assertThat;
9 | import static org.mockito.Mockito.mock;
10 |
11 | public class ResponseTypeBuilderTest {
12 |
13 | private ResponseBuilder parent;
14 | private ResponseTypeBuilder responseTypeBuilder;
15 |
16 | @Before
17 | public void setUp() throws Exception {
18 | parent = mock(ResponseBuilder.class);
19 | responseTypeBuilder = new TestResponseBuilder(parent);
20 |
21 | }
22 |
23 | @Test
24 | public void shouldEndWithItsParent() throws Exception {
25 | assertThat(responseTypeBuilder.end(), is(parent));
26 | }
27 |
28 | private class TestResponseBuilder extends ResponseTypeBuilder {
29 |
30 | TestResponseBuilder(ResponseBuilder parent) {
31 | super(parent);
32 | }
33 |
34 | @Override
35 | protected Response build() {
36 | return null;
37 | }
38 | }
39 | }
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/http/core/StubTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.core;
2 |
3 | import org.junit.Test;
4 | import org.mbtest.javabank.http.responses.Is;
5 |
6 | import static org.assertj.core.api.Assertions.assertThat;
7 |
8 | public class StubTest {
9 | @Test
10 | public void shouldAddAResponse() {
11 | Stub stub = new Stub()
12 | .withResponse(new Is());
13 |
14 | assertThat(stub.getResponses()).hasSize(1);
15 | }
16 |
17 | @Test
18 | public void shouldAddAnotherResponse() {
19 | Stub stub = new Stub()
20 | .withResponse(new Is());
21 |
22 | Is additionalResponse = new Is();
23 | stub.addResponse(additionalResponse);
24 |
25 | assertThat(stub.getResponses()).hasSize(2);
26 | assertThat(stub.getResponses()).contains(additionalResponse);
27 | }
28 |
29 | @Test
30 | public void shouldOverwriteExistingResponsesWhenUsingWithResponse() {
31 | Is responseToBeOverwritten = new Is().withStatusCode(400);
32 | Stub stub = new Stub()
33 | .withResponse(responseToBeOverwritten);
34 |
35 | Is additionalResponse = new Is();
36 | stub.withResponse(additionalResponse.withStatusCode(200));
37 |
38 | assertThat(stub.getResponses()).hasSize(1);
39 | assertThat(stub.getResponses()).doesNotContain(responseToBeOverwritten);
40 | }
41 | }
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/PredicateValueBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.mbtest.javabank.http.predicates.Predicate;
4 | import org.mbtest.javabank.http.predicates.PredicateType;
5 |
6 | public class PredicateValueBuilder implements FluentBuilder {
7 | private final Predicate predicate;
8 | private PredicateTypeBuilder parent;
9 |
10 | public PredicateValueBuilder(PredicateTypeBuilder predicateTypeBuilder, PredicateType type) {
11 | predicate = new Predicate(type);
12 | parent = predicateTypeBuilder;
13 | }
14 |
15 | public PredicateValueBuilder method(String method) {
16 | predicate.withMethod(method);
17 | return this;
18 | }
19 |
20 | public PredicateValueBuilder path(String path) {
21 | predicate.withPath(path);
22 | return this;
23 | }
24 |
25 | public PredicateValueBuilder query(String parameter, String value) {
26 | predicate.addQueryParameter(parameter, value);
27 | return this;
28 | }
29 |
30 | public PredicateValueBuilder body(String body) {
31 | predicate.withBody(body);
32 | return this;
33 | }
34 |
35 | public PredicateValueBuilder header(String name, String value) {
36 | predicate.addHeader(name, value);
37 | return this;
38 | }
39 |
40 | @Override
41 | public PredicateTypeBuilder end() {
42 | return parent;
43 | }
44 |
45 | public Predicate build() {
46 | return predicate;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # javabank [](https://travis-ci.org/thejamesthomas/javabank)
2 | Native Java bindings for Mountebank
3 |
4 | ## Project Status
5 | Functional but not under active development. I accept pull requests, and generally get them merged within a week, and the resulting build out to central within a few hours of a successful merge.
6 |
7 | ## To install
8 |
9 | You'll need to at least include javabank-core. This includes all of the classes which let you build imposters, predicates, and the like. It also handles serialization to and from JSON.
10 |
11 | #### Maven
12 | ```
13 |
14 | org.mbtest.javabank
15 | javabank-core
16 | 0.4.10
17 |
18 | ```
19 | #### Gradle
20 | ```
21 | compile 'org.mbtest.javabank:javabank-core:0.4.10'
22 | ```
23 |
24 | If you also need a REST client to talk to Mountebank, you can include the javabank-client library. I use [unirest](http://unirest.io/java.html) as my client of choice. If you already have a rest client in your application, you can save some overhead by continuing to use that instead, though that route will require you to learn a little more about the Mountebank REST API.
25 |
26 | #### Maven
27 | ```
28 |
29 | org.mbtest.javabank
30 | javabank-client
31 | 0.4.10
32 |
33 | ```
34 | #### Gradle
35 | ```
36 | compile 'org.mbtest.javabank:javabank-client:0.4.10'
37 | ```
38 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/StubBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.mbtest.javabank.http.core.Stub;
4 |
5 | import java.util.List;
6 |
7 | import static com.google.common.collect.Lists.newArrayList;
8 |
9 | public class StubBuilder implements FluentBuilder {
10 | private ImposterBuilder parent;
11 | private List childResponses = newArrayList();
12 | private List childPredicates = newArrayList();
13 |
14 | protected StubBuilder(ImposterBuilder httpImposterBuilder) {
15 | this.parent = httpImposterBuilder;
16 | }
17 |
18 | public ResponseBuilder response() {
19 | ResponseBuilder childResponse = new ResponseBuilder(this);
20 | childResponses.add(childResponse);
21 | return childResponse;
22 | }
23 |
24 | public PredicateTypeBuilder predicate() {
25 | PredicateTypeBuilder childPredicate = new PredicateTypeBuilder(this);
26 | childPredicates.add(childPredicate);
27 | return childPredicate;
28 | }
29 |
30 | @Override
31 | public ImposterBuilder end() {
32 | return parent;
33 | }
34 |
35 | protected Stub build() {
36 | Stub stub = new Stub();
37 | for(ResponseBuilder childResponse : childResponses) {
38 | stub.addResponse(childResponse.build());
39 | }
40 | for(PredicateTypeBuilder childPredicate : childPredicates) {
41 | stub.addPredicates(childPredicate.build());
42 | }
43 |
44 | return stub;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.core;
2 |
3 | import org.mbtest.javabank.http.predicates.Predicate;
4 | import org.mbtest.javabank.http.responses.Is;
5 | import org.mbtest.javabank.http.responses.Response;
6 |
7 | import java.util.HashMap;
8 | import java.util.List;
9 |
10 | import static com.google.common.collect.Lists.newArrayList;
11 |
12 | public class Stub extends HashMap {
13 |
14 | private static final String RESPONSES = "responses";
15 | private static final String PREDICATES = "predicates";
16 |
17 | public Stub() {
18 | this.put(RESPONSES, newArrayList());
19 | this.put(PREDICATES, newArrayList());
20 | }
21 |
22 | public Stub withResponse(Is response) {
23 | getResponses().clear();
24 | getResponses().add(response);
25 |
26 | return this;
27 | }
28 |
29 | public Stub addResponse(Response response) {
30 | getResponses().add(response);
31 |
32 | return this;
33 | }
34 |
35 | public Stub addPredicates(List predicates) {
36 | getPredicates().addAll(predicates);
37 | return this;
38 | }
39 |
40 | public List getResponses() {
41 | return (List) this.get(RESPONSES);
42 | }
43 |
44 | public List getPredicates() {
45 | return (List) this.get(PREDICATES);
46 | }
47 |
48 | public HashMap getResponse(int index) {
49 | return getResponses().get(index);
50 | }
51 |
52 | public Predicate getPredicate(int index) {
53 | return getPredicates().get(index);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.imposters;
2 |
3 | import org.json.simple.JSONObject;
4 | import org.mbtest.javabank.http.core.Stub;
5 |
6 | import java.util.HashMap;
7 | import java.util.List;
8 |
9 | import static com.google.common.collect.Lists.newArrayList;
10 |
11 | public class Imposter extends HashMap {
12 | private static final String PORT = "port";
13 | private static final String PROTOCOL = "protocol";
14 | private static final String STUBS = "stubs";
15 |
16 | public Imposter() {
17 | this.put(PROTOCOL, "http");
18 | this.put(STUBS, newArrayList());
19 | }
20 |
21 | public static Imposter fromJSON(JSONObject json) {
22 | Imposter imposter = new Imposter();
23 | imposter.putAll(json);
24 |
25 | return imposter;
26 | }
27 |
28 | public static Imposter anImposter() {
29 | return new Imposter();
30 | }
31 |
32 | public Imposter onPort(int port) {
33 | this.put(PORT, port);
34 | return this;
35 | }
36 |
37 | public Imposter addStub(Stub stub) {
38 | getStubs().add(stub);
39 | return this;
40 | }
41 |
42 | public Imposter withStub(Stub stub) {
43 | this.remove(STUBS);
44 | this.put(STUBS, newArrayList());
45 | addStub(stub);
46 | return this;
47 | }
48 |
49 | public List getStubs() {
50 | return ((List) get(STUBS));
51 | }
52 |
53 | public Stub getStub(int index) {
54 | return getStubs().get(index);
55 | }
56 |
57 | public JSONObject toJSON() {
58 | return new JSONObject(this);
59 | }
60 |
61 | public String toString() {
62 | return toJSON().toJSONString();
63 | }
64 |
65 | public int getPort() {
66 | return Integer.valueOf(String.valueOf(get(PORT)));
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/IsBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.mbtest.javabank.http.responses.Is;
4 |
5 | import java.io.File;
6 | import java.io.IOException;
7 | import java.nio.file.Files;
8 | import java.util.Map;
9 |
10 | import static com.google.common.collect.Maps.newHashMap;
11 |
12 | public class IsBuilder extends ResponseTypeBuilder {
13 | private int statusCode = 200;
14 | private String body = "";
15 | private String mode;
16 | private File bodyFile;
17 | private final Map headers = newHashMap();
18 |
19 | public IsBuilder(ResponseBuilder responseBuilder) {
20 | super(responseBuilder);
21 | }
22 |
23 | public IsBuilder statusCode(int statusCode) {
24 | this.statusCode = statusCode;
25 | return this;
26 | }
27 |
28 | public IsBuilder header(String name, String value) {
29 | headers.put(name, value);
30 | return this;
31 | }
32 |
33 | public IsBuilder body(String body) {
34 | this.body = body;
35 | return this;
36 | }
37 |
38 | public IsBuilder body(File body) {
39 | this.bodyFile = body;
40 | return this;
41 | }
42 |
43 | public IsBuilder mode(String mode){
44 | this.mode = mode;
45 | return this;
46 | }
47 |
48 | @Override
49 | protected Is build() {
50 |
51 | if (this.bodyFile != null) {
52 | try {
53 | byte[] bytes = Files.readAllBytes(this.bodyFile.toPath());
54 | this.body = new String(bytes);
55 | } catch (IOException e) {
56 | e.printStackTrace();
57 | }
58 | }
59 |
60 | return new Is()
61 | .withStatusCode(statusCode)
62 | .withHeaders(headers)
63 | .withBody(body)
64 | .withMode(mode);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/fluent/ResponseBuilderTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 |
6 | import java.util.HashMap;
7 |
8 | import static org.hamcrest.core.Is.is;
9 | import static org.junit.Assert.assertThat;
10 | import static org.mockito.Mockito.mock;
11 |
12 | public class ResponseBuilderTest {
13 |
14 | StubBuilder parent;
15 | ResponseBuilder responseBuilder;
16 |
17 | @Before
18 | public void setUp() throws Exception {
19 | parent = mock(StubBuilder.class);
20 | responseBuilder = new ResponseBuilder(parent);
21 | }
22 |
23 | @Test
24 | public void shouldConstructAnIsBuilderWithItselfAsTheParent() throws Exception {
25 | IsBuilder isBuilder = responseBuilder.is();
26 |
27 | assertThat(isBuilder.end(), is(responseBuilder));
28 | }
29 |
30 | @Test
31 | public void shouldEndWithItsParent() throws Exception {
32 | assertThat(responseBuilder.end(), is(parent));
33 | }
34 |
35 | @Test
36 | public void shouldBuildAnEmptyIsByDefault() throws Exception {
37 | HashMap expectedIs = new IsBuilder(responseBuilder).build();
38 |
39 | assertThat(responseBuilder.build(), is(expectedIs));
40 | }
41 |
42 | @Test
43 | public void shouldBuildAnIs() throws Exception {
44 | IsBuilder isBuilder = responseBuilder.is();
45 | isBuilder.body("some file");
46 | HashMap expectedIs = isBuilder.build();
47 |
48 | assertThat(responseBuilder.build(), is(expectedIs));
49 | }
50 |
51 | @Test
52 | public void shouldBuildAnInject() throws Exception {
53 | InjectBuilder injectBuilder = responseBuilder.inject();
54 | injectBuilder.function("some function");
55 | HashMap expectedInject = injectBuilder.build();
56 |
57 | assertThat(responseBuilder.build(), is(expectedInject));
58 | }
59 | }
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/ImposterParserTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank;
2 |
3 | import org.json.simple.JSONArray;
4 | import org.json.simple.JSONObject;
5 | import org.json.simple.parser.ParseException;
6 | import org.junit.Ignore;
7 | import org.junit.Test;
8 | import org.mbtest.javabank.fluent.ImposterBuilder;
9 | import org.mbtest.javabank.http.imposters.Imposter;
10 |
11 | import static org.assertj.core.api.Assertions.assertThat;
12 |
13 | public class ImposterParserTest {
14 | @Test
15 | public void shouldParseJSONIntoImposter() throws ParseException {
16 | Imposter expectedImposter = ImposterBuilder.anImposter().onPort(1234).build();
17 |
18 | Imposter actualImposter = ImposterParser.parse(expectedImposter.toString());
19 |
20 | assertThat(actualImposter.getPort()).isEqualTo(expectedImposter.getPort());
21 | }
22 |
23 | @Ignore
24 | @Test
25 | public void shouldReturnAnImposterWithAnIntegerForThePort() throws ParseException {
26 | Imposter expectedImposter = ImposterBuilder.anImposter().onPort(1234).build();
27 |
28 | Imposter actualImposter = ImposterParser.parse(expectedImposter.toString());
29 |
30 | assertThat(actualImposter.get("port")).hasSameClassAs(new Integer(1));
31 | }
32 |
33 | @Ignore
34 | @Test
35 | public void shouldReturnAnImposterWithIntegersForTheResponseStatusCode() throws ParseException {
36 | Imposter expectedImposter = ImposterBuilder.anImposter()
37 | .onPort(1234)
38 | .stub()
39 | .response()
40 | .is()
41 | .statusCode(200)
42 | .end()
43 | .end()
44 | .end()
45 | .build();
46 |
47 | Imposter actualImposter = ImposterParser.parse(expectedImposter.toString());
48 |
49 | JSONArray stubs = (JSONArray) actualImposter.get("stubs");
50 | JSONObject stub = (JSONObject) stubs.get(0);
51 | JSONArray responses = (JSONArray) stub.get("responses");
52 | JSONObject response = (JSONObject) responses.get(0);
53 | JSONObject is = (JSONObject) response.get("is");
54 | assertThat(is.get("statusCode")).hasSameClassAs(new Integer(1));
55 | }
56 | }
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.responses;
2 |
3 | import com.google.common.net.HttpHeaders;
4 | import org.apache.http.HttpStatus;
5 |
6 | import java.util.HashMap;
7 | import java.util.Map;
8 | import java.util.Objects;
9 |
10 | import static com.google.common.collect.Maps.newHashMap;
11 |
12 | public class Is extends Response {
13 | private static final String IS = "is";
14 | private static final String HEADERS = "headers";
15 | private static final String BODY = "body";
16 | private static final String STATUS_CODE = "statusCode";
17 | public static final String MODE = "_mode";
18 |
19 | private final Map data;
20 | private Map headers;
21 |
22 | public Is() {
23 | headers = newHashMap();
24 | headers.put(HttpHeaders.CONNECTION, "close");
25 |
26 | this.data = newHashMap();
27 | this.data.put(STATUS_CODE, 200);
28 | this.data.put(HEADERS, headers);
29 |
30 | this.put(IS, data);
31 | withStatusCode(HttpStatus.SC_OK);
32 | withBody("");
33 | }
34 |
35 | public Is withStatusCode(int statusCode) {
36 | this.data.put("statusCode", statusCode);
37 | return this;
38 | }
39 |
40 | public Is withHeader(String name, String value) {
41 | this.headers.clear();
42 | addHeader(name, value);
43 | return this;
44 | }
45 |
46 | public Is addHeader(String name, String value) {
47 | this.headers.put(name, value);
48 | return this;
49 | }
50 |
51 | public Is withBody(String body) {
52 | this.data.put(BODY, body);
53 | return this;
54 | }
55 |
56 | public Is withMode(String mode){
57 | if(!Objects.isNull(mode)) {
58 | this.data.put(MODE, mode);
59 | }
60 | return this;
61 | }
62 |
63 | public Is withHeaders(Map headers) {
64 | this.headers = headers;
65 | this.data.put(HEADERS, headers); // issue #5
66 | return this;
67 | }
68 |
69 | public int getStatusCode() {
70 | return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
71 | }
72 |
73 | public Map getHeaders() {
74 | return headers;
75 | }
76 |
77 | public String getBody() {
78 | return (String) this.data.get(BODY);
79 | }
80 |
81 | public String getMode() {
82 | return (String) this.data.get(MODE);
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/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 Windows 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 |
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/fluent/PredicateTypeBuilder.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import org.mbtest.javabank.http.predicates.Predicate;
4 | import org.mbtest.javabank.http.predicates.PredicateType;
5 |
6 | import java.util.List;
7 |
8 | import static com.google.common.collect.Lists.newArrayList;
9 |
10 | public class PredicateTypeBuilder implements FluentBuilder {
11 | private StubBuilder parent;
12 | private List childPredicateValueBuilders = newArrayList();
13 |
14 | protected PredicateTypeBuilder(StubBuilder stubBuilder) {
15 | this.parent = stubBuilder;
16 | }
17 |
18 | public PredicateValueBuilder equals() {
19 | return getHttpMatcherBuilder(PredicateType.EQUALS);
20 | }
21 |
22 | public PredicateValueBuilder deepEquals() {
23 | return getHttpMatcherBuilder(PredicateType.DEEP_EQUALS);
24 | }
25 |
26 | public PredicateValueBuilder contains() {
27 | return getHttpMatcherBuilder(PredicateType.CONTAINS);
28 | }
29 |
30 | public PredicateValueBuilder startsWith() {
31 | return getHttpMatcherBuilder(PredicateType.STARTS_WITH);
32 | }
33 |
34 | public PredicateValueBuilder endsWith() {
35 | return getHttpMatcherBuilder(PredicateType.ENDS_WITH);
36 | }
37 |
38 | public PredicateValueBuilder matches() {
39 | return getHttpMatcherBuilder(PredicateType.MATCHES);
40 | }
41 |
42 | public PredicateValueBuilder exists() {
43 | return getHttpMatcherBuilder(PredicateType.EXISTS);
44 | }
45 |
46 | public PredicateValueBuilder not() {
47 | return getHttpMatcherBuilder(PredicateType.NOT);
48 | }
49 |
50 | public PredicateValueBuilder or() {
51 | return getHttpMatcherBuilder(PredicateType.OR);
52 | }
53 |
54 | public PredicateValueBuilder inject() {
55 | return getHttpMatcherBuilder(PredicateType.INJECT);
56 | }
57 |
58 | public PredicateValueBuilder and() {
59 | return getHttpMatcherBuilder(PredicateType.AND);
60 | }
61 |
62 | private PredicateValueBuilder getHttpMatcherBuilder(PredicateType type) {
63 | PredicateValueBuilder predicateValueBuilder = new PredicateValueBuilder(this, type);
64 | childPredicateValueBuilders.add(predicateValueBuilder);
65 | return predicateValueBuilder;
66 | }
67 |
68 | @Override
69 | public StubBuilder end() {
70 | return parent;
71 | }
72 |
73 | protected List build() {
74 | List predicates = newArrayList();
75 | for(PredicateValueBuilder predicateValueBuilder : childPredicateValueBuilders) {
76 | predicates.add(predicateValueBuilder.build());
77 | }
78 | return predicates;
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/javabank-client/src/main/java/org/mbtest/javabank/Client.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank;
2 |
3 | import org.json.JSONArray;
4 | import org.json.simple.parser.ParseException;
5 | import org.mbtest.javabank.http.imposters.Imposter;
6 |
7 | import com.mashape.unirest.http.HttpResponse;
8 | import com.mashape.unirest.http.JsonNode;
9 | import com.mashape.unirest.http.Unirest;
10 | import com.mashape.unirest.http.exceptions.UnirestException;
11 |
12 | public class Client {
13 |
14 | static final String DEFAULT_BASE_URL = "http://localhost:2525";
15 |
16 | protected String baseUrl;
17 |
18 | public Client() {
19 | this(DEFAULT_BASE_URL);
20 | }
21 |
22 | public Client(String baseUrl) {
23 | this.baseUrl = baseUrl;
24 | }
25 |
26 | public Client(String host, int port) {
27 | this.baseUrl = String.format("http://%s:%d", host, port);
28 | }
29 |
30 | public String getBaseUrl() {
31 | return baseUrl;
32 | }
33 |
34 | public boolean isMountebankRunning() {
35 | try {
36 | HttpResponse response = Unirest.get(baseUrl).asJson();
37 | return response.getStatus() == 200;
38 | } catch (UnirestException e) {
39 | return false;
40 | }
41 | }
42 |
43 | public boolean isMountebankAllowingInjection() {
44 | try {
45 | HttpResponse response = Unirest.get(baseUrl + "/config").asJson();
46 | return response.getBody().getObject().getJSONObject("options").getBoolean("allowInjection");
47 | } catch (UnirestException e) {
48 | return false;
49 | }
50 | }
51 |
52 | public int createImposter(Imposter imposter) {
53 | try {
54 | HttpResponse response = Unirest.post(baseUrl + "/imposters").body(imposter.toString()).asJson();
55 | return response.getStatus();
56 | } catch (UnirestException e) {
57 | return 500;
58 | }
59 | }
60 |
61 | public String deleteImposter(int port) {
62 | try {
63 | HttpResponse response = Unirest.delete(baseUrl + "/imposters/" + port).asJson();
64 | return response.getBody().toString();
65 | } catch (UnirestException e) {
66 | return null;
67 | }
68 | }
69 |
70 | public int getImposterCount() {
71 | try {
72 | HttpResponse response = Unirest.get(baseUrl + "/imposters").asJson();
73 | return ((JSONArray) response.getBody().getObject().get("imposters")).length();
74 | } catch (UnirestException e) {
75 | return -1;
76 | }
77 | }
78 |
79 | public int deleteAllImposters() {
80 | try {
81 | HttpResponse response = Unirest.delete(baseUrl + "/imposters").asJson();
82 | return response.getStatus();
83 | } catch (UnirestException e) {
84 | return 500;
85 | }
86 | }
87 |
88 | public Imposter getImposter(int port) throws ParseException {
89 | try {
90 | HttpResponse response = Unirest.get(baseUrl + "/imposters/" + port).asJson();
91 | String responseJson = response.getBody().toString();
92 |
93 | return ImposterParser.parse(responseJson);
94 | } catch (UnirestException e) {
95 | return null;
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/http/core/IsTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.core;
2 |
3 | import com.google.common.collect.ImmutableMap;
4 | import org.apache.http.HttpHeaders;
5 | import org.apache.http.HttpStatus;
6 | import org.json.simple.JSONObject;
7 | import org.junit.Before;
8 | import org.junit.Test;
9 | import org.mbtest.javabank.http.responses.Is;
10 |
11 | import static org.assertj.core.api.Assertions.assertThat;
12 |
13 | public class IsTest {
14 |
15 | private ImmutableMap defaultHeaders;
16 |
17 | @Before
18 | public void setUp() throws Exception {
19 | defaultHeaders = ImmutableMap.of(HttpHeaders.CONNECTION, "close");
20 | }
21 |
22 | @Test
23 | public void shouldSetTheDefaultHttpStatusCodeTo200() {
24 | Is is = new Is();
25 |
26 | assertThat(is.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
27 | }
28 |
29 | @Test
30 | public void shouldSetTheDefaultHeadersToConnectionClose() {
31 | Is is = new Is();
32 |
33 | assertThat(is.getHeaders()).isEqualTo(defaultHeaders);
34 | }
35 |
36 | @Test
37 | public void shouldSetTheDefaultBodyToEmpty() {
38 | Is is = new Is();
39 |
40 | assertThat(is.getBody()).isEqualTo("");
41 | }
42 |
43 | @Test
44 | public void shouldSetTheStatusCode() {
45 | Is is = new Is()
46 | .withStatusCode(HttpStatus.SC_BAD_REQUEST);
47 |
48 | assertThat(is.getStatusCode()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
49 | }
50 |
51 | @Test
52 | public void shouldSetTheHeaders() {
53 | Is is = new Is().withHeader(HttpHeaders.CONTENT_TYPE, "application/xml");
54 |
55 | ImmutableMap expectedHeaders = ImmutableMap.of(HttpHeaders.CONTENT_TYPE, "application/xml");
56 |
57 | assertThat(is.getHeaders()).isEqualTo(expectedHeaders);
58 | }
59 |
60 | @Test
61 | public void shouldSetTheBody() {
62 | String expectedBody = "Hello World!";
63 | Is is = new Is().withBody(expectedBody);
64 |
65 | assertThat(is.getBody()).isEqualTo(expectedBody);
66 | }
67 |
68 | @Test
69 | public void shouldSetTheMode(){
70 | Is is = new Is().withMode("binary");
71 | assertThat(is.getMode()).isEqualTo("binary");
72 | }
73 |
74 | @Test
75 | public void shouldNotSetAModeByDefault() throws Exception {
76 | Is is = new Is();
77 | assertThat(is.getMode()).isNull();
78 | assertThat(is.getJSON().containsKey(Is.MODE)).isFalse();
79 | }
80 |
81 | @Test
82 | public void shouldContainAllDefaultValuesInJson() {
83 | Is is = new Is();
84 |
85 | JSONObject innerJson = new JSONObject();
86 | innerJson.put("statusCode", 200);
87 | innerJson.put("headers", defaultHeaders);
88 | innerJson.put("body", "");
89 |
90 | JSONObject expectedJson = new JSONObject();
91 | expectedJson.put("is", innerJson);
92 |
93 | assertThat(is.getJSON()).isEqualTo(expectedJson);
94 | }
95 |
96 | @Test
97 | public void shouldAddAdditionalHeaders() {
98 | Is is = new Is()
99 | .withHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
100 | .addHeader(HttpHeaders.ACCEPT, "*");
101 |
102 | ImmutableMap expectedHeaders = ImmutableMap.of(HttpHeaders.CONTENT_TYPE, "text/plain", HttpHeaders.ACCEPT, "*");
103 | assertThat(is.getHeaders()).isEqualTo(expectedHeaders);
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/http/imposters/ImposterTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.imposters;
2 |
3 | import org.apache.http.HttpHeaders;
4 | import org.json.simple.JSONArray;
5 | import org.json.simple.JSONObject;
6 | import org.junit.Before;
7 | import org.junit.Test;
8 | import org.mbtest.javabank.fluent.ImposterBuilder;
9 | import org.mbtest.javabank.http.core.Stub;
10 | import org.mbtest.javabank.http.responses.Is;
11 |
12 | import static org.assertj.core.api.Assertions.assertThat;
13 |
14 | public class ImposterTest {
15 |
16 | private String expectedProtocol = "http";
17 | private int expectedPort;
18 |
19 | @Before
20 | public void setUp() throws Exception {
21 | expectedPort = 4545;
22 | }
23 |
24 | @Test
25 | public void shouldCreateAnImposter() {
26 | Imposter imposter = Imposter.anImposter()
27 | .onPort(expectedPort);
28 |
29 | assertThat(imposter.getPort()).isEqualTo(expectedPort);
30 | }
31 |
32 | @Test
33 | public void shouldCreateAnHttpImposterWithAStub() {
34 | Stub expectedStub = new Stub();
35 | Imposter imposter = Imposter.anImposter()
36 | .withStub(expectedStub);
37 |
38 | assertThat(imposter.getStubs()).contains(expectedStub);
39 | }
40 |
41 | @Test
42 | public void shouldAddAStubToAnHttpImposter() {
43 | Stub additionalStub = new Stub();
44 | Imposter imposter = Imposter.anImposter()
45 | .withStub(new Stub());
46 | imposter.addStub(additionalStub);
47 |
48 | assertThat(imposter.getStubs()).hasSize(2);
49 | assertThat(imposter.getStubs()).contains(additionalStub);
50 | }
51 |
52 | @Test
53 | public void shouldCreateAJsonObject() {
54 | Imposter imposter = Imposter.anImposter()
55 | .onPort(expectedPort)
56 | .withStub(new Stub());
57 |
58 | JSONObject expectedJson = new JSONObject();
59 | expectedJson.put("port", expectedPort);
60 | expectedJson.put("protocol", expectedProtocol);
61 | JSONArray stubs = new JSONArray();
62 | stubs.add(new Stub());
63 | expectedJson.put("stubs", stubs);
64 |
65 | assertThat(imposter.toJSON()).isEqualTo(expectedJson);
66 | }
67 |
68 | @Test
69 | public void shouldCreateAJsonObjectWithBuilder() {
70 |
71 | String expectedBody = "Hello World!";
72 | int expectedStatusCode = 201;
73 | String expectedContentType = "plain/text";
74 |
75 | Imposter imposter = ImposterBuilder.anImposter().onPort(expectedPort)
76 | .stub()
77 | .response()
78 | .is()
79 | .body(expectedBody)
80 | .statusCode(expectedStatusCode)
81 | .header(com.google.common.net.HttpHeaders.CONTENT_TYPE, expectedContentType)
82 | .end()
83 | .end()
84 | .end().build();
85 |
86 | final Is response = new Is();
87 | response.withHeader(HttpHeaders.CONTENT_TYPE, expectedContentType);
88 | response.withBody(expectedBody);
89 | response.withStatusCode(expectedStatusCode);
90 |
91 | final Stub stub = new Stub();
92 | stub.addResponse(response);
93 |
94 | JSONArray stubs = new JSONArray();
95 | stubs.add(stub);
96 |
97 | JSONObject expectedJson = new JSONObject();
98 | expectedJson.put("port", expectedPort);
99 | expectedJson.put("protocol", expectedProtocol);
100 | expectedJson.put("stubs", stubs);
101 |
102 | assertThat(imposter.toJSON()).isEqualTo(expectedJson);
103 | }
104 | }
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/http/predicates/PredicateTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.predicates;
2 |
3 | import com.google.common.collect.ImmutableMap;
4 | import org.json.simple.JSONValue;
5 | import org.junit.Test;
6 |
7 | import static org.assertj.core.api.Assertions.assertThat;
8 | import static org.mbtest.javabank.http.predicates.PredicateType.EQUALS;
9 |
10 | public class PredicateTest {
11 | @Test
12 | public void shouldSetTheName() {
13 | Predicate predicate = new Predicate(PredicateType.EQUALS);
14 |
15 | assertThat(predicate.getType()).isEqualTo("equals");
16 | }
17 |
18 | @Test
19 | public void shouldSetTheDefaultNameToEquals() {
20 | Predicate equalsJsonMatcher = new Predicate(EQUALS);
21 |
22 | assertThat(equalsJsonMatcher.getType()).isEqualTo("equals");
23 | }
24 |
25 | @Test
26 | public void shouldSetThePath() {
27 | Predicate equalsJsonMatcher = new Predicate(EQUALS).withPath("/test");
28 |
29 | assertThat(equalsJsonMatcher.getPath()).isEqualTo("/test");
30 | }
31 |
32 | @Test
33 | public void shouldSetTheMethod() {
34 | Predicate equalsJsonMatcher = new Predicate(EQUALS).withMethod("POST");
35 |
36 | assertThat(equalsJsonMatcher.getMethod()).isEqualTo("POST");
37 | }
38 |
39 | @Test
40 | public void shouldSetTheQueryParameters() {
41 | Predicate equalsJsonMatcher = new Predicate(EQUALS).addQueryParameter("first", "1");
42 |
43 | assertThat(equalsJsonMatcher.getQueryParameter("first")).isEqualTo("1");
44 | }
45 |
46 | @Test
47 | public void shouldGetTheQueryParameters() {
48 | Predicate equalsJsonMatcher = new Predicate(EQUALS).addQueryParameter("first", "1").addQueryParameter("second", "2");
49 |
50 | assertThat(equalsJsonMatcher.getQueryParameters()).isEqualTo(ImmutableMap.of("first", "1", "second", "2"));
51 | }
52 |
53 | @Test
54 | public void shouldAddHeaders() {
55 | Predicate httpMatcher = new Predicate(EQUALS).addHeader("Accept", "text/plain").addHeader("Content-Type", "application/json");
56 |
57 | assertThat(httpMatcher.getHeaders()).isEqualTo(ImmutableMap.of("Accept", "text/plain", "Content-Type", "application/json"));
58 | }
59 |
60 | @Test
61 | public void shouldSetRequestFrom() {
62 | Predicate httpMatcher = new Predicate(EQUALS).withRequestFrom("127.0.0.1", "12345");
63 |
64 | assertThat(httpMatcher.getRequestFrom()).isEqualTo("127.0.0.1:12345");
65 | }
66 |
67 | @Test
68 | public void shouldSetBody() {
69 | Predicate httpMatcher = new Predicate(EQUALS).withBody("Hello World!");
70 |
71 | assertThat(httpMatcher.getBody()).isEqualTo("Hello World!");
72 | }
73 |
74 | @Test
75 | public void shouldSerializeToJSON() {
76 | Predicate equalsJsonMatcher = new Predicate(EQUALS)
77 | .withMethod("POST")
78 | .withPath("/testing")
79 | .withRequestFrom("127.0.0.1", "12345")
80 | .withBody("hello, world")
81 | .addQueryParameter("one", "1")
82 | .addQueryParameter("two", "2")
83 | .addHeader("Accept", "text/plain")
84 | .addHeader("Content-Type", "application/json");
85 |
86 | String expectedJson = "{\"equals\":{" +
87 | "\"path\":\"\\/testing\"," +
88 | "\"headers\":{\"Accept\":\"text\\/plain\",\"Content-Type\":\"application\\/json\"}," +
89 | "\"method\":\"POST\"," +
90 | "\"query\":{\"one\":\"1\",\"two\":\"2\"}," +
91 | "\"body\":\"hello, world\"," +
92 | "\"requestFrom\":\"127.0.0.1:12345\"}}";
93 |
94 | assertThat(JSONValue.parse(equalsJsonMatcher.toString())).isEqualTo(JSONValue.parse(expectedJson));
95 | }
96 | }
--------------------------------------------------------------------------------
/javabank-core/src/main/java/org/mbtest/javabank/http/predicates/Predicate.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.http.predicates;
2 |
3 | import org.json.simple.JSONObject;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | import static com.google.common.collect.Maps.newHashMap;
9 |
10 | public class Predicate extends HashMap {
11 | private static final String PATH = "path";
12 | private static final String METHOD = "method";
13 | private static final String QUERY = "query";
14 | private static final String HEADERS = "headers";
15 | private static final String REQUEST_FROM = "requestFrom";
16 | private static final String BODY = "body";
17 |
18 | private Map data;
19 | private PredicateType type;
20 |
21 | public Predicate(PredicateType type) {
22 | this.type = type;
23 | data = newHashMap();
24 | this.put(type.getValue(), data);
25 | }
26 |
27 | private Predicate addEntry(String key, String value) {
28 | data.put(key, value);
29 | return this;
30 | }
31 |
32 | private Predicate addEntry(String key, Map map) {
33 | data.put(key, map);
34 | return this;
35 | }
36 |
37 | private Predicate addMapEntry(String key, String name, String value) {
38 | if(!data.containsKey(key)) {
39 | data.put(key, newHashMap());
40 | }
41 |
42 | Map entryMap = (Map) data.get(key);
43 | entryMap.put(name, value);
44 |
45 | return this;
46 | }
47 |
48 | private Object getEntry(String key) {
49 | return this.data.get(key);
50 | }
51 |
52 | @Override
53 | public String toString() {
54 | return toJSON().toJSONString();
55 | }
56 |
57 | private JSONObject toJSON() {
58 | return new JSONObject(this);
59 | }
60 |
61 | public String getType() {
62 | return type.getValue();
63 | }
64 |
65 | public Predicate withPath(String path) {
66 | addEntry(PATH, path);
67 | return this;
68 | }
69 |
70 | public Predicate withMethod(String method) {
71 | addEntry(METHOD, method);
72 | return this;
73 | }
74 |
75 | public Predicate withQueryParameters(Map parameters) {
76 | addEntry(QUERY, parameters);
77 | return this;
78 | }
79 |
80 | public Predicate addQueryParameter(String name, String value) {
81 | addMapEntry(QUERY, name, value);
82 | return this;
83 | }
84 |
85 | public Predicate addHeader(String name, String value) {
86 | addMapEntry(HEADERS, name, value);
87 | return this;
88 | }
89 |
90 | public Predicate withRequestFrom(String host, String port) {
91 | addEntry(REQUEST_FROM, host + ":" + port);
92 | return this;
93 | }
94 |
95 | public Predicate withBody(String body) {
96 | addEntry(BODY, body);
97 | return this;
98 | }
99 |
100 | public String getPath() {
101 | return (String) getEntry(PATH);
102 | }
103 |
104 | public String getMethod() {
105 | return (String) getEntry(METHOD);
106 | }
107 |
108 | public String getRequestFrom() {
109 | return (String) getEntry(REQUEST_FROM);
110 | }
111 |
112 | public String getBody() {
113 | return (String) getEntry(BODY);
114 | }
115 |
116 | public Map getQueryParameters() {
117 | return (Map) getEntry(QUERY);
118 | }
119 |
120 | public String getQueryParameter(String parameter) {
121 | return getQueryParameters().get(parameter);
122 | }
123 |
124 | public Map getHeaders() {
125 | return (Map) getEntry(HEADERS);
126 | }
127 |
128 | public String getHeader(String name) {
129 | return getHeaders().get(name);
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/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 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/javabank-core/src/test/java/org/mbtest/javabank/fluent/ImposterBuilderTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank.fluent;
2 |
3 | import com.google.common.net.HttpHeaders;
4 | import org.junit.Test;
5 | import org.mbtest.javabank.http.core.Stub;
6 | import org.mbtest.javabank.http.imposters.Imposter;
7 | import org.mbtest.javabank.http.predicates.Predicate;
8 | import org.mbtest.javabank.http.predicates.PredicateType;
9 | import org.mbtest.javabank.http.responses.Is;
10 |
11 | import static org.assertj.core.api.Assertions.assertThat;
12 |
13 | // @formatter:off
14 | public class ImposterBuilderTest {
15 | @Test
16 | public void shouldBuildAnHttpImposterWithTheCorrectPort() {
17 | Imposter imposter = ImposterBuilder.anImposter().onPort(4545).build();
18 |
19 | assertThat(imposter.getPort()).isEqualTo(4545);
20 | }
21 |
22 | @Test
23 | public void shouldBuildAnHttpImposterWithAStub() {
24 | Imposter imposter = ImposterBuilder.anImposter()
25 | .stub().end()
26 | .stub().end()
27 | .build();
28 |
29 | assertThat(imposter.getStubs()).hasSize(2);
30 | }
31 |
32 | @Test
33 | public void shouldBuildAnHttpImposterWithAResponse() {
34 | String expectedBody = "Hello World!";
35 | int expectedStatusCode = 201;
36 | String expectedContentType = "plain/text";
37 | Imposter imposter = ImposterBuilder.anImposter()
38 | .stub()
39 | .response()
40 | .is()
41 | .body(expectedBody)
42 | .statusCode(expectedStatusCode)
43 | .header(HttpHeaders.CONTENT_TYPE, expectedContentType)
44 | .end()
45 | .end()
46 | .end()
47 | .build();
48 |
49 | Is actualIs = (Is)imposter.getStub(0).getResponse(0);
50 |
51 | assertThat(actualIs.getBody()).isEqualTo(expectedBody);
52 | assertThat(actualIs.getStatusCode()).isEqualTo(expectedStatusCode);
53 | assertThat(actualIs.getHeaders().get(HttpHeaders.CONTENT_TYPE)).isEqualTo(expectedContentType);
54 | }
55 |
56 | @Test
57 | public void shouldBuildAnHttpImposterWithMultipleResponses() {
58 | Imposter imposter = ImposterBuilder.anImposter()
59 | .stub()
60 | .response().end()
61 | .response().end()
62 | .end()
63 | .build();
64 |
65 | assertThat(imposter.getStubs().get(0).getResponses()).hasSize(2);
66 | }
67 |
68 | @Test
69 | public void shouldBuildAnHttpImposterWithAPredicate() {
70 | String expectedValue = "POST";
71 | Imposter imposter = ImposterBuilder.anImposter()
72 | .stub()
73 | .predicate()
74 | .equals()
75 | .method(expectedValue)
76 | .end()
77 | .end()
78 | .end()
79 | .build();
80 |
81 | Predicate predicate = imposter.getStub(0).getPredicate(0);
82 |
83 | assertThat(predicate.getMethod()).isEqualTo(expectedValue);
84 | }
85 |
86 | @Test
87 | public void shouldBuildAnHttpImposterWithMultipleMatchers() {
88 | Imposter imposter = ImposterBuilder.anImposter()
89 | .stub()
90 | .predicate()
91 | .equals().body("test").end()
92 | .contains().path("testing").end()
93 | .startsWith().query("one","two").end()
94 | .not().query("hola", "hmmm").end()
95 | .end()
96 | .end()
97 | .build();
98 |
99 | Stub stub = imposter.getStub(0);
100 | Predicate firstPredicate = stub.getPredicate(0);
101 | Predicate secondPredicate = stub.getPredicate(1);
102 | Predicate thirdPredicate = stub.getPredicate(2);
103 | Predicate fourthPredicate = stub.getPredicate(3);
104 |
105 | assertThat(firstPredicate.getType()).isEqualTo(PredicateType.EQUALS.getValue());
106 | assertThat(firstPredicate.getBody()).isEqualTo("test");
107 |
108 | assertThat(secondPredicate.getType()).isEqualTo(PredicateType.CONTAINS.getValue());
109 | assertThat(secondPredicate.getPath()).isEqualTo("testing");
110 |
111 | assertThat(thirdPredicate.getType()).isEqualTo(PredicateType.STARTS_WITH.getValue());
112 | assertThat(thirdPredicate.getQueryParameter("one")).isEqualTo("two");
113 |
114 | assertThat(fourthPredicate.getType()).isEqualTo(PredicateType.NOT.getValue());
115 | assertThat(fourthPredicate.getQueryParameter("hola")).isEqualTo("hmmm");
116 | }
117 |
118 | @Test
119 | public void shouldBuildAnHttpImposterWithAPredicateWithMultipleCriteria() {
120 | Imposter imposter = ImposterBuilder.anImposter()
121 | .stub()
122 | .predicate()
123 | .equals()
124 | .body("hello, world")
125 | .method("POST")
126 | .path("/test")
127 | .query("first", "1")
128 | .header("Content-Type", "text/plain")
129 | .end()
130 | .end()
131 | .end()
132 | .build();
133 |
134 | Predicate predicate = imposter.getStub(0).getPredicate(0);
135 |
136 | assertThat(predicate.getBody()).isEqualTo("hello, world");
137 | assertThat(predicate.getMethod()).isEqualTo("POST");
138 | assertThat(predicate.getPath()).isEqualTo("/test");
139 | assertThat(predicate.getQueryParameter("first")).isEqualTo("1");
140 | assertThat(predicate.getHeader("Content-Type")).isEqualTo("text/plain");
141 | }
142 | }
143 | // @formatter:on
--------------------------------------------------------------------------------
/javabank-client/src/test/java/org/mbtest/javabank/ClientTest.java:
--------------------------------------------------------------------------------
1 | package org.mbtest.javabank;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 | import static org.assertj.core.api.Fail.fail;
5 | import static org.junit.Assert.assertEquals;
6 | import static org.mockito.Mockito.mock;
7 | import static org.mockito.Mockito.when;
8 |
9 | import org.json.JSONArray;
10 | import org.json.JSONObject;
11 | import org.json.simple.parser.ParseException;
12 | import org.junit.Before;
13 | import org.junit.Test;
14 | import org.junit.runner.RunWith;
15 | import org.mbtest.javabank.fluent.ImposterBuilder;
16 | import org.mbtest.javabank.http.imposters.Imposter;
17 | import org.mockito.Mock;
18 | import org.powermock.api.mockito.PowerMockito;
19 | import org.powermock.core.classloader.annotations.PrepareForTest;
20 | import org.powermock.modules.junit4.PowerMockRunner;
21 |
22 | import com.mashape.unirest.http.HttpResponse;
23 | import com.mashape.unirest.http.JsonNode;
24 | import com.mashape.unirest.http.Unirest;
25 | import com.mashape.unirest.http.exceptions.UnirestException;
26 | import com.mashape.unirest.request.GetRequest;
27 | import com.mashape.unirest.request.HttpRequestWithBody;
28 | import com.mashape.unirest.request.body.RequestBodyEntity;
29 |
30 | @RunWith(PowerMockRunner.class)
31 | @PrepareForTest({ Unirest.class, ImposterParser.class })
32 | public class ClientTest {
33 |
34 | private static final Client client = new Client();
35 |
36 | @Mock
37 | private GetRequest getRequest;
38 |
39 | @Mock
40 | private HttpResponse httpResponse;
41 |
42 | @Mock
43 | private HttpRequestWithBody requestWithBody;
44 |
45 | @Mock
46 | private RequestBodyEntity requestBodyEntity;
47 |
48 | @Mock
49 | JsonNode value;
50 |
51 | @Before
52 | public void setup() {
53 | PowerMockito.mockStatic(Unirest.class);
54 | PowerMockito.mockStatic(ImposterParser.class);
55 | }
56 |
57 | @Test
58 | public void shouldUseDefaultBaseUrlForDefaultConstructor() {
59 | assertThat(client.getBaseUrl()).isEqualTo(Client.DEFAULT_BASE_URL);
60 | }
61 |
62 | @Test
63 | public void shouldVerifyMountebankIsRunning() throws UnirestException {
64 | when(Unirest.get(Client.DEFAULT_BASE_URL)).thenReturn(getRequest);
65 | when(getRequest.asJson()).thenReturn(httpResponse);
66 | when(httpResponse.getStatus()).thenReturn(Integer.valueOf(200));
67 |
68 | assertThat(client.isMountebankRunning()).isEqualTo(true);
69 | }
70 |
71 | @Test
72 | public void shouldCreateAnImposter() throws UnirestException {
73 | Imposter imposter = new Imposter();
74 | when(Unirest.post(Client.DEFAULT_BASE_URL + "/imposters")).thenReturn(requestWithBody);
75 | when(requestWithBody.body(imposter.toString())).thenReturn(requestBodyEntity);
76 | when(requestBodyEntity.asJson()).thenReturn(httpResponse);
77 | when(httpResponse.getStatus()).thenReturn(Integer.valueOf(201));
78 |
79 | int statusCode = client.createImposter(imposter);
80 |
81 | assertThat(statusCode).isEqualTo(201);
82 | }
83 |
84 | @Test
85 | public void shouldDeleteAnImposter() throws UnirestException {
86 | String deleteResponse = "{ url: http://localhost:5757 }";
87 | when(Unirest.delete(Client.DEFAULT_BASE_URL + "/imposters/5757")).thenReturn(requestWithBody);
88 | when(requestWithBody.asJson()).thenReturn(httpResponse);
89 | when(httpResponse.getBody()).thenReturn(value);
90 | when(value.toString()).thenReturn(deleteResponse);
91 |
92 | String response = client.deleteImposter(5757);
93 |
94 | assertThat(response).contains("5757").contains("http");
95 | }
96 |
97 | @Test
98 | public void shouldCountTheNumberOfImposters() throws UnirestException {
99 | JsonNode jsonNode = mock(JsonNode.class);
100 | JSONObject jsonObject = mock(JSONObject.class);
101 | JSONArray jsonArray = mock(JSONArray.class);
102 | when(Unirest.get(Client.DEFAULT_BASE_URL + "/imposters")).thenReturn(getRequest);
103 | when(getRequest.asJson()).thenReturn(httpResponse);
104 | when(httpResponse.getBody()).thenReturn(jsonNode);
105 | when(jsonNode.getObject()).thenReturn(jsonObject);
106 | when(jsonObject.get("imposters")).thenReturn(jsonArray);
107 | when(jsonArray.length()).thenReturn(Integer.valueOf(3));
108 |
109 | assertThat(client.getImposterCount()).isEqualTo(3);
110 | }
111 |
112 | @Test
113 | public void shouldDeleteAllImposters() throws UnirestException {
114 | when(Unirest.delete(Client.DEFAULT_BASE_URL + "/imposters")).thenReturn(requestWithBody);
115 | when(requestWithBody.asJson()).thenReturn(httpResponse);
116 | when(httpResponse.getStatus()).thenReturn(Integer.valueOf(200));
117 |
118 | assertThat(client.deleteAllImposters()).isEqualTo(200);
119 | }
120 |
121 | @Test
122 | public void shouldGetAnImposter() throws ParseException, UnirestException {
123 | int port = 5757;
124 | String jsonString = "test string";
125 | Imposter expectedImposter = new ImposterBuilder().onPort(5757).build();
126 | when(Unirest.get(Client.DEFAULT_BASE_URL + "/imposters/5757")).thenReturn(getRequest);
127 | when(getRequest.asJson()).thenReturn(httpResponse);
128 | when(httpResponse.getBody()).thenReturn(value);
129 | when(value.toString()).thenReturn(jsonString);
130 | when(ImposterParser.parse(jsonString)).thenReturn(expectedImposter);
131 |
132 | Imposter actualImposter = client.getImposter(port);
133 | assertThat(actualImposter.getPort()).isEqualTo(expectedImposter.getPort());
134 | }
135 |
136 | @Test
137 | public void assertThatMountebankAllowsInjection() throws UnirestException {
138 | JSONObject jsonObjectOptions = mock(JSONObject.class);
139 | JSONObject jsonObjectAllowInjection = mock(JSONObject.class);
140 | when(Unirest.get(Client.DEFAULT_BASE_URL + "/config")).thenReturn(getRequest);
141 | when(getRequest.asJson()).thenReturn(httpResponse);
142 | when(httpResponse.getBody()).thenReturn(value);
143 | when(value.getObject()).thenReturn(jsonObjectOptions);
144 | when(jsonObjectOptions.getJSONObject("options")).thenReturn(jsonObjectAllowInjection);
145 | when(jsonObjectAllowInjection.getBoolean("allowInjection")).thenReturn(Boolean.TRUE);
146 |
147 | if (!client.isMountebankAllowingInjection()) {
148 | fail("Mountebank is not running with --allowInjection!");
149 | }
150 | }
151 |
152 | @Test
153 | public void assertTwoArgumentConstructorSetsBaseUrlCorrectly() {
154 | String host = "localhost";
155 | int port = 5757;
156 |
157 | Client client = new Client(host, port);
158 | assertEquals("http://localhost:5757", client.getBaseUrl());
159 | }
160 |
161 | @Test
162 | public void assertOneArgumentConstructorSetsBaseUrlCorrectly() {
163 | String host = "localhost";
164 | int port = 5757;
165 |
166 | Client client = new Client("http://" + host + ":" + port);
167 | assertEquals("http://localhost:5757", client.getBaseUrl());
168 | }
169 | }
--------------------------------------------------------------------------------