Search in sources :

Example 6 with EmailSubscriptionProperties

use of com.redhat.cloud.notifications.models.EmailSubscriptionProperties 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 EmailSubscriptionProperties

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

the class EndpointResourceTest method testAddEndpointEmailSubscription.

@Test
void testAddEndpointEmailSubscription() {
    String tenant = "adding-email-subscription";
    String orgId = "adding-email-subscription2";
    String userName = "user";
    String identityHeaderValue = TestHelpers.encodeRHIdentityInfo(tenant, orgId, userName);
    Header identityHeader = TestHelpers.createRHIdentityHeader(identityHeaderValue);
    MockServerConfig.addMockRbacAccess(identityHeaderValue, MockServerConfig.RbacAccess.FULL_ACCESS);
    // EmailSubscription can't be created
    EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
    Endpoint ep = new Endpoint();
    ep.setType(EndpointType.EMAIL_SUBSCRIPTION);
    ep.setName("Endpoint: EmailSubscription");
    ep.setDescription("Subscribe!");
    ep.setEnabled(true);
    ep.setProperties(properties);
    String stringResponse = given().header(identityHeader).when().contentType(JSON).body(Json.encode(ep)).post("/endpoints").then().statusCode(400).extract().asString();
    assertSystemEndpointTypeError(stringResponse, EndpointType.EMAIL_SUBSCRIPTION);
    RequestEmailSubscriptionProperties requestProps = new RequestEmailSubscriptionProperties();
    // EmailSubscription can be fetch from the properties
    Response response = given().header(identityHeader).when().contentType(JSON).body(Json.encode(requestProps)).post("/endpoints/system/email_subscription").then().statusCode(200).contentType(JSON).extract().response();
    JsonObject responsePoint = new JsonObject(response.getBody().asString());
    responsePoint.mapTo(Endpoint.class);
    assertNotNull(responsePoint.getString("id"));
    // It is always enabled
    assertEquals(true, responsePoint.getBoolean("enabled"));
    // Calling again yields the same endpoint id
    String defaultEndpointId = responsePoint.getString("id");
    response = given().header(identityHeader).when().contentType(JSON).body(Json.encode(requestProps)).post("/endpoints/system/email_subscription").then().statusCode(200).contentType(JSON).extract().response();
    responsePoint = new JsonObject(response.getBody().asString());
    responsePoint.mapTo(Endpoint.class);
    assertEquals(defaultEndpointId, responsePoint.getString("id"));
    // Different properties are different endpoints
    Set<String> endpointIds = new HashSet<>();
    endpointIds.add(defaultEndpointId);
    requestProps.setOnlyAdmins(true);
    response = given().header(identityHeader).when().contentType(JSON).body(Json.encode(requestProps)).post("/endpoints/system/email_subscription").then().statusCode(200).contentType(JSON).extract().response();
    responsePoint = new JsonObject(response.getBody().asString());
    responsePoint.mapTo(Endpoint.class);
    assertFalse(endpointIds.contains(responsePoint.getString("id")));
    endpointIds.add(responsePoint.getString("id"));
    response = given().header(identityHeader).when().contentType(JSON).body(Json.encode(requestProps)).post("/endpoints/system/email_subscription").then().statusCode(200).contentType(JSON).extract().response();
    responsePoint = new JsonObject(response.getBody().asString());
    responsePoint.mapTo(Endpoint.class);
    assertTrue(endpointIds.contains(responsePoint.getString("id")));
    // It is not possible to delete it
    stringResponse = given().header(identityHeader).when().delete("/endpoints/" + defaultEndpointId).then().statusCode(400).extract().asString();
    assertSystemEndpointTypeError(stringResponse, EndpointType.EMAIL_SUBSCRIPTION);
    // It is not possible to disable or enable it
    stringResponse = given().header(identityHeader).when().delete("/endpoints/" + defaultEndpointId + "/enable").then().statusCode(400).extract().asString();
    assertSystemEndpointTypeError(stringResponse, EndpointType.EMAIL_SUBSCRIPTION);
    stringResponse = given().header(identityHeader).when().put("/endpoints/" + defaultEndpointId + "/enable").then().statusCode(400).extract().asString();
    assertSystemEndpointTypeError(stringResponse, EndpointType.EMAIL_SUBSCRIPTION);
    // It is not possible to update it
    stringResponse = given().header(identityHeader).contentType(JSON).body(Json.encode(ep)).when().put("/endpoints/" + defaultEndpointId).then().statusCode(400).extract().asString();
    assertSystemEndpointTypeError(stringResponse, EndpointType.EMAIL_SUBSCRIPTION);
    // It is not possible to update it to other type
    ep.setType(EndpointType.WEBHOOK);
    WebhookProperties webhookProperties = new WebhookProperties();
    webhookProperties.setMethod(HttpType.POST);
    webhookProperties.setDisableSslVerification(false);
    webhookProperties.setSecretToken("my-super-secret-token");
    webhookProperties.setUrl(getMockServerUrl());
    ep.setProperties(webhookProperties);
    stringResponse = given().header(identityHeader).contentType(JSON).body(Json.encode(ep)).when().put("/endpoints/" + defaultEndpointId).then().statusCode(400).extract().asString();
    assertSystemEndpointTypeError(stringResponse, EndpointType.EMAIL_SUBSCRIPTION);
}
Also used : Response(io.restassured.response.Response) RequestEmailSubscriptionProperties(com.redhat.cloud.notifications.routers.models.RequestEmailSubscriptionProperties) Header(io.restassured.http.Header) Endpoint(com.redhat.cloud.notifications.models.Endpoint) RequestEmailSubscriptionProperties(com.redhat.cloud.notifications.routers.models.RequestEmailSubscriptionProperties) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) WebhookProperties(com.redhat.cloud.notifications.models.WebhookProperties) JsonObject(io.vertx.core.json.JsonObject) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test) QuarkusTest(io.quarkus.test.junit.QuarkusTest) DbIsolatedTest(com.redhat.cloud.notifications.db.DbIsolatedTest) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 8 with EmailSubscriptionProperties

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

the class LifecycleITest method addDefaultBehaviorGroupAction.

private void addDefaultBehaviorGroupAction(BehaviorGroup behaviorGroup) {
    EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
    properties.setOnlyAdmins(true);
    Endpoint endpoint = createEndpoint(null, EMAIL_SUBSCRIPTION, "Email endpoint", "System email endpoint", properties);
    addBehaviorGroupAction(behaviorGroup.getId(), endpoint.getId());
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties)

Aggregations

EmailSubscriptionProperties (com.redhat.cloud.notifications.models.EmailSubscriptionProperties)8 Endpoint (com.redhat.cloud.notifications.models.Endpoint)7 List (java.util.List)5 Collectors (java.util.stream.Collectors)5 Inject (javax.inject.Inject)5 Transactional (javax.transaction.Transactional)5 EndpointType (com.redhat.cloud.notifications.models.EndpointType)4 StatelessSessionFactory (com.redhat.cloud.notifications.db.StatelessSessionFactory)3 WebhookProperties (com.redhat.cloud.notifications.models.WebhookProperties)3 JsonObject (io.vertx.core.json.JsonObject)3 HashSet (java.util.HashSet)3 UUID (java.util.UUID)3 EntityManager (javax.persistence.EntityManager)3 BadRequestException (javax.ws.rs.BadRequestException)3 Logger (org.jboss.logging.Logger)3 Test (org.junit.jupiter.api.Test)3 MockServerLifecycleManager (com.redhat.cloud.notifications.MockServerLifecycleManager)2 TestHelpers (com.redhat.cloud.notifications.TestHelpers)2 Action (com.redhat.cloud.notifications.ingress.Action)2 Context (com.redhat.cloud.notifications.ingress.Context)2