Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate ServiceNow, Slack, Geocoder & Telegram tests to WireMock #1993

Merged
merged 7 commits into from
Nov 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ List<ReflectiveClassBuildItem> registerReflectiveClasses() {
items.add(new ReflectiveClassBuildItem(false, true, "com.google.maps.model.Bounds"));
items.add(new ReflectiveClassBuildItem(false, true, "com.google.maps.model.LatLng"));
items.add(new ReflectiveClassBuildItem(false, true, "com.google.maps.model.LocationType"));
items.add(new ReflectiveClassBuildItem(false, true, "com.google.maps.model.GeolocationPayload"));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your effort pays back!

return items;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import java.util.Map;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.common.ClasspathFileSource;
import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.recording.RecordingStatus;
import com.github.tomakehurst.wiremock.recording.SnapshotRecordResult;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
Expand Down Expand Up @@ -116,26 +118,30 @@ public void stop() {
@Override
public void inject(Object testInstance) {
if (isMockingEnabled() || isRecordingEnabled()) {
Class<?> c = testInstance.getClass();
for (Field field : c.getDeclaredFields()) {
if (field.getAnnotation(MockServer.class) != null) {
if (!WireMockServer.class.isAssignableFrom(field.getType())) {
throw new RuntimeException("@MockServer can only be used on fields of type WireMockServer");
}
Class<?> testClass = testInstance.getClass();
while (testClass != Object.class) {
for (Field field : testClass.getDeclaredFields()) {
if (field.getAnnotation(MockServer.class) != null) {
if (!WireMockServer.class.isAssignableFrom(field.getType())) {
throw new RuntimeException("@MockServer can only be used on fields of type WireMockServer");
}

field.setAccessible(true);
try {
if (server == null) {
server = createServer();
server.start();
field.setAccessible(true);
try {
if (server == null) {
LOG.info("Starting WireMockServer");
server = createServer();
server.start();
}
LOG.infof("Injecting WireMockServer for field %s", field.getName());
field.set(testInstance, server);
return;
} catch (Exception e) {
throw new RuntimeException(e);
}
LOG.infof("Injecting WireMockServer for field %s", field.getName());
field.set(testInstance, server);
return;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
testClass = testClass.getSuperclass();
}
}
}
Expand Down Expand Up @@ -196,7 +202,9 @@ protected boolean isDeleteRecordedMappingsOnError() {
private WireMockServer createServer() {
LOG.info("Starting WireMockServer");
MockBackendUtils.startMockBackend(true);
return new WireMockServer(options().dynamicPort());
return new WireMockServer(options()
.dynamicPort()
.fileSource(new CamelQuarkusFileSource()));
}

/**
Expand All @@ -208,4 +216,18 @@ private boolean isRecordingEnabled() {
String recordEnabled = System.getProperty("wiremock.record", System.getenv("WIREMOCK_RECORD"));
return recordEnabled != null && recordEnabled.equals("true");
}

/**
* A custom ClasspathFileSource so that WireMock mapping files can be resolved in the quarkus-platform build
*/
private static class CamelQuarkusFileSource extends ClasspathFileSource {
private CamelQuarkusFileSource() {
super("");
}

@Override
public FileSource child(String subDirectoryName) {
return new ClasspathFileSource(subDirectoryName);
}
}
}
10 changes: 10 additions & 0 deletions integration-tests/geocoder/README.adoc
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
== Camel Quarkus Geocoder Integration Tests

By default the Geocoder integration tests use WireMock to stub the API interactions.

To run `camel-quarkus-geocoder` integration tests using google maps service, you will need a google cloud https://developers.google.com/maps/documentation/javascript/get-api-key[API key].

Then set the following environment variable:
Expand All @@ -8,3 +10,11 @@ Then set the following environment variable:
----
GOOGLE_API_KEY=your-api-id
----

If the WireMock stub recordings need updating, then remove the existing files from `src/test/resources/mappings` and run tests with either:

System property `-Dwiremock.record=true`

Or

Set environment variable `WIREMOCK_RECORD=true`
2 changes: 1 addition & 1 deletion integration-tests/geocoder/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
</dependency>
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-integration-test-support-mock-backend</artifactId>
<artifactId>camel-quarkus-integration-wiremock-support</artifactId>
</dependency>


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public GeocodingResult[] getByCurrentLocation() {
LOG.infof("Retrieve info from current location");
final GeocodingResult[] response = producerTemplate.requestBody(
String.format("geocoder:address:current?apiKey=%s", googleApiKey),
"Hello World", GeocodingResult[].class);
null, GeocodingResult[].class);
LOG.infof("Response : %s", response);
return response;
}
Expand All @@ -57,7 +57,7 @@ public GeocodingResult[] getByAddress(@PathParam("address") String address) {
LOG.infof("Retrieve info from address : %s", address);
final GeocodingResult[] response = producerTemplate.requestBody(
String.format("geocoder:address:%s?apiKey=%s", address, googleApiKey),
"Hello World", GeocodingResult[].class);
null, GeocodingResult[].class);
LOG.infof("Response: %s", response);
return response;
}
Expand All @@ -68,7 +68,7 @@ public GeocodingResult[] getByCoordinate(@PathParam("lat") String latitude, @Pat
LOG.infof("Retrieve info from georgraphic coordinates latitude : %s, longitude %s", latitude, longitude);
final GeocodingResult[] response = producerTemplate.requestBody(
String.format("geocoder:latlng:%s,%s?apiKey=%s", latitude, longitude, googleApiKey),
"Hello World", GeocodingResult[].class);
null, GeocodingResult[].class);
LOG.infof("Response : %s", response);
return response;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.camel.quarkus.component.geocoder.it;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Named;

import io.quarkus.arc.Unremovable;
import org.apache.camel.CamelContext;
import org.apache.camel.component.geocoder.GeoCoderComponent;
import org.eclipse.microprofile.config.inject.ConfigProperty;

@ApplicationScoped
public class GeocoderProducers {

@ConfigProperty(name = "google.api.key")
String googleApiKey;

/**
* We need to implement some conditional configuration of the {@link GeoCoderComponent} thus we create it
* programmatically and publish via CDI.
*
* @return a configured {@link GeoCoderComponent}
*/
@Produces
@ApplicationScoped
@Unremovable
@Named("geocoder")
GeoCoderComponent geocoderComponent(CamelContext camelContext, MockApiService mockApiService)
throws IllegalAccessException, NoSuchFieldException, InstantiationException {
final String wireMockUrl = System.getProperty("wiremock.url");
final GeoCoderComponent result = new GeoCoderComponent();
result.setCamelContext(camelContext);

if (wireMockUrl != null) {
result.setGeoApiContext(mockApiService.createGeoApiContext(wireMockUrl, googleApiKey));
}
return result;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,7 @@
# add your API KEY to run the examples
google.api.key=${GOOGLE_API_KEY:AIzaFakeKey}

# You may want to export CAMEL_QUARKUS_START_MOCK_BACKEND=false to avoid starting he the mock Google Maps API
# to make sure that you test against the real remote Google Maps API
camel.quarkus.start-mock-backend=true

# this configuration is needed only to mock Google Maps API
quarkus.index-dependency.gmaps.group-id=com.google.maps
quarkus.index-dependency.gmaps.artifact-id=google-maps-services
quarkus.camel.native.reflection.include-patterns=com.google.maps.GeoApiContext$Builder


quarkus.camel.native.reflection.include-patterns=com.google.maps.GeoApiContext$Builder
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,43 @@
*/
package org.apache.camel.quarkus.component.geocoder.it;

import com.github.tomakehurst.wiremock.WireMockServer;
import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.common.http.TestHTTPEndpoint;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import org.apache.camel.quarkus.test.wiremock.MockServer;
import org.junit.jupiter.api.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.request;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.hamcrest.Matchers.hasKey;

@QuarkusTest
@TestHTTPEndpoint(GeocoderGoogleResource.class)
@QuarkusTestResource(GeocoderTestResource.class)
class GeocoderGoogleTest {

@MockServer
WireMockServer server;

@Test
public void loadCurrentLocation() {
// disable test if no API KEY
// We need to manually stub this API call because it invokes multiple API targets:
// - googleapis.com
// - maps.googleapis.com
if (server != null) {
server.stubFor(request("POST", urlPathEqualTo("/geolocation/v1/geolocate"))
.withQueryParam("key", matching(".*"))
.withRequestBody(equalToJson("{\"considerIp\": true}"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\"location\":{\"lat\":24.7768404,\"lng\":-76.2849047},\"accuracy\":8252}")));
}

RestAssured.get()
.then()
.statusCode(200)
Expand Down