Skip to content

Commit

Permalink
feat: Mock Web Server migrated to this repository
Browse files Browse the repository at this point in the history
Signed-off-by: Marc Nuri <[email protected]>
  • Loading branch information
manusa committed Sep 20, 2023
1 parent 3bd9373 commit 053e88f
Show file tree
Hide file tree
Showing 76 changed files with 5,370 additions and 18 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* Fix #5373: Gradle base API based on v8.2.1

#### New Features
* Fix #5430: Mock Web Server migrated to this repository

#### _**Note**_: Breaking changes
* Fix #5343: Removed `io.fabric8.kubernetes.model.annotation.PrinterColumn`, use `io.fabric8.crd.generator.annotation.PrinterColumn`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ default MockResponse handle(RecordedRequest request) throws KubernetesCrudDispat
default void validatePath(AttributeSet query, JsonNode updatedResource) throws KubernetesCrudDispatcherException {
// metadata.name
final String updatedName = updatedResource.path(METADATA).path(NAME).asText();
final String pathName = query.getAttribute(NAME).getValue().toString();
final String pathName = query.getAttribute(NAME).getValues().iterator().next().toString();
if (!updatedName.isEmpty() && !pathName.equals(updatedName)) {
throw new KubernetesCrudDispatcherException(
"the name of the object (" + updatedName + ") does not match the name on the URL (" + pathName + ")",
Expand All @@ -62,7 +62,7 @@ default void validatePath(AttributeSet query, JsonNode updatedResource) throws K
// metadata.namespace
if (query.getAttribute(NAMESPACE) != null) {
final String updatedNamespace = updatedResource.path(METADATA).path(NAMESPACE).asText();
final String pathNamespace = query.getAttribute(NAMESPACE).getValue().toString();
final String pathNamespace = query.getAttribute(NAMESPACE).getValues().iterator().next().toString();
if (!updatedNamespace.isEmpty() && !updatedNamespace.equals(pathNamespace)) {
throw new KubernetesCrudDispatcherException(
"the namespace of the object (" + updatedNamespace + ") does not match the namespace on the URL ("
Expand Down
72 changes: 72 additions & 0 deletions junit/mockwebserver/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2015 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.fabric8</groupId>
<artifactId>kubernetes-client-project</artifactId>
<version>6.9-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

<artifactId>mockwebserver</artifactId>
<packaging>jar</packaging>

<name>Fabric8 :: Mock Web Server</name>

<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>io.fabric8</groupId>
<artifactId>zjsonpatch</artifactId>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>${gmavenplus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>

</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.mockwebserver;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Context {

private final ObjectMapper mapper;

public Context() {
this(new ObjectMapper());
}

public Context(ObjectMapper mapper) {
this.mapper = mapper;
}

public ObjectMapper getMapper() {
return mapper;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.fabric8.mockwebserver;

import io.fabric8.mockwebserver.dsl.MockServerExpectation;
import io.fabric8.mockwebserver.internal.MockDispatcher;
import io.fabric8.mockwebserver.internal.MockSSLContextFactory;
import io.fabric8.mockwebserver.internal.MockServerExpectationImpl;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class DefaultMockServer implements MockServer {

private final Context context;
private final boolean useHttps;
private final MockWebServer server;
private final Map<ServerRequest, Queue<ServerResponse>> responses;
private final AtomicInteger lastRequestCount;
private final AtomicReference<RecordedRequest> lastRequest;

private final AtomicBoolean initialized = new AtomicBoolean();
private final AtomicBoolean shutdown = new AtomicBoolean();

public DefaultMockServer() {
this(new Context(), new MockWebServer(), new HashMap<>(), false);
}

public DefaultMockServer(boolean useHttps) {
this(new Context(), new MockWebServer(), new HashMap<>(), useHttps);
}

public DefaultMockServer(MockWebServer server, Map<ServerRequest, Queue<ServerResponse>> responses, boolean useHttps) {
this(new Context(), server, responses, useHttps);
}

public DefaultMockServer(Context context, MockWebServer server, Map<ServerRequest, Queue<ServerResponse>> responses,
boolean useHttps) {
this(context, server, responses, new MockDispatcher(responses), useHttps);
}

public DefaultMockServer(Context context, MockWebServer server, Map<ServerRequest, Queue<ServerResponse>> responses,
Dispatcher dispatcher, boolean useHttps) {
this.context = context;
this.useHttps = useHttps;
this.server = server;
this.responses = responses;
this.lastRequest = new AtomicReference<>();
this.lastRequestCount = new AtomicInteger(0);
this.server.setDispatcher(dispatcher);
}

private void startInternal() {
if (initialized.compareAndSet(false, true)) {
if (useHttps) {
server.useHttps(MockSSLContextFactory.create().getSocketFactory(), false);
}
onStart();
}
}

private void shutdownInternal() {
if (shutdown.compareAndSet(false, true)) {
onShutdown();
}
}

public final void start() {
try {
startInternal();
server.start();
} catch (IOException e) {
throw new MockServerException("Exception when starting DefaultMockServer", e);
}
}

public final void start(int port) {
try {
startInternal();
server.start(port);
} catch (IOException e) {
throw new MockServerException("Exception when starting DefaultMockServer with port", e);
}
}

public final void start(InetAddress inetAddress, int port) {
try {
startInternal();
server.start(inetAddress, port);
} catch (IOException e) {
throw new MockServerException("Exception when starting DefaultMockServer with InetAddress and port", e);
}
}

public final void shutdown() {
try {
server.shutdown();
} catch (IOException e) {
throw new MockServerException("Exception when stopping DefaultMockServer", e);
} finally {
shutdownInternal();
}
}

/**
* {@inheritDoc}
*/
@Override
public String url(String path) {
return server.url(path).toString();
}

/**
* {@inheritDoc}
*/
@Override
public int getPort() {
return server.getPort();
}

/**
* {@inheritDoc}
*/
@Override
public String getHostName() {
return server.getHostName();
}

/**
* {@inheritDoc}
*/
@Override
public Proxy toProxyAddress() {
return server.toProxyAddress();
}

/**
* {@inheritDoc}
*/
@Override
public MockServerExpectation expect() {
return new MockServerExpectationImpl(responses, context);
}

/**
* {@inheritDoc}
*/
@Override
public int getRequestCount() {
return server.getRequestCount();
}

/**
* {@inheritDoc}
*/
@Override
public RecordedRequest takeRequest() throws InterruptedException {
return server.takeRequest();
}

/**
* {@inheritDoc}
*/
@Override
public RecordedRequest takeRequest(long timeout, TimeUnit unit) throws InterruptedException {
return server.takeRequest(timeout, unit);
}

/**
* {@inheritDoc}
*/
@Override
public synchronized RecordedRequest getLastRequest() throws InterruptedException {
if (lastRequest.get() != null && getRequestCount() == lastRequestCount.get()) {
return lastRequest.get();
}
int requestCount = getRequestCount() - lastRequestCount.getAndSet(getRequestCount());
RecordedRequest latestRequest = null;
while (requestCount-- > 0) {
latestRequest = takeRequest();
}
lastRequest.set(latestRequest);
return latestRequest;
}
}
Loading

0 comments on commit 053e88f

Please sign in to comment.