Search in sources :

Example 6 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory 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();
}
Also used : INSTANT(com.redhat.cloud.notifications.models.EmailSubscriptionType.INSTANT) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) HttpRequest(org.mockserver.model.HttpRequest) Endpoint(com.redhat.cloud.notifications.models.Endpoint) ITUserResponse(com.redhat.cloud.notifications.recipients.itservice.pojo.response.ITUserResponse) LocalDateTime(java.time.LocalDateTime) Disabled(org.junit.jupiter.api.Disabled) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) MockServerLifecycleManager(com.redhat.cloud.notifications.MockServerLifecycleManager) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) InjectSpy(io.quarkus.test.junit.mockito.InjectSpy) ITUserRequest(com.redhat.cloud.notifications.recipients.itservice.pojo.request.ITUserRequest) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Payload(com.redhat.cloud.notifications.ingress.Payload) Context(com.redhat.cloud.notifications.ingress.Context) InjectMock(io.quarkus.test.junit.mockito.InjectMock) RestClient(org.eclipse.microprofile.rest.client.inject.RestClient) Transactional(javax.transaction.Transactional) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) EntityManager(javax.persistence.EntityManager) Collectors(java.util.stream.Collectors) ITUserService(com.redhat.cloud.notifications.recipients.itservice.ITUserService) Test(org.junit.jupiter.api.Test) JsonArray(io.vertx.core.json.JsonArray) Mockito(org.mockito.Mockito) List(java.util.List) Authentication(com.redhat.cloud.notifications.recipients.itservice.pojo.response.Authentication) EndpointType(com.redhat.cloud.notifications.models.EndpointType) StatelessSessionFactory(com.redhat.cloud.notifications.db.StatelessSessionFactory) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AccountRelationship(com.redhat.cloud.notifications.recipients.itservice.pojo.response.AccountRelationship) TestHelpers(com.redhat.cloud.notifications.TestHelpers) Metadata(com.redhat.cloud.notifications.ingress.Metadata) Action(com.redhat.cloud.notifications.ingress.Action) Comparator(java.util.Comparator) HttpResponse.response(org.mockserver.model.HttpResponse.response) PersonalInformation(com.redhat.cloud.notifications.recipients.itservice.pojo.response.PersonalInformation) HttpRequest(org.mockserver.model.HttpRequest) Action(com.redhat.cloud.notifications.ingress.Action) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Endpoint(com.redhat.cloud.notifications.models.Endpoint) JsonArray(io.vertx.core.json.JsonArray) Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Event(com.redhat.cloud.notifications.models.Event) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Example 7 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory 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);
    }
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) HttpType(com.redhat.cloud.notifications.models.HttpType) HttpRequest(org.mockserver.model.HttpRequest) Endpoint(com.redhat.cloud.notifications.models.Endpoint) WebhookTypeProcessor(com.redhat.cloud.notifications.processors.webhooks.WebhookTypeProcessor) TestLifecycleManager(com.redhat.cloud.notifications.TestLifecycleManager) LocalDateTime(java.time.LocalDateTime) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) MockServerLifecycleManager(com.redhat.cloud.notifications.MockServerLifecycleManager) QuarkusTest(io.quarkus.test.junit.QuarkusTest) ArrayList(java.util.ArrayList) MockServerLifecycleManager.getMockServerUrl(com.redhat.cloud.notifications.MockServerLifecycleManager.getMockServerUrl) Inject(javax.inject.Inject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Event(com.redhat.cloud.notifications.models.Event) WebhookProperties(com.redhat.cloud.notifications.models.WebhookProperties) JsonObject(io.vertx.core.json.JsonObject) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Payload(com.redhat.cloud.notifications.ingress.Payload) Context(com.redhat.cloud.notifications.ingress.Context) QuarkusTestResource(io.quarkus.test.common.QuarkusTestResource) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) Test(org.junit.jupiter.api.Test) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) EndpointType(com.redhat.cloud.notifications.models.EndpointType) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Metadata(com.redhat.cloud.notifications.ingress.Metadata) Action(com.redhat.cloud.notifications.ingress.Action) HttpResponse.response(org.mockserver.model.HttpResponse.response) HttpRequest(org.mockserver.model.HttpRequest) Action(com.redhat.cloud.notifications.ingress.Action) Endpoint(com.redhat.cloud.notifications.models.Endpoint) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Event(com.redhat.cloud.notifications.models.Event)

Example 8 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class EventResourceTest method assertSameEvent.

private static void assertSameEvent(EventLogEntry eventLogEntry, Event event, NotificationHistory... historyEntries) {
    assertEquals(event.getId(), eventLogEntry.getId());
    // Jackson's serialization gets rid of nanoseconds so an equals between the LocalDateTime objects won't work.
    assertEquals(event.getCreated().toEpochSecond(UTC), eventLogEntry.getCreated().toEpochSecond(UTC));
    assertEquals(event.getBundleDisplayName(), eventLogEntry.getBundle());
    assertEquals(event.getApplicationDisplayName(), eventLogEntry.getApplication());
    assertEquals(event.getEventTypeDisplayName(), eventLogEntry.getEventType());
    if (historyEntries == null) {
        assertTrue(eventLogEntry.getActions().isEmpty());
    } else {
        assertEquals(historyEntries.length, eventLogEntry.getActions().size());
        for (EventLogEntryAction eventLogEntryAction : eventLogEntry.getActions()) {
            Optional<NotificationHistory> historyEntry = Arrays.stream(historyEntries).filter(entry -> entry.getId().equals(eventLogEntryAction.getId())).findAny();
            assertTrue(historyEntry.isPresent());
            assertEquals(historyEntry.get().getEndpointType(), eventLogEntryAction.getEndpointType());
            assertEquals(historyEntry.get().getEndpointSubType(), eventLogEntryAction.getEndpointSubType());
            assertEquals(historyEntry.get().isInvocationResult(), eventLogEntryAction.getInvocationResult());
        }
    }
}
Also used : Arrays(java.util.Arrays) ResourceHelpers(com.redhat.cloud.notifications.db.ResourceHelpers) Endpoint(com.redhat.cloud.notifications.models.Endpoint) TestLifecycleManager(com.redhat.cloud.notifications.TestLifecycleManager) FULL_ACCESS(com.redhat.cloud.notifications.MockServerConfig.RbacAccess.FULL_ACCESS) Header(io.restassured.http.Header) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) DEFAULT_ORG_ID(com.redhat.cloud.notifications.TestConstants.DEFAULT_ORG_ID) NO_ACCESS(com.redhat.cloud.notifications.MockServerConfig.RbacAccess.NO_ACCESS) RequestSpecification(io.restassured.specification.RequestSpecification) Map(java.util.Map) TypeRef(io.restassured.common.mapper.TypeRef) Event(com.redhat.cloud.notifications.models.Event) QuarkusTestResource(io.quarkus.test.common.QuarkusTestResource) Application(com.redhat.cloud.notifications.models.Application) PATH(com.redhat.cloud.notifications.routers.EventResource.PATH) JSON(io.restassured.http.ContentType.JSON) Transactional(javax.transaction.Transactional) Set(java.util.Set) EMAIL_SUBSCRIPTION(com.redhat.cloud.notifications.models.EndpointType.EMAIL_SUBSCRIPTION) UUID(java.util.UUID) DEFAULT_ACCOUNT_ID(com.redhat.cloud.notifications.TestConstants.DEFAULT_ACCOUNT_ID) Test(org.junit.jupiter.api.Test) NOTIFICATIONS_READ_ACCESS_ONLY(com.redhat.cloud.notifications.MockServerConfig.RbacAccess.NOTIFICATIONS_READ_ACCESS_ONLY) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) UTC(java.time.ZoneOffset.UTC) Optional(java.util.Optional) TestHelpers(com.redhat.cloud.notifications.TestHelpers) RestAssured.given(io.restassured.RestAssured.given) TRUE(java.lang.Boolean.TRUE) LocalDateTime(java.time.LocalDateTime) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) EndpointRepository(com.redhat.cloud.notifications.db.repositories.EndpointRepository) MockServerConfig(com.redhat.cloud.notifications.MockServerConfig) EventLogEntry(com.redhat.cloud.notifications.routers.models.EventLogEntry) QuarkusTest(io.quarkus.test.junit.QuarkusTest) WEBHOOK(com.redhat.cloud.notifications.models.EndpointType.WEBHOOK) Inject(javax.inject.Inject) NOTIFICATIONS_ACCESS_ONLY(com.redhat.cloud.notifications.MockServerConfig.RbacAccess.NOTIFICATIONS_ACCESS_ONLY) EventType(com.redhat.cloud.notifications.models.EventType) RbacAccess(com.redhat.cloud.notifications.MockServerConfig.RbacAccess) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DbIsolatedTest(com.redhat.cloud.notifications.db.DbIsolatedTest) FALSE(java.lang.Boolean.FALSE) Bundle(com.redhat.cloud.notifications.models.Bundle) EntityManager(javax.persistence.EntityManager) CAMEL(com.redhat.cloud.notifications.models.EndpointType.CAMEL) UUID.randomUUID(java.util.UUID.randomUUID) Page(com.redhat.cloud.notifications.routers.models.Page) EventLogEntryAction(com.redhat.cloud.notifications.routers.models.EventLogEntryAction) EventLogEntryAction(com.redhat.cloud.notifications.routers.models.EventLogEntryAction) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory)

Example 9 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class LifecycleITest method createNotificationHistory.

@Transactional
void createNotificationHistory(Event event, String endpointId, boolean invocationResult) {
    Endpoint endpoint = entityManager.createQuery("FROM Endpoint WHERE id = :id", Endpoint.class).setParameter("id", UUID.fromString(endpointId)).getSingleResult();
    NotificationHistory history = new NotificationHistory();
    history.setId(UUID.randomUUID());
    history.setEvent(event);
    history.setEndpoint(endpoint);
    history.setEndpointType(endpoint.getType());
    history.setInvocationTime(123L);
    history.setInvocationResult(invocationResult);
    if (!invocationResult) {
        history.setDetails(Map.of("code", 400, "url", "https://www.foo.com", "method", "GET"));
    }
    history.prePersist();
    entityManager.persist(history);
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Transactional(javax.transaction.Transactional)

Example 10 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class ResourceHelpers method createNotificationHistory.

public NotificationHistory createNotificationHistory(Event event, Endpoint endpoint, Boolean invocationResult) {
    NotificationHistory history = new NotificationHistory();
    history.setId(UUID.randomUUID());
    history.setInvocationTime(1L);
    history.setInvocationResult(invocationResult);
    history.setEvent(event);
    history.setEndpoint(endpoint);
    history.setEndpointType(endpoint.getType());
    history.setEndpointSubType(endpoint.getSubType());
    history.prePersist();
    entityManager.persist(history);
    return history;
}
Also used : NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory)

Aggregations

NotificationHistory (com.redhat.cloud.notifications.models.NotificationHistory)16 Endpoint (com.redhat.cloud.notifications.models.Endpoint)14 Event (com.redhat.cloud.notifications.models.Event)10 JsonObject (io.vertx.core.json.JsonObject)9 LocalDateTime (java.time.LocalDateTime)8 Test (org.junit.jupiter.api.Test)8 Action (com.redhat.cloud.notifications.ingress.Action)7 List (java.util.List)7 Inject (javax.inject.Inject)7 Context (com.redhat.cloud.notifications.ingress.Context)6 QuarkusTest (io.quarkus.test.junit.QuarkusTest)6 EndpointType (com.redhat.cloud.notifications.models.EndpointType)5 MockServerLifecycleManager (com.redhat.cloud.notifications.MockServerLifecycleManager)4 StatelessSessionFactory (com.redhat.cloud.notifications.db.StatelessSessionFactory)4 Metadata (com.redhat.cloud.notifications.ingress.Metadata)4 Payload (com.redhat.cloud.notifications.ingress.Payload)4 Arrays (java.util.Arrays)4 Map (java.util.Map)4 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)4 Assertions.assertTrue (org.junit.jupiter.api.Assertions.assertTrue)4