use of org.mockserver.mock.action.ExpectationResponseCallback in project notifications-backend by RedHatInsights.
the class EmailTest method testEmailSubscriptionInstantWrongPayload.
@Test
@Disabled
void testEmailSubscriptionInstantWrongPayload() {
mockGetUsers(8);
final String tenant = "instant-email-tenant-wrong-payload";
final String[] usernames = { "username-1", "username-2", "username-4" };
String bundle = "rhel";
String application = "policies";
for (String username : usernames) {
subscribe(tenant, username, bundle, application);
}
final List<String> bodyRequests = new ArrayList<>();
ExpectationResponseCallback verifyEmptyRequest = req -> {
assertEquals(BOP_TOKEN, req.getHeader(EmailSender.BOP_APITOKEN_HEADER).get(0));
assertEquals(BOP_CLIENT_ID, req.getHeader(EmailSender.BOP_CLIENT_ID_HEADER).get(0));
assertEquals(BOP_ENV, req.getHeader(EmailSender.BOP_ENV_HEADER).get(0));
bodyRequests.add(req.getBodyAsString());
return response().withStatusCode(200);
};
HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
Action emailActionMessage = new Action();
emailActionMessage.setBundle(bundle);
emailActionMessage.setApplication(application);
emailActionMessage.setTimestamp(LocalDateTime.of(2020, 10, 3, 15, 22, 13, 25));
emailActionMessage.setEventType(TestHelpers.eventType);
emailActionMessage.setRecipients(List.of());
emailActionMessage.setContext(new Context.ContextBuilder().withAdditionalProperty("inventory_id-wrong", "host-01").withAdditionalProperty("system_check_in-wrong", "2020-08-03T15:22:42.199046").withAdditionalProperty("display_name-wrong", "My test machine").withAdditionalProperty("tags-what?", List.of()).build());
emailActionMessage.setEvents(List.of(new com.redhat.cloud.notifications.ingress.Event.EventBuilder().withMetadata(new Metadata.MetadataBuilder().build()).withPayload(new Payload.PayloadBuilder().withAdditionalProperty("foo", "bar").build()).build()));
emailActionMessage.setAccountId(tenant);
Event event = new Event();
event.setAction(emailActionMessage);
EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
Endpoint ep = new Endpoint();
ep.setType(EndpointType.EMAIL_SUBSCRIPTION);
ep.setName("positive feeling");
ep.setDescription("needle in the haystack");
ep.setEnabled(true);
ep.setProperties(properties);
try {
List<NotificationHistory> historyEntries = statelessSessionFactory.withSession(statelessSession -> {
return emailProcessor.process(event, List.of(ep));
});
// The processor returns a null history value but Multi does not support null values so the resulting Multi is empty.
assertTrue(historyEntries.isEmpty());
// No email, invalid payload
assertEquals(0, bodyRequests.size());
} catch (Exception e) {
e.printStackTrace();
fail(e);
} finally {
// Remove expectations
MockServerLifecycleManager.getClient().clear(postReq);
}
clearSubscriptions();
}
use of org.mockserver.mock.action.ExpectationResponseCallback in project notifications-backend by RedHatInsights.
the class EmailTest method testEmailSubscriptionInstant.
@Test
@Disabled
void testEmailSubscriptionInstant() {
mockGetUsers(8);
final String tenant = "instant-email-tenant";
final String[] usernames = { "username-1", "username-2", "username-4" };
String bundle = "rhel";
String application = "policies";
for (String username : usernames) {
subscribe(tenant, username, bundle, application);
}
final List<String> bodyRequests = new ArrayList<>();
ExpectationResponseCallback verifyEmptyRequest = req -> {
assertEquals(BOP_TOKEN, req.getHeader(EmailSender.BOP_APITOKEN_HEADER).get(0));
assertEquals(BOP_CLIENT_ID, req.getHeader(EmailSender.BOP_CLIENT_ID_HEADER).get(0));
assertEquals(BOP_ENV, req.getHeader(EmailSender.BOP_ENV_HEADER).get(0));
bodyRequests.add(req.getBodyAsString());
return response().withStatusCode(200);
};
HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
Action emailActionMessage = TestHelpers.createPoliciesAction(tenant, bundle, application, "My test machine");
Event event = new Event();
event.setAction(emailActionMessage);
EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
Endpoint ep = new Endpoint();
ep.setType(EndpointType.EMAIL_SUBSCRIPTION);
ep.setName("positive feeling");
ep.setDescription("needle in the haystack");
ep.setEnabled(true);
ep.setProperties(properties);
try {
List<NotificationHistory> historyEntries = statelessSessionFactory.withSession(statelessSession -> {
return emailProcessor.process(event, List.of(ep));
});
NotificationHistory history = historyEntries.get(0);
assertTrue(history.isInvocationResult());
assertEquals(3, bodyRequests.size());
List<JsonObject> emailRequests = emailRequestIsOK(bodyRequests, usernames);
for (int i = 0; i < usernames.length; ++i) {
JsonObject body = emailRequests.get(i);
JsonArray emails = body.getJsonArray("emails");
assertNotNull(emails);
assertEquals(1, emails.size());
JsonObject firstEmail = emails.getJsonObject(0);
JsonArray recipients = firstEmail.getJsonArray("recipients");
assertEquals(1, recipients.size());
assertEquals(usernames[i], recipients.getString(0));
JsonArray bccList = firstEmail.getJsonArray("bccList");
assertEquals(0, bccList.size());
String bodyRequest = body.toString();
assertTrue(bodyRequest.contains(TestHelpers.policyId1), "Body should contain policy id" + TestHelpers.policyId1);
assertTrue(bodyRequest.contains(TestHelpers.policyName1), "Body should contain policy name" + TestHelpers.policyName1);
assertTrue(bodyRequest.contains(TestHelpers.policyId2), "Body should contain policy id" + TestHelpers.policyId2);
assertTrue(bodyRequest.contains(TestHelpers.policyName2), "Body should contain policy name" + TestHelpers.policyName2);
// Display name
assertTrue(bodyRequest.contains("My test machine"), "Body should contain the display_name");
// Formatted date
assertTrue(bodyRequest.contains("03 Aug 2020 15:22 UTC"));
}
} catch (Exception e) {
e.printStackTrace();
fail(e);
} finally {
// Remove expectations
MockServerLifecycleManager.getClient().clear(postReq);
}
clearSubscriptions();
}
use of org.mockserver.mock.action.ExpectationResponseCallback in project notifications-backend by RedHatInsights.
the class WebhookTest method testRetry.
private void testRetry(boolean shouldSucceedEventually) {
String url = getMockServerUrl() + "/foobar";
AtomicInteger callsCounter = new AtomicInteger();
ExpectationResponseCallback expectationResponseCallback = request -> {
if (callsCounter.incrementAndGet() == MAX_RETRY_ATTEMPTS && shouldSucceedEventually) {
return response().withStatusCode(200);
} else {
return response().withStatusCode(500);
}
};
HttpRequest mockServerRequest = getMockHttpRequest(expectationResponseCallback);
try {
Action action = buildWebhookAction();
Event event = new Event();
event.setAction(action);
Endpoint ep = buildWebhookEndpoint(url);
List<NotificationHistory> process = webhookTypeProcessor.process(event, List.of(ep));
NotificationHistory history = process.get(0);
assertEquals(shouldSucceedEventually, history.isInvocationResult());
assertEquals(MAX_RETRY_ATTEMPTS, callsCounter.get());
} finally {
// Remove expectations
MockServerLifecycleManager.getClient().clear(mockServerRequest);
}
}
use of org.mockserver.mock.action.ExpectationResponseCallback in project conquery by bakdata.
the class OIDCMockServer method init.
public void init(Consumer<ClientAndServer> testMappings) {
// Mock well-known discovery endpoint (this is actually the output of keycloak)
OIDC_SERVER.when(request().withMethod("GET").withPath(String.format("/realms/%s/.well-known/uma2-configuration", REALM_NAME))).respond(response().withBody(JsonBody.json(new Object() {
@Getter
final String issuer = MOCK_SERVER_URL + "/realms/EVA";
@Getter
final String authorization_endpoint = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/protocol/openid-connect/auth";
@Getter
final String token_endpoint = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/protocol/openid-connect/token";
@Getter
final String introspection_endpoint = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/protocol/openid-connect/token/introspect";
@Getter
final String end_session_endpoint = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/protocol/openid-connect/logout";
@Getter
final String jwks_uri = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/protocol/openid-connect/certs";
@Getter
final String[] grant_types_supported = { "authorization_code", "implicit", "refresh_token", "password", "client_credentials" };
@Getter
final String[] response_types_supported = { "code", "none", "id_token", "token", "id_token token", "code id_token", "code token", "code id_token token" };
@Getter
final String[] response_modes_supported = { "query", "fragment", "form_post" };
@Getter
final String registration_endpoint = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/clients-registrations/openid-connect";
@Getter
final String[] token_endpoint_auth_methods_supported = { "private_key_jwt", "client_secret_basic", "client_secret_post", "tls_client_auth", "client_secret_jwt" };
@Getter
final String[] token_endpoint_auth_signing_alg_values_supported = { "PS384", "ES384", "RS384", "HS256", "HS512", "ES256", "RS256", "HS384", "ES512", "PS256", "PS512", "RS512" };
@Getter
final String[] scopes_supported = { "openid", "address", "email", "microprofile-jwt", "offline_access", "phone", "profile", "roles", "web-origins" };
@Getter
final String resource_registration_endpoint = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/authz/protection/resource_set";
@Getter
final String permission_endpoint = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/authz/protection/permission";
@Getter
final String policy_endpoint = MOCK_SERVER_URL + "/realms/" + REALM_NAME + "/authz/protection/uma-policy";
})));
// Register test provided mappings
testMappings.accept(OIDC_SERVER);
// At last (so it has the lowest priority): initialize a trap for debugging, that captures all unmapped requests
OIDC_SERVER.when(request()).respond(new ExpectationResponseCallback() {
@Override
public HttpResponse handle(HttpRequest httpRequest) throws Exception {
log.error("{} on {}\n\t Headers: {}n\tBody {}", httpRequest.getMethod(), httpRequest.getPath(), httpRequest.getHeaderList(), httpRequest.getBodyAsString());
fail("Trapped because request did not match. See log.");
return null;
}
});
}
use of org.mockserver.mock.action.ExpectationResponseCallback in project notifications-backend by RedHatInsights.
the class WebhookTest method testWebhook.
@Test
void testWebhook() {
String url = getMockServerUrl() + "/foobar";
final List<String> bodyRequests = new ArrayList<>();
ExpectationResponseCallback verifyEmptyRequest = req -> {
bodyRequests.add(req.getBodyAsString());
return response().withStatusCode(200);
};
HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
Action webhookActionMessage = buildWebhookAction();
Event event = new Event();
event.setAction(webhookActionMessage);
Endpoint ep = buildWebhookEndpoint(url);
try {
List<NotificationHistory> process = webhookTypeProcessor.process(event, List.of(ep));
NotificationHistory history = process.get(0);
assertTrue(history.isInvocationResult());
} catch (Exception e) {
e.printStackTrace();
fail(e);
} finally {
// Remove expectations
MockServerLifecycleManager.getClient().clear(postReq);
}
assertEquals(1, bodyRequests.size());
JsonObject webhookInput = new JsonObject(bodyRequests.get(0));
assertEquals("mybundle", webhookInput.getString("bundle"));
assertEquals("WebhookTest", webhookInput.getString("application"));
assertEquals("testWebhook", webhookInput.getString("event_type"));
assertEquals("tenant", webhookInput.getString("account_id"));
JsonObject webhookInputContext = webhookInput.getJsonObject("context");
assertEquals("more", webhookInputContext.getString("free"));
assertEquals(1, webhookInputContext.getInteger("format"));
assertEquals("stuff", webhookInputContext.getString("here"));
JsonArray webhookInputEvents = webhookInput.getJsonArray("events");
assertEquals(2, webhookInputEvents.size());
JsonObject webhookInputPayload1 = webhookInputEvents.getJsonObject(0).getJsonObject("payload");
assertEquals("thing", webhookInputPayload1.getString("any"));
assertEquals(1, webhookInputPayload1.getInteger("we"));
assertEquals("here", webhookInputPayload1.getString("want"));
}
Aggregations