kandi background
Explore Kits

wiremock | A tool for mocking HTTP services | Mock library

 by   tomakehurst Java Version: 2.31.0-beta License: Apache-2.0

 by   tomakehurst Java Version: 2.31.0-beta License: Apache-2.0

Download this library from

kandi X-RAY | wiremock Summary

wiremock is a Java library typically used in Telecommunications, Media, Media, Entertainment, Testing, Mock applications. wiremock has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
To run all of WireMock’s tests:.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • wiremock has a highly active ecosystem.
  • It has 4577 star(s) with 1128 fork(s). There are 136 watchers for this library.
  • There were 1 major release(s) in the last 12 months.
  • There are 158 open issues and 886 have been closed. On average issues are closed in 197 days. There are 50 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of wiremock is 2.31.0-beta
wiremock Support
Best in #Mock
Average in #Mock
wiremock Support
Best in #Mock
Average in #Mock

quality kandi Quality

  • wiremock has 0 bugs and 0 code smells.
wiremock Quality
Best in #Mock
Average in #Mock
wiremock Quality
Best in #Mock
Average in #Mock

securitySecurity

  • wiremock has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • wiremock code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
wiremock Security
Best in #Mock
Average in #Mock
wiremock Security
Best in #Mock
Average in #Mock

license License

  • wiremock is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
wiremock License
Best in #Mock
Average in #Mock
wiremock License
Best in #Mock
Average in #Mock

buildReuse

  • wiremock releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • wiremock saves you 8257 person hours of effort in developing the same functionality from scratch.
  • It has 62945 lines of code, 5684 functions and 856 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
wiremock Reuse
Best in #Mock
Average in #Mock
wiremock Reuse
Best in #Mock
Average in #Mock
Top functions reviewed by kandi - BETA

kandi has reviewed wiremock and discovered the below as its top functions. This is intended to give you an instant insight into wiremock implemented functionality, and help decide if they suit your requirements.

  • Applies the given parameters to the given response .
  • Matches an XML document against the expected XML document .
  • Add the default routes .
  • Main method .
  • Apply additional configuration if enabled .
  • Handle incoming request .
  • Handle an admin request .
  • Renders the given event .
  • Deserialise a date - time value pattern .
  • Add admin context .

wiremock Key Features

HTTP response stubbing, matchable on URL, header and body content patterns

Request verification

Runs in unit tests, as a standalone process or as a WAR app

Configurable via a fluent Java API, JSON files and JSON over HTTP

Record/playback of stubs

Fault injection

Per-request conditional proxying

Browser proxying for request inspection and replacement

Stateful behaviour simulation

Configurable response delays

Building WireMock locally

copy iconCopydownload iconDownload
./gradlew clean test

How to write response in wiremock as a template with list?

copy iconCopydownload iconDownload
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars-jackson2</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
                .extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
  "place": "{{parameters.place}}",
  "users": {{json parameters.users}}
}
{
  "place": "New York",
  "users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
-----------------------
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars-jackson2</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
                .extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
  "place": "{{parameters.place}}",
  "users": {{json parameters.users}}
}
{
  "place": "New York",
  "users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
-----------------------
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars-jackson2</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
                .extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
  "place": "{{parameters.place}}",
  "users": {{json parameters.users}}
}
{
  "place": "New York",
  "users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
-----------------------
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars-jackson2</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
                .extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
  "place": "{{parameters.place}}",
  "users": {{json parameters.users}}
}
{
  "place": "New York",
  "users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
-----------------------
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars-jackson2</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
                .extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
  "place": "{{parameters.place}}",
  "users": {{json parameters.users}}
}
{
  "place": "New York",
  "users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}

Docker Container with Wiremock could not find stub mappings

copy iconCopydownload iconDownload
{
  "mappings": [
    {
      "id": "679dd3ce-55e5-45ee-b270-01dcf1b371ca",
      "request": {
        "urlPattern": "^/hello",
        "method": "GET"
      },
      "response": {
        "status": 200,
        "jsonBody": {
          "status": "success",
          "message": "Hello"
        },
        "headers": {
          "Content-Type": "text/plain"
        }
      },
      "uuid": "679dd3ce-55e5-45ee-b270-01dcf1b371ca"
    },
    {
      "id": "679dd3ce-55e5-45ee-b270-01dcf1b371c2",
      "request": {
        "urlPattern": "^/hello-2",
        "method": "GET"
      },
      "response": {
        "status": 200,
        "jsonBody": {
          "status": "success",
          "message": "Hello-2"
        },
        "headers": {
          "Content-Type": "text/plain"
        }
      },
      "uuid": "679dd3ce-55e5-45ee-b270-01dcf1b371c2"
    }
  ]
}
docker run -it --rm \
  -p 8090:8080 \
  -v $PWD/samples/hello/stubs:/home/wiremock \
  wiremock/wiremock
-----------------------
{
  "mappings": [
    {
      "id": "679dd3ce-55e5-45ee-b270-01dcf1b371ca",
      "request": {
        "urlPattern": "^/hello",
        "method": "GET"
      },
      "response": {
        "status": 200,
        "jsonBody": {
          "status": "success",
          "message": "Hello"
        },
        "headers": {
          "Content-Type": "text/plain"
        }
      },
      "uuid": "679dd3ce-55e5-45ee-b270-01dcf1b371ca"
    },
    {
      "id": "679dd3ce-55e5-45ee-b270-01dcf1b371c2",
      "request": {
        "urlPattern": "^/hello-2",
        "method": "GET"
      },
      "response": {
        "status": 200,
        "jsonBody": {
          "status": "success",
          "message": "Hello-2"
        },
        "headers": {
          "Content-Type": "text/plain"
        }
      },
      "uuid": "679dd3ce-55e5-45ee-b270-01dcf1b371c2"
    }
  ]
}
docker run -it --rm \
  -p 8090:8080 \
  -v $PWD/samples/hello/stubs:/home/wiremock \
  wiremock/wiremock

Unable to run JUnit5 tests with Maven

copy iconCopydownload iconDownload
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter</artifactId>
                        <version>5.8.2</version>
                    </dependency>
                </dependencies>
            </plugin>

Implement different response with WireMock when no request(s) match

copy iconCopydownload iconDownload
try {
    fileSource.getBinaryFileNamed(bodyFileName).readContents();
} catch (FileNotFoundException e) {
    return WireMock.notFound().withBody("custom body");
}

// Otherwise return the unmodified response definition
-----------------------
{
  "mappings": [
    {
      "name": "Retrieve Items - Success",
      "priority": 1, // arbitrary number lower than the second priority
      "request": {
        "headers": {
          "accept": {
            "caseInsensitive": true,
            "equalTo": "application/json"
          }
        },
        "method": "GET",
        "urlPathPattern": "/api/items/(UUID1|UUID2|UUID3|UUID4)"
      },
      "response": {
        "bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json",
        "headers": {
          "content-type": "application/json"
        },
        "status": 200
      }
    },
    {
      "name": "Retrieve Items - 404 Not Found",
      "priority": 5, // arbitrary number that is higher than 1
      "request": {
        "headers": {
          "accept": {
            "caseInsensitive": true,
            "equalTo": "application/json"
          }
        },
        "method": "GET",
        "urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"
      },
      "response": {
        "status": 404
      }
    }
  ]
}

Wiremock stubs for an API client that has hardcoded urls

copy iconCopydownload iconDownload
JvmProxyConfigurer.configureFor(wireMockServer);

 wireMockServer.stubFor(get("/stuff")
    .withHost(equalTo("api.sandbox.braintreegateway.com"))
    .willReturn(okJson("{ ... }")));

// Test something that uses the Braintree client lib

Matching JSON request body based on JSON Path with logical operators in WireMock

copy iconCopydownload iconDownload
...
{
  "matchesJsonPath": "$[?(@.amnt < 20000)]"
}
...
{ 
  "amnt": 20000 // correct format
  "amnt": "20000" // incorrect format
}
-----------------------
...
{
  "matchesJsonPath": "$[?(@.amnt < 20000)]"
}
...
{ 
  "amnt": 20000 // correct format
  "amnt": "20000" // incorrect format
}

How to invoke JUnit5 test runner / Junit tag expressions using Maven Surefire plugin?

copy iconCopydownload iconDownload
pom.xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M5</version>
    <configuration>
        <groups>Demo1Test,Demo2Test,Demo3Test,Demo4Test</groups>
    </configuration>
</plugin>
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

@Tag("Demo1Test")
public class Demo1Test {

    @Test
    void name1(TestInfo info) {
        System.out.println(info.getDisplayName());
    }
}
-----------------------
pom.xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M5</version>
    <configuration>
        <groups>Demo1Test,Demo2Test,Demo3Test,Demo4Test</groups>
    </configuration>
</plugin>
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

@Tag("Demo1Test")
public class Demo1Test {

    @Test
    void name1(TestInfo info) {
        System.out.println(info.getDisplayName());
    }
}

quarkus.oidc.auth-server-url for both testing and localhost development

copy iconCopydownload iconDownload
src/test/resources/application.properties

Is there a way to block all external network access from a Java JUnit test?

copy iconCopydownload iconDownload
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M5</version>
    <configuration>
      <systemPropertyVariables>
        <socksProxyHost>localhost</socksProxyHost>
        <socksProxyPort>1080</socksProxyPort>
        [...]
      </systemPropertyVariables>
    </configuration>
  </plugin>
-----------------------
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.time.Duration;
import java.time.Instant;

public class BlockNetworkByProperty {

    public static void main(String[] args) throws Exception {

        System.setProperty("sun.net.spi.nameservice.nameservers", "192.168.0.254"); // Pick any dead IP.
        System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
        
        Instant start = Instant.now();
        System.out.println("Attempting connection.. ");

        try {
            
        URL oracle = new URL("https://www.cnet.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
            yc.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();

        System.out.println("Should not have gotten here.");
        } finally {
            long secondsPassed = Duration.between(start, Instant.now()).getSeconds();
            System.out.println(String.format("%s seconds have passed.", secondsPassed));
        }
        
    }

}
Attempting connection.. 
60 seconds have passed.
Exception in thread "main" java.net.UnknownHostException: www.cnet.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
...stack trace continues
-----------------------
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.time.Duration;
import java.time.Instant;

public class BlockNetworkByProperty {

    public static void main(String[] args) throws Exception {

        System.setProperty("sun.net.spi.nameservice.nameservers", "192.168.0.254"); // Pick any dead IP.
        System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
        
        Instant start = Instant.now();
        System.out.println("Attempting connection.. ");

        try {
            
        URL oracle = new URL("https://www.cnet.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
            yc.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();

        System.out.println("Should not have gotten here.");
        } finally {
            long secondsPassed = Duration.between(start, Instant.now()).getSeconds();
            System.out.println(String.format("%s seconds have passed.", secondsPassed));
        }
        
    }

}
Attempting connection.. 
60 seconds have passed.
Exception in thread "main" java.net.UnknownHostException: www.cnet.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
...stack trace continues
-----------------------
docker run --network none
-----------------------
    @Rule public SniffyRule sniffyRule = new SniffyRule();

    @Test
    @DisableSockets
    public void testDisableSockets() throws IOException {
        try {
            new Socket("google.com", 443);
            fail("Sniffy should have thrown ConnectException");
        } catch (ConnectException e) {
            assertNotNull(e);
        }
    }
-----------------------
public class DisableRemoteSocketsExtension implements BeforeAllCallback {
    private static final AtomicBoolean APPLIED = new AtomicBoolean(false);

    @Override
    public void beforeAll(ExtensionContext context) throws Exception {
        if (!APPLIED.get()) {
            System.out.println("Globally disabling non-loopback sockets");

            Socket.setSocketImplFactory(DisableRemoteSocketImpl::forSocket);
            ServerSocket.setSocketFactory(DisableRemoteSocketImpl::forServerSocket);

            APPLIED.set(true);
        }
    }
}
com.example.DisableRemoteSocketsExtension
junit.jupiter.extensions.autodetection.enabled=true
public class DisableRemoteSocketImpl extends SocketImpl {
    private static final Pattern LOOPBACK_PATTERN =
            Pattern.compile("^localhost$|^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^(?:0*:)*?:?0*1$");

    private final SocketImpl delegate;

    public DisableRemoteSocketImpl(SocketImpl delegate) {
        this.delegate = delegate;
    }

    public static DisableRemoteSocketImpl forSocket() {
        // Mimics implementation in Socket.setImpl()
        SocketImpl delegate = newSocksSocketImpl(getDefaultSocketImpl());
        return new DisableRemoteSocketImpl(delegate);
    }

    public static DisableRemoteSocketImpl forServerSocket() {
        // Mimics implementation in ServerSocket.setImpl()
        SocketImpl delegate = getDefaultSocketImpl();
        return new DisableRemoteSocketImpl(delegate);
    }

    @Override
    protected void create(boolean stream) throws IOException {
        callDelegate("create", new Class<?>[]{boolean.class}, new Object[]{stream});
    }

    @Override
    protected void connect(String host, int port) throws IOException {
        requireLoopbackAddress(host);
        callDelegate("connect", new Class<?>[]{String.class, int.class}, new Object[]{host, port});
    }

    @Override
    protected void connect(InetAddress address, int port) throws IOException {
        requireLoopbackAddress(address);
        callDelegate("connect", new Class<?>[]{InetAddress.class, int.class}, new Object[]{address, port});
    }

    @Override
    protected void connect(SocketAddress address, int timeout) throws IOException {
        if (!(address instanceof InetSocketAddress)) {
            throw new UnsupportedOperationException("Unsupported address type: " + address);
        }
        requireLoopbackAddress(((InetSocketAddress) address).getHostString());
        callDelegate("connect", new Class<?>[]{SocketAddress.class, int.class}, new Object[]{address, timeout});
    }

    @Override
    protected void bind(InetAddress host, int port) throws IOException {
        requireLoopbackAddress(host);
        callDelegate("bind", new Class<?>[]{InetAddress.class, int.class}, new Object[]{host, port});
    }

    @Override
    protected void listen(int backlog) throws IOException {
        callDelegate("listen", new Class<?>[]{int.class}, new Object[]{backlog});
    }

    @Override
    protected void accept(SocketImpl s) throws IOException {
        callDelegate("accept", new Class<?>[]{SocketImpl.class}, new Object[]{s});
    }

    @Override
    protected InputStream getInputStream() throws IOException {
        return callDelegate("getInputStream", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected OutputStream getOutputStream() throws IOException {
        return callDelegate("getOutputStream", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected int available() throws IOException {
        return callDelegate("available", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected void close() throws IOException {
        callDelegate("close", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected void sendUrgentData(int data) throws IOException {
        callDelegate("close", new Class<?>[]{int.class}, new Object[]{data});
    }

    @Override
    public void setOption(int optID, Object value) throws SocketException {
        delegate.setOption(optID, value);
    }

    @Override
    public Object getOption(int optID) throws SocketException {
        return delegate.getOption(optID);
    }

    private void requireLoopbackAddress(String host) {
        if (!LOOPBACK_PATTERN.matcher(host).matches()) {
            throw new UnsupportedOperationException("Attempted to connect to remote host: " + host);
        }
    }

    private void requireLoopbackAddress(InetAddress address) {
        if (!address.isLoopbackAddress()) {
            throw new UnsupportedOperationException("Attempted to connect to remote host: " + address);
        }
    }

    private static SocketImpl createDelegate() {
        // Mimics implementation in Socket.setImpl()
        return newSocksSocketImpl(getDefaultSocketImpl());
    }

    private static SocketImpl getDefaultSocketImpl() {
        try {
            Method factoryMethod = SocketImpl.class.getDeclaredMethod("createPlatformSocketImpl", Boolean.TYPE);
            factoryMethod.setAccessible(true);
            return (SocketImpl) factoryMethod.invoke(null, false);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    private static SocketImpl newSocksSocketImpl(SocketImpl delegate) {
        try {
            Constructor<? extends SocketImpl> constructor = Class.forName("java.net.SocksSocketImpl")
                    .asSubclass(SocketImpl.class).getDeclaredConstructor(SocketImpl.class);
            constructor.setAccessible(true);
            return constructor.newInstance(delegate);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    private <T> T callDelegate(String methodName, Class<?>[] parameterTypes, Object[] args) throws IOException {
        try {
            Method method = SocketImpl.class.getDeclaredMethod(methodName, parameterTypes);
            method.setAccessible(true);
            return (T) method.invoke(delegate, args);
        } catch (InvocationTargetException invocationTargetException) {
            Throwable e = invocationTargetException.getCause();
            if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else if (e instanceof Error) {
                throw (Error) e;
            } else {
                throw new AssertionError(invocationTargetException);
            }
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }
}
-----------------------
public class DisableRemoteSocketsExtension implements BeforeAllCallback {
    private static final AtomicBoolean APPLIED = new AtomicBoolean(false);

    @Override
    public void beforeAll(ExtensionContext context) throws Exception {
        if (!APPLIED.get()) {
            System.out.println("Globally disabling non-loopback sockets");

            Socket.setSocketImplFactory(DisableRemoteSocketImpl::forSocket);
            ServerSocket.setSocketFactory(DisableRemoteSocketImpl::forServerSocket);

            APPLIED.set(true);
        }
    }
}
com.example.DisableRemoteSocketsExtension
junit.jupiter.extensions.autodetection.enabled=true
public class DisableRemoteSocketImpl extends SocketImpl {
    private static final Pattern LOOPBACK_PATTERN =
            Pattern.compile("^localhost$|^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^(?:0*:)*?:?0*1$");

    private final SocketImpl delegate;

    public DisableRemoteSocketImpl(SocketImpl delegate) {
        this.delegate = delegate;
    }

    public static DisableRemoteSocketImpl forSocket() {
        // Mimics implementation in Socket.setImpl()
        SocketImpl delegate = newSocksSocketImpl(getDefaultSocketImpl());
        return new DisableRemoteSocketImpl(delegate);
    }

    public static DisableRemoteSocketImpl forServerSocket() {
        // Mimics implementation in ServerSocket.setImpl()
        SocketImpl delegate = getDefaultSocketImpl();
        return new DisableRemoteSocketImpl(delegate);
    }

    @Override
    protected void create(boolean stream) throws IOException {
        callDelegate("create", new Class<?>[]{boolean.class}, new Object[]{stream});
    }

    @Override
    protected void connect(String host, int port) throws IOException {
        requireLoopbackAddress(host);
        callDelegate("connect", new Class<?>[]{String.class, int.class}, new Object[]{host, port});
    }

    @Override
    protected void connect(InetAddress address, int port) throws IOException {
        requireLoopbackAddress(address);
        callDelegate("connect", new Class<?>[]{InetAddress.class, int.class}, new Object[]{address, port});
    }

    @Override
    protected void connect(SocketAddress address, int timeout) throws IOException {
        if (!(address instanceof InetSocketAddress)) {
            throw new UnsupportedOperationException("Unsupported address type: " + address);
        }
        requireLoopbackAddress(((InetSocketAddress) address).getHostString());
        callDelegate("connect", new Class<?>[]{SocketAddress.class, int.class}, new Object[]{address, timeout});
    }

    @Override
    protected void bind(InetAddress host, int port) throws IOException {
        requireLoopbackAddress(host);
        callDelegate("bind", new Class<?>[]{InetAddress.class, int.class}, new Object[]{host, port});
    }

    @Override
    protected void listen(int backlog) throws IOException {
        callDelegate("listen", new Class<?>[]{int.class}, new Object[]{backlog});
    }

    @Override
    protected void accept(SocketImpl s) throws IOException {
        callDelegate("accept", new Class<?>[]{SocketImpl.class}, new Object[]{s});
    }

    @Override
    protected InputStream getInputStream() throws IOException {
        return callDelegate("getInputStream", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected OutputStream getOutputStream() throws IOException {
        return callDelegate("getOutputStream", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected int available() throws IOException {
        return callDelegate("available", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected void close() throws IOException {
        callDelegate("close", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected void sendUrgentData(int data) throws IOException {
        callDelegate("close", new Class<?>[]{int.class}, new Object[]{data});
    }

    @Override
    public void setOption(int optID, Object value) throws SocketException {
        delegate.setOption(optID, value);
    }

    @Override
    public Object getOption(int optID) throws SocketException {
        return delegate.getOption(optID);
    }

    private void requireLoopbackAddress(String host) {
        if (!LOOPBACK_PATTERN.matcher(host).matches()) {
            throw new UnsupportedOperationException("Attempted to connect to remote host: " + host);
        }
    }

    private void requireLoopbackAddress(InetAddress address) {
        if (!address.isLoopbackAddress()) {
            throw new UnsupportedOperationException("Attempted to connect to remote host: " + address);
        }
    }

    private static SocketImpl createDelegate() {
        // Mimics implementation in Socket.setImpl()
        return newSocksSocketImpl(getDefaultSocketImpl());
    }

    private static SocketImpl getDefaultSocketImpl() {
        try {
            Method factoryMethod = SocketImpl.class.getDeclaredMethod("createPlatformSocketImpl", Boolean.TYPE);
            factoryMethod.setAccessible(true);
            return (SocketImpl) factoryMethod.invoke(null, false);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    private static SocketImpl newSocksSocketImpl(SocketImpl delegate) {
        try {
            Constructor<? extends SocketImpl> constructor = Class.forName("java.net.SocksSocketImpl")
                    .asSubclass(SocketImpl.class).getDeclaredConstructor(SocketImpl.class);
            constructor.setAccessible(true);
            return constructor.newInstance(delegate);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    private <T> T callDelegate(String methodName, Class<?>[] parameterTypes, Object[] args) throws IOException {
        try {
            Method method = SocketImpl.class.getDeclaredMethod(methodName, parameterTypes);
            method.setAccessible(true);
            return (T) method.invoke(delegate, args);
        } catch (InvocationTargetException invocationTargetException) {
            Throwable e = invocationTargetException.getCause();
            if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else if (e instanceof Error) {
                throw (Error) e;
            } else {
                throw new AssertionError(invocationTargetException);
            }
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }
}
-----------------------
public class DisableRemoteSocketsExtension implements BeforeAllCallback {
    private static final AtomicBoolean APPLIED = new AtomicBoolean(false);

    @Override
    public void beforeAll(ExtensionContext context) throws Exception {
        if (!APPLIED.get()) {
            System.out.println("Globally disabling non-loopback sockets");

            Socket.setSocketImplFactory(DisableRemoteSocketImpl::forSocket);
            ServerSocket.setSocketFactory(DisableRemoteSocketImpl::forServerSocket);

            APPLIED.set(true);
        }
    }
}
com.example.DisableRemoteSocketsExtension
junit.jupiter.extensions.autodetection.enabled=true
public class DisableRemoteSocketImpl extends SocketImpl {
    private static final Pattern LOOPBACK_PATTERN =
            Pattern.compile("^localhost$|^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^(?:0*:)*?:?0*1$");

    private final SocketImpl delegate;

    public DisableRemoteSocketImpl(SocketImpl delegate) {
        this.delegate = delegate;
    }

    public static DisableRemoteSocketImpl forSocket() {
        // Mimics implementation in Socket.setImpl()
        SocketImpl delegate = newSocksSocketImpl(getDefaultSocketImpl());
        return new DisableRemoteSocketImpl(delegate);
    }

    public static DisableRemoteSocketImpl forServerSocket() {
        // Mimics implementation in ServerSocket.setImpl()
        SocketImpl delegate = getDefaultSocketImpl();
        return new DisableRemoteSocketImpl(delegate);
    }

    @Override
    protected void create(boolean stream) throws IOException {
        callDelegate("create", new Class<?>[]{boolean.class}, new Object[]{stream});
    }

    @Override
    protected void connect(String host, int port) throws IOException {
        requireLoopbackAddress(host);
        callDelegate("connect", new Class<?>[]{String.class, int.class}, new Object[]{host, port});
    }

    @Override
    protected void connect(InetAddress address, int port) throws IOException {
        requireLoopbackAddress(address);
        callDelegate("connect", new Class<?>[]{InetAddress.class, int.class}, new Object[]{address, port});
    }

    @Override
    protected void connect(SocketAddress address, int timeout) throws IOException {
        if (!(address instanceof InetSocketAddress)) {
            throw new UnsupportedOperationException("Unsupported address type: " + address);
        }
        requireLoopbackAddress(((InetSocketAddress) address).getHostString());
        callDelegate("connect", new Class<?>[]{SocketAddress.class, int.class}, new Object[]{address, timeout});
    }

    @Override
    protected void bind(InetAddress host, int port) throws IOException {
        requireLoopbackAddress(host);
        callDelegate("bind", new Class<?>[]{InetAddress.class, int.class}, new Object[]{host, port});
    }

    @Override
    protected void listen(int backlog) throws IOException {
        callDelegate("listen", new Class<?>[]{int.class}, new Object[]{backlog});
    }

    @Override
    protected void accept(SocketImpl s) throws IOException {
        callDelegate("accept", new Class<?>[]{SocketImpl.class}, new Object[]{s});
    }

    @Override
    protected InputStream getInputStream() throws IOException {
        return callDelegate("getInputStream", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected OutputStream getOutputStream() throws IOException {
        return callDelegate("getOutputStream", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected int available() throws IOException {
        return callDelegate("available", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected void close() throws IOException {
        callDelegate("close", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected void sendUrgentData(int data) throws IOException {
        callDelegate("close", new Class<?>[]{int.class}, new Object[]{data});
    }

    @Override
    public void setOption(int optID, Object value) throws SocketException {
        delegate.setOption(optID, value);
    }

    @Override
    public Object getOption(int optID) throws SocketException {
        return delegate.getOption(optID);
    }

    private void requireLoopbackAddress(String host) {
        if (!LOOPBACK_PATTERN.matcher(host).matches()) {
            throw new UnsupportedOperationException("Attempted to connect to remote host: " + host);
        }
    }

    private void requireLoopbackAddress(InetAddress address) {
        if (!address.isLoopbackAddress()) {
            throw new UnsupportedOperationException("Attempted to connect to remote host: " + address);
        }
    }

    private static SocketImpl createDelegate() {
        // Mimics implementation in Socket.setImpl()
        return newSocksSocketImpl(getDefaultSocketImpl());
    }

    private static SocketImpl getDefaultSocketImpl() {
        try {
            Method factoryMethod = SocketImpl.class.getDeclaredMethod("createPlatformSocketImpl", Boolean.TYPE);
            factoryMethod.setAccessible(true);
            return (SocketImpl) factoryMethod.invoke(null, false);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    private static SocketImpl newSocksSocketImpl(SocketImpl delegate) {
        try {
            Constructor<? extends SocketImpl> constructor = Class.forName("java.net.SocksSocketImpl")
                    .asSubclass(SocketImpl.class).getDeclaredConstructor(SocketImpl.class);
            constructor.setAccessible(true);
            return constructor.newInstance(delegate);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    private <T> T callDelegate(String methodName, Class<?>[] parameterTypes, Object[] args) throws IOException {
        try {
            Method method = SocketImpl.class.getDeclaredMethod(methodName, parameterTypes);
            method.setAccessible(true);
            return (T) method.invoke(delegate, args);
        } catch (InvocationTargetException invocationTargetException) {
            Throwable e = invocationTargetException.getCause();
            if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else if (e instanceof Error) {
                throw (Error) e;
            } else {
                throw new AssertionError(invocationTargetException);
            }
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }
}
-----------------------
public class DisableRemoteSocketsExtension implements BeforeAllCallback {
    private static final AtomicBoolean APPLIED = new AtomicBoolean(false);

    @Override
    public void beforeAll(ExtensionContext context) throws Exception {
        if (!APPLIED.get()) {
            System.out.println("Globally disabling non-loopback sockets");

            Socket.setSocketImplFactory(DisableRemoteSocketImpl::forSocket);
            ServerSocket.setSocketFactory(DisableRemoteSocketImpl::forServerSocket);

            APPLIED.set(true);
        }
    }
}
com.example.DisableRemoteSocketsExtension
junit.jupiter.extensions.autodetection.enabled=true
public class DisableRemoteSocketImpl extends SocketImpl {
    private static final Pattern LOOPBACK_PATTERN =
            Pattern.compile("^localhost$|^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^(?:0*:)*?:?0*1$");

    private final SocketImpl delegate;

    public DisableRemoteSocketImpl(SocketImpl delegate) {
        this.delegate = delegate;
    }

    public static DisableRemoteSocketImpl forSocket() {
        // Mimics implementation in Socket.setImpl()
        SocketImpl delegate = newSocksSocketImpl(getDefaultSocketImpl());
        return new DisableRemoteSocketImpl(delegate);
    }

    public static DisableRemoteSocketImpl forServerSocket() {
        // Mimics implementation in ServerSocket.setImpl()
        SocketImpl delegate = getDefaultSocketImpl();
        return new DisableRemoteSocketImpl(delegate);
    }

    @Override
    protected void create(boolean stream) throws IOException {
        callDelegate("create", new Class<?>[]{boolean.class}, new Object[]{stream});
    }

    @Override
    protected void connect(String host, int port) throws IOException {
        requireLoopbackAddress(host);
        callDelegate("connect", new Class<?>[]{String.class, int.class}, new Object[]{host, port});
    }

    @Override
    protected void connect(InetAddress address, int port) throws IOException {
        requireLoopbackAddress(address);
        callDelegate("connect", new Class<?>[]{InetAddress.class, int.class}, new Object[]{address, port});
    }

    @Override
    protected void connect(SocketAddress address, int timeout) throws IOException {
        if (!(address instanceof InetSocketAddress)) {
            throw new UnsupportedOperationException("Unsupported address type: " + address);
        }
        requireLoopbackAddress(((InetSocketAddress) address).getHostString());
        callDelegate("connect", new Class<?>[]{SocketAddress.class, int.class}, new Object[]{address, timeout});
    }

    @Override
    protected void bind(InetAddress host, int port) throws IOException {
        requireLoopbackAddress(host);
        callDelegate("bind", new Class<?>[]{InetAddress.class, int.class}, new Object[]{host, port});
    }

    @Override
    protected void listen(int backlog) throws IOException {
        callDelegate("listen", new Class<?>[]{int.class}, new Object[]{backlog});
    }

    @Override
    protected void accept(SocketImpl s) throws IOException {
        callDelegate("accept", new Class<?>[]{SocketImpl.class}, new Object[]{s});
    }

    @Override
    protected InputStream getInputStream() throws IOException {
        return callDelegate("getInputStream", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected OutputStream getOutputStream() throws IOException {
        return callDelegate("getOutputStream", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected int available() throws IOException {
        return callDelegate("available", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected void close() throws IOException {
        callDelegate("close", new Class<?>[]{}, new Object[]{});
    }

    @Override
    protected void sendUrgentData(int data) throws IOException {
        callDelegate("close", new Class<?>[]{int.class}, new Object[]{data});
    }

    @Override
    public void setOption(int optID, Object value) throws SocketException {
        delegate.setOption(optID, value);
    }

    @Override
    public Object getOption(int optID) throws SocketException {
        return delegate.getOption(optID);
    }

    private void requireLoopbackAddress(String host) {
        if (!LOOPBACK_PATTERN.matcher(host).matches()) {
            throw new UnsupportedOperationException("Attempted to connect to remote host: " + host);
        }
    }

    private void requireLoopbackAddress(InetAddress address) {
        if (!address.isLoopbackAddress()) {
            throw new UnsupportedOperationException("Attempted to connect to remote host: " + address);
        }
    }

    private static SocketImpl createDelegate() {
        // Mimics implementation in Socket.setImpl()
        return newSocksSocketImpl(getDefaultSocketImpl());
    }

    private static SocketImpl getDefaultSocketImpl() {
        try {
            Method factoryMethod = SocketImpl.class.getDeclaredMethod("createPlatformSocketImpl", Boolean.TYPE);
            factoryMethod.setAccessible(true);
            return (SocketImpl) factoryMethod.invoke(null, false);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    private static SocketImpl newSocksSocketImpl(SocketImpl delegate) {
        try {
            Constructor<? extends SocketImpl> constructor = Class.forName("java.net.SocksSocketImpl")
                    .asSubclass(SocketImpl.class).getDeclaredConstructor(SocketImpl.class);
            constructor.setAccessible(true);
            return constructor.newInstance(delegate);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    private <T> T callDelegate(String methodName, Class<?>[] parameterTypes, Object[] args) throws IOException {
        try {
            Method method = SocketImpl.class.getDeclaredMethod(methodName, parameterTypes);
            method.setAccessible(true);
            return (T) method.invoke(delegate, args);
        } catch (InvocationTargetException invocationTargetException) {
            Throwable e = invocationTargetException.getCause();
            if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else if (e instanceof Error) {
                throw (Error) e;
            } else {
                throw new AssertionError(invocationTargetException);
            }
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }
}

Can I create a spring bean as part of my cucumber step definitions?

copy iconCopydownload iconDownload
@Profile("cucumber")
@TestConfiguration
public class ClockConfiguration {
    @Bean
    public Clock clock() {
        return Clock.fixed(Instant.parse(TestScope.getDateValue()), ZoneId.systemDefault());
    }
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    TestScope.setDateValue(dateTime);
}

-----------------------
@Profile("cucumber")
@TestConfiguration
public class ClockConfiguration {
    @Bean
    public Clock clock() {
        return Clock.fixed(Instant.parse(TestScope.getDateValue()), ZoneId.systemDefault());
    }
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    TestScope.setDateValue(dateTime);
}

-----------------------
public void setClock(String dateTime) {
    this.clock = Clock.fixed(Instant.parse(dateTime), ZoneId.systemDefault());
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    applicationContext.getBean(MyWrapperClock.class).setClock(dateTime);
}
@Bean 
public Clock clock() {
    return Mockito.mock(Clock.class);
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    when(this.clock.instant()).thenReturn(Instant.parse(dateTime));
    when(this.clock.getZone()).thenReturn(ZoneId.systemDefault());
}
-----------------------
public void setClock(String dateTime) {
    this.clock = Clock.fixed(Instant.parse(dateTime), ZoneId.systemDefault());
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    applicationContext.getBean(MyWrapperClock.class).setClock(dateTime);
}
@Bean 
public Clock clock() {
    return Mockito.mock(Clock.class);
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    when(this.clock.instant()).thenReturn(Instant.parse(dateTime));
    when(this.clock.getZone()).thenReturn(ZoneId.systemDefault());
}
-----------------------
public void setClock(String dateTime) {
    this.clock = Clock.fixed(Instant.parse(dateTime), ZoneId.systemDefault());
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    applicationContext.getBean(MyWrapperClock.class).setClock(dateTime);
}
@Bean 
public Clock clock() {
    return Mockito.mock(Clock.class);
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    when(this.clock.instant()).thenReturn(Instant.parse(dateTime));
    when(this.clock.getZone()).thenReturn(ZoneId.systemDefault());
}
-----------------------
public void setClock(String dateTime) {
    this.clock = Clock.fixed(Instant.parse(dateTime), ZoneId.systemDefault());
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    applicationContext.getBean(MyWrapperClock.class).setClock(dateTime);
}
@Bean 
public Clock clock() {
    return Mockito.mock(Clock.class);
}
@Given("now is {string})
public void setDateTime(String dateTime) {
    when(this.clock.instant()).thenReturn(Instant.parse(dateTime));
    when(this.clock.getZone()).thenReturn(ZoneId.systemDefault());
}

Community Discussions

Trending Discussions on wiremock
  • How to write response in wiremock as a template with list?
  • Docker Container with Wiremock could not find stub mappings
  • Unable to run JUnit5 tests with Maven
  • how to setup Wiremock dynamic port
  • Implement different response with WireMock when no request(s) match
  • Wiremock stubs for an API client that has hardcoded urls
  • SpringBoot2 Configuration JOOQ MariaDB: &quot;required a bean of type 'javax.sql.DataSource' that could not be found&quot;
  • Trying to update embedded database when mocked http response is returned using Wiremock of MockServer
  • Wiremock does not receive any requests
  • With wiremock how can I match against the wiremock server URL in the body of a POST?
Trending Discussions on wiremock

QUESTION

How to write response in wiremock as a template with list?

Asked 2022-Mar-18 at 20:10

I want to use template response in wiremock and set list as a parameter. How to do that?

I set up wiremock in Java:

wireMockServer.stubFor(get(urlPathEqualTo("/somePath"))
            .withQueryParam("place.id", equalTo(buildingId))
            .willReturn(aResponse()
                .withHeader("Content-Type", "application/json")
                .withBodyFile("wiremock/response-template.json") //how to set up this file
                .withTransformerParameters(Map.of(
                    "place", "New York",
                    "users", List.of(new User("John", 24), new User("Merry", 31)) //list to insert
                 ))
                .withTransformers("response-template")));

How to write file: response-template.json to have result like this:

{
  "place": "New York",
  "users": [
    {
      "name": "John",
      "age": 24
    },
    {
      "name": "Marry",
      "age": 31
    }
  ]
}

I know that it should start like this:

{
  "place": "{{parameters.place}}",
  "users": [
    ???
  ]
}

I

ANSWER

Answered 2022-Mar-18 at 20:10

The easiest solution would be to use Jackson2 Helper or any other helper that can serialize to jsons.

  1. Add Handlebars jackson2 dependency to your project:
  • Gradle
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
  • Maven
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars-jackson2</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>
  1. Register handler with your wiremock instance :
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
                .extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))

The name of the helper will be json and that is how you will refer to it from your template.

  1. In your template use it like :
{
  "place": "{{parameters.place}}",
  "users": {{json parameters.users}}
}
  1. The output is :
{
  "place": "New York",
  "users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}

Of course you can customize Jackson2Helper and create your own instance with own ObjectMapper instance - this is useful if you are using Spring and want to use same serialization options everywhere.

Source https://stackoverflow.com/questions/71529928

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install wiremock

You can download it from GitHub, Maven.
You can use wiremock like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the wiremock component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

If you have a question about WireMock, or are experiencing a problem you’re not sure is a bug please post a message to the [WireMock mailing list](https://groups.google.com/forum/#!forum/wiremock-user). On the other hand if you’re pretty certain you’ve found a bug please open an issue.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Consider Popular Mock Libraries
Compare Mock Libraries with Highest Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.