com.github.tomakehurst.wiremock.stubbing.StubMapping Java Examples

The following examples show how to use com.github.tomakehurst.wiremock.stubbing.StubMapping. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecondTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeRejectedDueToAbnormalLoanAmount() throws Exception {
	server.addStubMapping(StubMapping.buildFrom(StreamUtils.copyToString(
			markClientAsNotFraud.getInputStream(), Charset.forName("UTF-8"))));
	// given:
	LoanApplication loanApplication = new LoanApplication(new Client("1234567890"),
			123.123);

	// when:
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/vnd.fraud.v1+json");

	ResponseEntity<FraudServiceResponse> response = new RestTemplate().exchange(
			"http://localhost:" + server.port() + "/fraudcheck", HttpMethod.PUT,
			new HttpEntity<>(new FraudServiceRequest(loanApplication), httpHeaders),
			FraudServiceResponse.class);
	// then:
	assertThat(response.getBody().getFraudCheckStatus())
			.isEqualTo(FraudCheckStatus.OK);
}
 
Example #2
Source File: WireMockHttpServerStub.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private void registerStubs(Collection<File> sortedMappings, WireMock wireMock) {
	List<StubMapping> stubMappings = new ArrayList<>();
	for (File mappingDescriptor : sortedMappings) {
		try {
			stubMappings.add(registerDescriptor(wireMock, mappingDescriptor));
			if (log.isDebugEnabled()) {
				log.debug(
						"Registered stub mappings from [" + mappingDescriptor + "]");
			}
		}
		catch (Exception e) {
			if (log.isDebugEnabled()) {
				log.debug("Failed to register the stub mapping [" + mappingDescriptor
						+ "]", e);
			}
		}
	}
	PortAndMappings portAndMappings = SERVERS.get(this);
	SERVERS.put(this, new PortAndMappings(portAndMappings.random,
			portAndMappings.port, stubMappings));
}
 
Example #3
Source File: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private void extractMatchers(Operation operation) {
	this.stubMapping = (StubMapping) operation.getAttributes()
			.get("contract.stubMapping");
	if (this.stubMapping != null) {
		return;
	}
	@SuppressWarnings("unchecked")
	Set<String> jsonPaths = (Set<String>) operation.getAttributes()
			.get("contract.jsonPaths");
	this.jsonPaths = jsonPaths;
	this.contentType = (MediaType) operation.getAttributes()
			.get("contract.contentType");
	if (this.contentType == null) {
		this.hasJsonBodyRequestToMatch = hasJsonContentType(operation);
		this.hasXmlBodyRequestToMatch = hasXmlContentType(operation);
	}
}
 
Example #4
Source File: BasicMappingBuilder.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Override
public StubMapping build() {
	if (this.scenarioName == null && (this.requiredScenarioState != null
			|| this.newScenarioState != null)) {
		throw new IllegalStateException(
				"Scenario name must be specified to require or set a new scenario state");
	}
	RequestPattern requestPattern = this.requestPatternBuilder.build();
	ResponseDefinition response = (this.responseDefBuilder != null
			? this.responseDefBuilder : aResponse()).build();
	StubMapping mapping = new StubMapping(requestPattern, response);
	mapping.setPriority(this.priority);
	mapping.setScenarioName(this.scenarioName);
	mapping.setRequiredScenarioState(this.requiredScenarioState);
	mapping.setNewScenarioState(this.newScenarioState);
	mapping.setUuid(this.id);
	mapping.setName(this.name);
	mapping.setPersistent(this.isPersistent);
	mapping.setPostServeActions(
			this.postServeActions.isEmpty() ? null : this.postServeActions);
	mapping.setMetadata(this.metadata);
	return mapping;
}
 
Example #5
Source File: WireMockEphemeral.java    From ephemerals with MIT License 6 votes vote down vote up
@Override
protected URL createObject(DeploymentEndpoints endpoints) {
    for(DeploymentEndpoints.Endpoint endpoint : endpoints.list()) {
        if(endpoint.getName().equals("wiremock-server")) {
            String host = endpoint.getHost();
            int port = endpoint.getPort();
            WireMock wireMock = new WireMock(host,port);
            wireMock.register(StubMapping.buildFrom(stubMapping));
            try {
                return new URL(String.format("http://%s:%s", host, port));
            } catch (MalformedURLException e) {
                return null;
            }
        }
    }
    return null;
}
 
Example #6
Source File: WireMockSnippetTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void should_use_equal_to_json_pattern_for_body_when_request_content_type_is_json_when_generating_stub()
		throws Exception {
	this.operation = operation(requestPostWithJsonContentType(), response(),
			this.context);
	WireMockSnippet snippet = new WireMockSnippet();

	snippet.document(this.operation);

	File stub = new File(this.outputFolder, "stubs/foo.json");
	assertThat(stub).exists();
	StubMapping stubMapping = WireMockStubMapping
			.buildFrom(new String(Files.readAllBytes(stub.toPath())));
	assertThat(stubMapping.getRequest().getBodyPatterns().get(0))
			.isInstanceOf(EqualToJsonPattern.class);
	assertThat(stubMapping.getRequest().getBodyPatterns().get(0).getValue())
			.isEqualTo("{\"name\": \"12\"}");
}
 
Example #7
Source File: WireMockSnippetTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void should_use_equal_to_xml_pattern_for_body_when_request_content_type_is_xml_when_generating_stub()
		throws Exception {
	this.operation = operation(requestPostWithXmlContentType(), response(),
			this.context);
	WireMockSnippet snippet = new WireMockSnippet();

	snippet.document(this.operation);

	File stub = new File(this.outputFolder, "stubs/foo.json");
	assertThat(stub).exists();
	StubMapping stubMapping = WireMockStubMapping
			.buildFrom(new String(Files.readAllBytes(stub.toPath())));
	assertThat(stubMapping.getRequest().getBodyPatterns().get(0))
			.isInstanceOf(EqualToXmlPattern.class);
	assertThat(stubMapping.getRequest().getBodyPatterns().get(0).getValue())
			.isEqualTo("<name>foo</name>");
}
 
Example #8
Source File: WiremockServerRestDocsApplicationTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void stubsRenderLinksWithPlaceholder() throws Exception {
	this.mockMvc.perform(MockMvcRequestBuilders.get("/link"))
			.andExpect(status().isOk())
			.andExpect(content().string(containsString("link:")))
			.andDo(document("link"));

	File file = new File("target/snippets/stubs", "link.json");
	BDDAssertions.then(file).exists();
	StubMapping stubMapping = StubMapping
			.buildFrom(new String(Files.readAllBytes(file.toPath())));
	String body = stubMapping.getResponse().getBody();
	BDDAssertions.then(body)
			.contains("http://localhost:{{request.requestLine.port}}/link");
	BDDAssertions.then(stubMapping.getResponse().getTransformers())
			.contains("response-template");
}
 
Example #9
Source File: WiremockServerRestDocsApplicationTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void queryParamsAreFetchedFromStubs() throws Exception {
	this.mockMvc.perform(MockMvcRequestBuilders.get(
			"/project_metadata/spring-framework?callback=a_function_name&foo=foo&bar=bar"))
			.andExpect(status().isOk())
			.andExpect(content().string("spring-framework a_function_name foo bar"))
			.andDo(document("query"));

	File file = new File("target/snippets/stubs", "query.json");
	BDDAssertions.then(file).exists();
	StubMapping stubMapping = StubMapping
			.buildFrom(new String(Files.readAllBytes(file.toPath())));
	Map<String, MultiValuePattern> queryParameters = stubMapping.getRequest()
			.getQueryParameters();
	BDDAssertions.then(queryParameters.get("callback").getValuePattern())
			.isEqualTo(WireMock.equalTo("a_function_name"));
	BDDAssertions.then(queryParameters.get("foo").getValuePattern())
			.isEqualTo(WireMock.equalTo("foo"));
	BDDAssertions.then(queryParameters.get("bar").getValuePattern())
			.isEqualTo(WireMock.equalTo("bar"));
}
 
Example #10
Source File: FirstTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeRejectedDueToAbnormalLoanAmount() throws Exception {
	server.addStubMapping(StubMapping.buildFrom(StreamUtils.copyToString(
			markClientAsFraud.getInputStream(), Charset.forName("UTF-8"))));
	// given:
	LoanApplication loanApplication = new LoanApplication(new Client("1234567890"),
			99999);

	// when:
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/vnd.fraud.v1+json");

	ResponseEntity<FraudServiceResponse> response = new RestTemplate().exchange(
			"http://localhost:" + server.port() + "/fraudcheck", HttpMethod.PUT,
			new HttpEntity<>(new FraudServiceRequest(loanApplication), httpHeaders),
			FraudServiceResponse.class);
	// then:
	assertThat(response.getBody().getFraudCheckStatus())
			.isEqualTo(FraudCheckStatus.FRAUD);
	assertThat(response.getBody().getRejectionReason()).isEqualTo("Amount too high");
}
 
Example #11
Source File: IronTestUtils.java    From irontest with Apache License 2.0 6 votes vote down vote up
public static void substituteRequestBodyMainPatternValue(List<HTTPStubMapping> httpStubMappings) {
    for (HTTPStubMapping httpStubMapping: httpStubMappings) {
        StubMapping spec = httpStubMapping.getSpec();
        List<ContentPattern<?>> requestBodyPatterns = spec.getRequest().getBodyPatterns();
        if (requestBodyPatterns != null) {
            for (int i = 0; i < requestBodyPatterns.size(); i++) {
                ContentPattern requestBodyPattern = requestBodyPatterns.get(i);
                if (requestBodyPattern instanceof EqualToXmlPattern) {
                    EqualToXmlPattern equalToXmlPattern = (EqualToXmlPattern) requestBodyPattern;
                    requestBodyPatterns.set(i, new EqualToXmlPattern(
                            httpStubMapping.getRequestBodyMainPatternValue(),
                            equalToXmlPattern.isEnablePlaceholders(),
                            equalToXmlPattern.getPlaceholderOpeningDelimiterRegex(),
                            equalToXmlPattern.getPlaceholderClosingDelimiterRegex()));
                    break;
                } else if (requestBodyPattern instanceof EqualToJsonPattern) {
                    EqualToJsonPattern equalToJsonPattern = (EqualToJsonPattern) requestBodyPattern;
                    requestBodyPatterns.set(i, new EqualToJsonPattern(
                            httpStubMapping.getRequestBodyMainPatternValue(),
                            equalToJsonPattern.isIgnoreArrayOrder(), equalToJsonPattern.isIgnoreExtraElements()));
                    break;
                }
            }
        }
    }
}
 
Example #12
Source File: HTTPStubsHitInOrderAssertionVerifier.java    From irontest with Apache License 2.0 6 votes vote down vote up
@Override
public AssertionVerificationResult verify(Object... inputs) {
    HTTPStubsHitInOrderAssertionVerificationResult result = new HTTPStubsHitInOrderAssertionVerificationResult();
    HTTPStubsHitInOrderAssertionProperties otherProperties =
            (HTTPStubsHitInOrderAssertionProperties) getAssertion().getOtherProperties();

    Map<Date, Short> hitMap = new TreeMap<>();
    List<ServeEvent> allServeEvents = (List<ServeEvent>) inputs[0];
    for (ServeEvent serveEvent: allServeEvents) {
        if (serveEvent.getWasMatched()) {
            StubMapping stubMapping = serveEvent.getStubMapping();
            hitMap.put(serveEvent.getRequest().getLoggedDate(),
                    (Short) stubMapping.getMetadata().get(WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_NUMBER));
        }
    }

    List<Short> actualHitOrder = new ArrayList(hitMap.values());
    result.setResult(otherProperties.getExpectedHitOrder().equals(actualHitOrder) ? TestResult.PASSED : TestResult.FAILED);
    result.setActualHitOrder(actualHitOrder);

    return result;
}
 
Example #13
Source File: HTTPStubsSetupTeststepRunner.java    From irontest with Apache License 2.0 6 votes vote down vote up
@Override
public BasicTeststepRun run() {
    WireMockServer wireMockServer = getTestcaseRunContext().getWireMockServer();

    //  reset mock server
    wireMockServer.resetAll();

    //  load stub mappings into mock server
    Map<Short, UUID> httpStubMappingInstanceIds = getTestcaseRunContext().getHttpStubMappingInstanceIds();
    HTTPStubsSetupTeststepProperties otherProperties = (HTTPStubsSetupTeststepProperties) getTeststep().getOtherProperties();
    wireMockServer.loadMappingsUsing(stubMappings -> {
        for (HTTPStubMapping stubMapping: otherProperties.getHttpStubMappings()) {
            StubMapping stubInstance = IronTestUtils.createStubInstance(stubMapping.getId(), stubMapping.getNumber(), stubMapping.getSpec());
            stubMappings.addMapping(stubInstance);
            httpStubMappingInstanceIds.put(stubMapping.getNumber(), stubInstance.getId());
        }
    });

    return new BasicTeststepRun();
}
 
Example #14
Source File: RequestVerifierFilter.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@Override
public Response filter(FilterableRequestSpecification requestSpec,
		FilterableResponseSpecification responseSpec, FilterContext context) {
	Map<String, Object> configuration = getConfiguration(requestSpec, context);
	configuration.put("contract.jsonPaths", this.jsonPaths.keySet());
	Response response = context.next(requestSpec, responseSpec);
	if (requestSpec.getBody() != null && !this.jsonPaths.isEmpty()) {
		String actual = new String((byte[]) requestSpec.getBody());
		for (JsonPath jsonPath : this.jsonPaths.values()) {
			new JsonPathValue(jsonPath, actual).assertHasValue(Object.class,
					"an object");
		}
	}
	if (this.builder != null) {
		this.builder.willReturn(getResponseDefinition(response));
		StubMapping stubMapping = this.builder.build();
		MatchResult match = stubMapping.getRequest()
				.match(new WireMockRestAssuredRequestAdapter(requestSpec));
		assertThat(match.isExactMatch()).as("wiremock did not match request")
				.isTrue();
		configuration.put("contract.stubMapping", stubMapping);
	}
	return response;
}
 
Example #15
Source File: LoanApplicationServiceTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeRejectedDueToAbnormalLoanAmount() throws Exception {
	this.server.addStubMapping(StubMapping.buildFrom(StreamUtils.copyToString(
			this.markClientAsFraud.getInputStream(), Charset.forName("UTF-8"))));
	// given:
	LoanApplication application = new LoanApplication(new Client("1234567890"),
			99999);
	// when:
	LoanApplicationResult loanApplication = this.service.loanApplication(application);
	// then:
	assertThat(loanApplication.getLoanApplicationStatus())
			.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
	assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
}
 
Example #16
Source File: LoanApplicationServiceTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSuccessfullyApplyForLoan() throws Exception {
	this.server.addStubMapping(StubMapping.buildFrom(StreamUtils.copyToString(
			this.markClientAsNotFraud.getInputStream(), Charset.forName("UTF-8"))));
	// given:
	LoanApplication application = new LoanApplication(new Client("1234567890"),
			123.123);
	// when:
	LoanApplicationResult loanApplication = this.service.loanApplication(application);
	// then:
	assertThat(loanApplication.getLoanApplicationStatus())
			.isEqualTo(LoanApplicationStatus.LOAN_APPLIED);
	assertThat(loanApplication.getRejectionReason()).isNull();
}
 
Example #17
Source File: XmlServiceTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSuccessfullyReturnFullResponse() throws Exception {
	server.addStubMapping(StubMapping.buildFrom(StreamUtils
			.copyToString(full.getInputStream(), Charset.forName("UTF-8"))));

	ResponseEntity<XmlResponseBody> responseEntity = new RestTemplate()
			.exchange(RequestEntity
					.post(URI.create(
							"http://localhost:" + server.port() + "/xmlfraud"))
					.contentType(MediaType.valueOf("application/xml;charset=UTF-8"))
					.body(new XmlRequestBody("foo")), XmlResponseBody.class);

	BDDAssertions.then(responseEntity.getStatusCodeValue()).isEqualTo(200);
	BDDAssertions.then(responseEntity.getBody().status).isEqualTo("FULL");
}
 
Example #18
Source File: WatchHttpTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotModified() throws Exception {
    BlockingQueue<String> queue = new LinkedBlockingQueue<>();
    List<ConfigurationListener> listeners = new ArrayList<>();
    listeners.add(new TestConfigurationListener(queue, "log4j-test2.xml"));
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    Calendar now = Calendar.getInstance(timeZone);
    Calendar previous = now;
    previous.add(Calendar.MINUTE, -5);
    Configuration configuration = new DefaultConfiguration();
    Assume.assumeTrue(!IS_WINDOWS || Boolean.getBoolean(FORCE_RUN_KEY));
    URL url = new URL("http://localhost:" + wireMockRule.port() + "/log4j-test2.xml");
    StubMapping stubMapping = stubFor(get(urlPathEqualTo("/log4j-test2.xml"))
        .willReturn(aResponse()
            .withBodyFile(file)
            .withStatus(304)
            .withHeader("Last-Modified", formatter.format(now) + " GMT")
            .withHeader("Content-Type", XML)));
    final ConfigurationScheduler scheduler = new ConfigurationScheduler();
    scheduler.incrementScheduledItems();
    final WatchManager watchManager = new WatchManager(scheduler);
    watchManager.setIntervalSeconds(1);
    scheduler.start();
    watchManager.start();
    try {
        watchManager.watch(new Source(url.toURI(), previous.getTimeInMillis()), new HttpWatcher(configuration, null,
            listeners, previous.getTimeInMillis()));
        final String str = queue.poll(2, TimeUnit.SECONDS);
        assertNull("File changed.", str);
    } finally {
        removeStub(stubMapping);
        watchManager.stop();
        scheduler.stop();
    }
}
 
Example #19
Source File: XmlServiceTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSuccessfullyReturnEmptyResponse() throws Exception {
	server.addStubMapping(StubMapping.buildFrom(StreamUtils
			.copyToString(empty.getInputStream(), Charset.forName("UTF-8"))));

	ResponseEntity<XmlResponseBody> responseEntity = new RestTemplate()
			.exchange(RequestEntity
					.post(URI.create(
							"http://localhost:" + server.port() + "/xmlfraud"))
					.contentType(MediaType.valueOf("application/xml;charset=UTF-8"))
					.body(new XmlRequestBody("")), XmlResponseBody.class);

	BDDAssertions.then(responseEntity.getStatusCodeValue()).isEqualTo(200);
	BDDAssertions.then(responseEntity.getBody().status).isEqualTo("EMPTY");
}
 
Example #20
Source File: LoanApplicationServiceTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeRejectedDueToAbnormalLoanAmount() throws Exception {
	server.addStubMapping(StubMapping.buildFrom(StreamUtils.copyToString(
			markClientAsFraud.getInputStream(), Charset.forName("UTF-8"))));
	// given:
	LoanApplication application = new LoanApplication(new Client("1234567890"),
			99999);
	// when:
	LoanApplicationResult loanApplication = service.loanApplication(application);
	// then:
	assertThat(loanApplication.getLoanApplicationStatus())
			.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
	assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
}
 
Example #21
Source File: IronTestUtils.java    From irontest with Apache License 2.0 5 votes vote down vote up
public static void addMixInsForWireMock(ObjectMapper objectMapper) {
    objectMapper.addMixIn(StubMapping.class, StubMappingMixIn.class);
    objectMapper.addMixIn(RequestPattern.class, RequestPatternMixIn.class);
    objectMapper.addMixIn(StringValuePattern.class, StringValuePatternMixIn.class);
    objectMapper.addMixIn(ResponseDefinition.class, ResponseDefinitionMixIn.class);
    objectMapper.addMixIn(ContentPattern.class, ContentPatternMixIn.class);
    objectMapper.addMixIn(LoggedResponse.class, LoggedResponseMixIn.class);
    objectMapper.addMixIn(ServeEvent.class, ServeEventMixIn.class);
    objectMapper.addMixIn(LoggedRequest.class, LoggedRequestMixIn.class);
}
 
Example #22
Source File: IronTestUtils.java    From irontest with Apache License 2.0 5 votes vote down vote up
/**
 * Create (clone) a new instance out of the stub spec, with UUID generated for the instance.
 * The instance also has the ironTestId as metadata.
 * The spec is not changed.
 * @param spec
 * @return
 */
public static StubMapping createStubInstance(long ironTestId, short ironTestNumber, StubMapping spec) {
    StubMapping stubInstance = StubMapping.buildFrom(StubMapping.buildJsonStringFor(spec));
    stubInstance.setMetadata(metadata()
            .attr(WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_ID, ironTestId)
            .attr(WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_NUMBER, ironTestNumber)
            .build());
    stubInstance.setDirty(false);
    return stubInstance;
}
 
Example #23
Source File: HTTPStubMapping.java    From irontest with Apache License 2.0 5 votes vote down vote up
public HTTPStubMapping(long id, long testcaseId, short number, StubMapping spec, String requestBodyMainPatternValue, short expectedHitCount) {
    this.id = id;
    this.testcaseId = testcaseId;
    this.number = number;
    setSpec(spec);
    this.requestBodyMainPatternValue = requestBodyMainPatternValue;
    this.expectedHitCount = expectedHitCount;
}
 
Example #24
Source File: HTTPStubMappingMapper.java    From irontest with Apache License 2.0 5 votes vote down vote up
@Override
public HTTPStubMapping map(ResultSet rs, StatementContext ctx) throws SQLException {
    String specJSON = rs.getString("spec_json");
    StubMapping spec = StubMapping.buildFrom(specJSON);
    HTTPStubMapping httpStubMapping = new HTTPStubMapping(
            rs.getLong("id"), rs.getLong("testcase_id"),
            rs.getShort("number"), spec, rs.getString("request_body_main_pattern_value"),
            rs.getShort("expected_hit_count"));

    return httpStubMapping;
}
 
Example #25
Source File: WatchHttpTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWatchManager() throws Exception {
    BlockingQueue<String> queue = new LinkedBlockingQueue<>();
    List<ConfigurationListener> listeners = new ArrayList<>();
    listeners.add(new TestConfigurationListener(queue, "log4j-test1.xml"));
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    Calendar now = Calendar.getInstance(timeZone);
    Calendar previous = now;
    previous.add(Calendar.MINUTE, -5);
    Configuration configuration = new DefaultConfiguration();
    Assume.assumeTrue(!IS_WINDOWS || Boolean.getBoolean(FORCE_RUN_KEY));
    URL url = new URL("http://localhost:" + wireMockRule.port() + "/log4j-test1.xml");
    StubMapping stubMapping = stubFor(get(urlPathEqualTo("/log4j-test1.xml"))
        .willReturn(aResponse()
        .withBodyFile(file)
        .withStatus(200)
        .withHeader("Last-Modified", formatter.format(previous) + " GMT")
        .withHeader("Content-Type", XML)));
    final ConfigurationScheduler scheduler = new ConfigurationScheduler();
    scheduler.incrementScheduledItems();
    final WatchManager watchManager = new WatchManager(scheduler);
    watchManager.setIntervalSeconds(1);
    scheduler.start();
    watchManager.start();
    try {
        watchManager.watch(new Source(url.toURI(), previous.getTimeInMillis()), new HttpWatcher(configuration, null,
            listeners, previous.getTimeInMillis()));
        final String str = queue.poll(2, TimeUnit.SECONDS);
        assertNotNull("File change not detected", str);
    } finally {
        removeStub(stubMapping);
        watchManager.stop();
        scheduler.stop();
    }
}
 
Example #26
Source File: MockServerResource.java    From irontest with Apache License 2.0 5 votes vote down vote up
@GET @Path("stubInstances/{stubInstanceId}")
public StubMapping findStubInstanceById(@PathParam("stubInstanceId") UUID stubInstanceId) {
    List<StubMapping> stubInstances = wireMockServer.getStubMappings();
    for (StubMapping stubInstance: stubInstances) {
        if (stubInstance.getId().equals(stubInstanceId)) {
            return stubInstance;
        }
    }
    return null;
}
 
Example #27
Source File: LoanApplicationServiceTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSuccessfullyApplyForLoan() throws Exception {
	server.addStubMapping(StubMapping.buildFrom(StreamUtils.copyToString(
			markClientAsNotFraud.getInputStream(), Charset.forName("UTF-8"))));
	// given:
	LoanApplication application = new LoanApplication(new Client("1234567890"),
			123.123);
	// when:
	LoanApplicationResult loanApplication = service.loanApplication(application);
	// then:
	assertThat(loanApplication.getLoanApplicationStatus())
			.isEqualTo(LoanApplicationStatus.LOAN_APPLIED);
	assertThat(loanApplication.getRejectionReason()).isNull();
}
 
Example #28
Source File: WireMockHttpServerStub.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
StubMapping getMapping(File file) {
	try (InputStream stream = Files.newInputStream(file.toPath())) {
		return StubMapping.buildFrom(
				StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
	}
	catch (IOException e) {
		throw new IllegalStateException("Cannot read file", e);
	}
}
 
Example #29
Source File: WireMockHttpServerStub.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public String registeredMappings() {
	Collection<String> mappings = new ArrayList<>();
	for (StubMapping stubMapping : this.wireMockServer.getStubMappings()) {
		mappings.add(stubMapping.toString());
	}
	return jsonArrayOfMappings(mappings);
}
 
Example #30
Source File: WiremockServerWebTestClientApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void stubsRenderLinksWithPlaceholder() throws Exception {
	this.client.get().uri("/link").exchange().expectBody(String.class)
			.value(containsString("link:")).consumeWith(document("link"));

	File file = new File("target/snippets/webtestclient/stubs", "link.json");
	BDDAssertions.then(file).exists();
	StubMapping stubMapping = StubMapping
			.buildFrom(new String(Files.readAllBytes(file.toPath())));
	String body = stubMapping.getResponse().getBody();
	BDDAssertions.then(body)
			.contains("http://localhost:{{request.requestLine.port}}/link");
	BDDAssertions.then(stubMapping.getResponse().getTransformers())
			.contains("response-template");
}