diff --git a/seyren-core/src/main/java/com/seyren/core/service/notification/SlackNotificationService.java b/seyren-core/src/main/java/com/seyren/core/service/notification/SlackNotificationService.java index 534e4e34..f1f2becd 100644 --- a/seyren-core/src/main/java/com/seyren/core/service/notification/SlackNotificationService.java +++ b/seyren-core/src/main/java/com/seyren/core/service/notification/SlackNotificationService.java @@ -65,206 +65,203 @@ public class SlackNotificationService implements NotificationService { @Inject public SlackNotificationService(SeyrenConfig seyrenConfig) { - this.seyrenConfig = seyrenConfig; - this.baseUrl = "https://slack.com"; + this.seyrenConfig = seyrenConfig; + this.baseUrl = "https://slack.com"; } protected SlackNotificationService(SeyrenConfig seyrenConfig, String baseUrl) { - this.seyrenConfig = seyrenConfig; - this.baseUrl = baseUrl; + this.seyrenConfig = seyrenConfig; + this.baseUrl = baseUrl; } @Override public boolean canHandle(SubscriptionType subscriptionType) { - return subscriptionType == SubscriptionType.SLACK; + return subscriptionType == SubscriptionType.SLACK; } @Override - public void sendNotification(Check check, Subscription subscription, List alerts) throws NotificationFailedException { - String token = seyrenConfig.getSlackToken(); - String webhookUrl = seyrenConfig.getSlackWebhook(); - - String url; - HttpEntity entity; - - if (!webhookUrl.isEmpty()) { - LOGGER.debug("Publishing notification using configured Webhook"); - url = webhookUrl; - try { - entity = createJsonEntity(check, subscription, alerts); - } catch (JsonProcessingException e) { - throw new NotificationFailedException("Failed to serialize message alert.", e); - } - } else if (!token.isEmpty()){ - LOGGER.debug("Publishing notification using slack web API"); - url = String.format("%s/api/chat.postMessage", baseUrl); - try { - entity = createFormEntity(check, subscription, alerts); - } catch (UnsupportedEncodingException e) { - throw new NotificationFailedException("Failed to serialize alert.", e); - } - } else { - LOGGER.warn("No SLACK_WEBHOOK_URL or SLACK_TOKEN set. Cannot notify slack."); - return; - } - - HttpClient client = HttpClientBuilder.create().useSystemProperties().build(); - HttpPost post = new HttpPost(url); - post.addHeader("accept", "application/json"); - - try { - post.setEntity(entity); - HttpResponse response = client.execute(post); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Status: {}, Body: {}", response.getStatusLine(), new BasicResponseHandler().handleResponse(response)); - } - } catch (Exception e) { - LOGGER.warn("Error posting to Slack", e); - } finally { - post.releaseConnection(); - HttpClientUtils.closeQuietly(client); - } + public void sendNotification(Check check, Subscription subscription, List alerts) + throws NotificationFailedException { + String token = seyrenConfig.getSlackToken(); + String webhookUrl = seyrenConfig.getSlackWebhook(); + + String url; + HttpEntity entity; + + if (!webhookUrl.isEmpty()) { + LOGGER.debug("Publishing notification using configured Webhook"); + url = webhookUrl; + try { + entity = createJsonEntity(check, subscription, alerts); + } catch (JsonProcessingException e) { + throw new NotificationFailedException("Failed to serialize message alert.", e); + } + } else if (!token.isEmpty()) { + LOGGER.debug("Publishing notification using slack web API"); + url = String.format("%s/api/chat.postMessage", baseUrl); + try { + entity = createFormEntity(check, subscription, alerts); + } catch (UnsupportedEncodingException e) { + throw new NotificationFailedException("Failed to serialize alert.", e); + } + } else { + LOGGER.warn("No SLACK_WEBHOOK_URL or SLACK_TOKEN set. Cannot notify slack."); + return; + } + + HttpClient client = HttpClientBuilder.create().useSystemProperties().build(); + HttpPost post = new HttpPost(url); + post.addHeader("accept", "application/json"); + + try { + post.setEntity(entity); + HttpResponse response = client.execute(post); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Status: {}, Body: {}", response.getStatusLine(), + new BasicResponseHandler().handleResponse(response)); + } + } catch (Exception e) { + LOGGER.warn("Error posting to Slack", e); + } finally { + post.releaseConnection(); + HttpClientUtils.closeQuietly(client); + } } - - private HttpEntity createJsonEntity(Check check, Subscription subscription, List alerts) throws JsonProcessingException { - Map payload = new HashMap(); - payload.put("channel", subscription.getTarget()); - payload.put("username", seyrenConfig.getSlackUsername()); - payload.put("icon_url", seyrenConfig.getSlackIconUrl()); - payload.put("attachments", formatForWebhook(check, subscription, alerts)); - String message = new ObjectMapper().writeValueAsString(payload); - - if (LOGGER.isDebugEnabled()) { - LOGGER.info("> message: {}", message); - } - - return new StringEntity(message, ContentType.APPLICATION_JSON); + + private HttpEntity createJsonEntity(Check check, Subscription subscription, List alerts) + throws JsonProcessingException { + Map payload = new HashMap(); + payload.put("channel", subscription.getTarget()); + payload.put("username", seyrenConfig.getSlackUsername()); + payload.put("icon_url", seyrenConfig.getSlackIconUrl()); + payload.put("attachments", formatForWebhook(check, subscription, alerts)); + String message = new ObjectMapper().writeValueAsString(payload); + + if (LOGGER.isDebugEnabled()) { + LOGGER.info("> message: {}", message); + } + + return new StringEntity(message, ContentType.APPLICATION_JSON); } - private HttpEntity createFormEntity(Check check, Subscription subscription, List alerts) throws UnsupportedEncodingException { - List parameters = new ArrayList(); - parameters.add(new BasicNameValuePair("token", seyrenConfig.getSlackToken())); - parameters.add(new BasicNameValuePair("channel", StringUtils.removeEnd(subscription.getTarget(), "!"))); - parameters.add(new BasicNameValuePair("text", formatForWebApi(check, subscription, alerts))); - parameters.add(new BasicNameValuePair("username", seyrenConfig.getSlackUsername())); - parameters.add(new BasicNameValuePair("icon_url", seyrenConfig.getSlackIconUrl())); - - if (LOGGER.isDebugEnabled()) { - LOGGER.info("> parameters: {}", parameters); - } - - return new UrlEncodedFormEntity(parameters); + private HttpEntity createFormEntity(Check check, Subscription subscription, List alerts) + throws UnsupportedEncodingException { + List parameters = new ArrayList(); + parameters.add(new BasicNameValuePair("token", seyrenConfig.getSlackToken())); + parameters.add(new BasicNameValuePair("channel", StringUtils.removeEnd(subscription.getTarget(), "!"))); + parameters.add(new BasicNameValuePair("text", formatForWebApi(check, subscription, alerts))); + parameters.add(new BasicNameValuePair("username", seyrenConfig.getSlackUsername())); + parameters.add(new BasicNameValuePair("icon_url", seyrenConfig.getSlackIconUrl())); + + if (LOGGER.isDebugEnabled()) { + LOGGER.info("> parameters: {}", parameters); + } + + return new UrlEncodedFormEntity(parameters); } - + private String formatForWebApi(Check check, Subscription subscription, List alerts) { - String url = formatCheckUrl(check); - String alertsString = formatAlertsForText(alerts); - String channel = subscription.getTarget().contains("!") ? "" : ""; - String description = formatDescription(check); - final String state = check.getState().toString(); - - return String.format("%s*%s* %s [%s]%s\n```\n%s\n```\n#%s %s", - Iterables.get(extractEmojis(), check.getState().ordinal(), ""), - state, - check.getName(), - url, - description, - alertsString, - state.toLowerCase(Locale.getDefault()), - channel - ); + String url = formatCheckUrl(check); + String alertsString = formatAlertsForText(alerts); + String channel = subscription.getTarget().contains("!") ? "" : ""; + String description = formatDescription(check); + final String state = check.getState().toString(); + + return String.format("%s*%s* %s [%s]%s\n```\n%s\n```\n#%s %s", + Iterables.get(extractEmojis(), check.getState().ordinal(), ""), state, check.getName(), url, + description, alertsString, state.toLowerCase(Locale.getDefault()), channel); } - - private List> formatForWebhook(Check check, Subscription subscription, List alerts) { - List> attachments = new ArrayList>(); - for (Alert alert: alerts) { - Map attachment = new HashMap(); - attachment.put("mrkdwn_in", Arrays.asList("fields", "text", "pretext")); - attachment.put("fallback", String.format("An alert has been triggered for '%s'",check.getName())); - attachment.put("color", formatColor(check)); - attachment.put("title", check.getName()); - attachment.put("title_link", formatCheckUrl(check)); - attachment.put("fields", formatAlertForWebhook(check, alert)); - attachments.add(attachment); - } - return attachments; + + private List> formatForWebhook(Check check, Subscription subscription, List alerts) { + List> attachments = new ArrayList>(); + for (Alert alert : alerts) { + Map attachment = new HashMap(); + attachment.put("mrkdwn_in", Arrays.asList("fields", "text", "pretext")); + attachment.put("fallback", String.format("An alert has been triggered for '%s'", check.getName())); + attachment.put("color", formatColor(check)); + attachment.put("title", check.getName()); + attachment.put("title_link", formatCheckUrl(check)); + attachment.put("fields", formatAlertForWebhook(check, alert)); + attachments.add(attachment); + } + return attachments; } private String formatAlertsForText(List alerts) { - return Joiner.on("\n").join(transform(alerts, new Function() { - @Override - public String apply(Alert input) { - return String.format("%s = %s (%s to %s)", input.getTarget(), input.getValue().toString(), input.getFromType(), input.getToType()); - } - })); + return Joiner.on("\n").join(transform(alerts, new Function() { + @Override + public String apply(Alert input) { + return String.format("%s = %s (%s to %s)", input.getTarget(), input.getValue().toString(), + input.getFromType(), input.getToType()); + } + })); } - - private List> formatAlertForWebhook(Check check, Alert alert) { - List> fields = new ArrayList>(); - - if (check.getDescription() != null && !check.getDescription().isEmpty()) { - Map description = new HashMap(); - description.put("title", "Description"); - description.put("value", check.getDescription()); - description.put("short", false); - fields.add(description); - } - - Map trigger = new HashMap(); - trigger.put("title", "Trigger"); - trigger.put("value", String.format("`%s = %s`", alert.getTarget(), alert.getValue().toString())); - trigger.put("short", false); - fields.add(trigger); - - Map from = new HashMap(); - from.put("title", "From"); - from.put("value", alert.getFromType().toString()); - from.put("short", true); - fields.add(from); - - Map to = new HashMap(); - to.put("title", "To"); - to.put("value", alert.getToType().toString()); - to.put("short", true); - fields.add(to); - - return fields; + + private List> formatAlertForWebhook(Check check, Alert alert) { + List> fields = new ArrayList>(); + + if (check.getDescription() != null && !check.getDescription().isEmpty()) { + Map description = new HashMap(); + description.put("title", "Description"); + description.put("value", check.getDescription());O + description.put("short", false); + fields.add(description); } + Map trigger = new HashMap(); + trigger.put("title", "Trigger"); + trigger.put("value", String.format("`%s = %s`", alert.getTarget(), alert.getValue().toString())); + trigger.put("short", false); + fields.add(trigger); + + Map from = new HashMap(); + from.put("title", "From"); + from.put("value", alert.getFromType().toString()); + from.put("short", true); + fields.add(from); + + Map to = new HashMap(); + to.put("title", "To"); + to.put("value", alert.getToType().toString()); + to.put("short", true); + fields.add(to); + + return fields; + } + private String formatDescription(Check check) { - String description; - if (StringUtils.isNotBlank(check.getDescription())) { - description = String.format("\n> %s", check.getDescription()); - } else { - description = ""; - } - return description; + String description; + if (StringUtils.isNotBlank(check.getDescription())) { + description = String.format("\n> %s", check.getDescription()); + } else { + description = ""; + } + return description; } - + private List extractEmojis() { - return Lists.newArrayList( - Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getSlackEmojis()) - ); - } - + return Lists + .newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getSlackEmojis())); + } + private String formatCheckUrl(Check check) { - return String.format("%s/#/checks/%s", seyrenConfig.getBaseUrl(), check.getId()); + return String.format("%s/#/checks/%s", seyrenConfig.getBaseUrl(), check.getId()); } - + private String formatColor(Check check) { - switch(check.getState()) { - case ERROR: - return seyrenConfig.getSlackDangerColor(); - case EXCEPTION: - return seyrenConfig.getSlackExceptionColor(); - case OK: - return seyrenConfig.getSlackGoodColor(); - case UNKNOWN: - return seyrenConfig.getSlackUnknownColor(); - case WARN: - return seyrenConfig.getSlackWarningColor(); - default: - return seyrenConfig.getSlackUnknownColor(); - } + switch (check.getState()) { + case ERROR: + return seyrenConfig.getSlackDangerColor(); + case EXCEPTION: + return seyrenConfig.getSlackExceptionColor(); + case OK: + return seyrenConfig.getSlackGoodColor(); + case UNKNOWN: + return seyrenConfig.getSlackUnknownColor(); + case WARN: + return seyrenConfig.getSlackWarningColor(); + default: + return seyrenConfig.getSlackUnknownColor(); + } } } diff --git a/seyren-core/src/test/java/com/seyren/core/service/notification/SlackNotificationServiceTest.java b/seyren-core/src/test/java/com/seyren/core/service/notification/SlackNotificationServiceTest.java index b0397713..4e5244dc 100644 --- a/seyren-core/src/test/java/com/seyren/core/service/notification/SlackNotificationServiceTest.java +++ b/seyren-core/src/test/java/com/seyren/core/service/notification/SlackNotificationServiceTest.java @@ -70,219 +70,198 @@ public class SlackNotificationServiceTest { @Before public void before() { - mockSeyrenConfig = mock(SeyrenConfig.class); - when(mockSeyrenConfig.getBaseUrl()).thenReturn(clientDriver.getBaseUrl() + "/slack"); - when(mockSeyrenConfig.getSlackEmojis()).thenReturn(""); - when(mockSeyrenConfig.getSlackIconUrl()).thenReturn(""); - when(mockSeyrenConfig.getSlackUsername()).thenReturn(SLACK_USERNAME); - notificationService = new SlackNotificationService(mockSeyrenConfig, clientDriver.getBaseUrl()); + mockSeyrenConfig = mock(SeyrenConfig.class); + when(mockSeyrenConfig.getBaseUrl()).thenReturn(clientDriver.getBaseUrl() + "/slack"); + when(mockSeyrenConfig.getSlackEmojis()).thenReturn(""); + when(mockSeyrenConfig.getSlackIconUrl()).thenReturn(""); + when(mockSeyrenConfig.getSlackUsername()).thenReturn(SLACK_USERNAME); + notificationService = new SlackNotificationService(mockSeyrenConfig, clientDriver.getBaseUrl()); } @After public void after() { - System.setProperty("SLACK_USERNAME", ""); + System.setProperty("SLACK_USERNAME", ""); } @Test public void notificationServiceCanOnlyHandleSlackSubscription() { - assertThat(notificationService.canHandle(SubscriptionType.SLACK), is(true)); - for (SubscriptionType type : SubscriptionType.values()) { - if (type == SubscriptionType.SLACK) { - continue; - } - assertThat(notificationService.canHandle(type), is(false)); - } + assertThat(notificationService.canHandle(SubscriptionType.SLACK), is(true)); + for (SubscriptionType type : SubscriptionType.values()) { + if (type == SubscriptionType.SLACK) { + continue; + } + assertThat(notificationService.canHandle(type), is(false)); + } } @Test public void useSlackApiTokenTest() { - // Given - when(mockSeyrenConfig.getSlackToken()).thenReturn(SLACK_TOKEN); - when(mockSeyrenConfig.getSlackWebhook()).thenReturn(""); + // Given + when(mockSeyrenConfig.getSlackToken()).thenReturn(SLACK_TOKEN); + when(mockSeyrenConfig.getSlackWebhook()).thenReturn(""); - Check check = givenCheck(); - Subscription subscription = givenSlackSubscriptionWithTarget("target"); - Alert alert = givenAlert(); + Check check = givenCheck(); + Subscription subscription = givenSlackSubscriptionWithTarget("target"); + Alert alert = givenAlert(); - List alerts = Arrays.asList(alert); + List alerts = Arrays.asList(alert); - StringBodyCapture bodyCapture = new StringBodyCapture(); + StringBodyCapture bodyCapture = new StringBodyCapture(); - clientDriver.addExpectation( - onRequestTo("/api/chat.postMessage") - .withMethod(ClientDriverRequest.Method.POST) - .capturingBodyIn(bodyCapture) - .withHeader("accept", "application/json"), - giveEmptyResponse()); + clientDriver.addExpectation(onRequestTo("/api/chat.postMessage").withMethod(ClientDriverRequest.Method.POST) + .capturingBodyIn(bodyCapture).withHeader("accept", "application/json"), giveEmptyResponse()); - // When - notificationService.sendNotification(check, subscription, alerts); + // When + notificationService.sendNotification(check, subscription, alerts); - // Then - String content = bodyCapture.getContent(); - //System.out.println(decode(content)); + // Then + String content = bodyCapture.getContent(); + // System.out.println(decode(content)); - assertContent(content, check, subscription); - assertThat(content, containsString("&channel=" + subscription.getTarget())); - assertThat(content, not(containsString(encode("")))); + assertContent(content, check, subscription); + assertThat(content, containsString("&channel=" + subscription.getTarget())); + assertThat(content, not(containsString(encode("")))); } @Test public void mentionChannelWhenTargetContainsExclamationTest() { - //Given - when(mockSeyrenConfig.getSlackToken()).thenReturn(SLACK_TOKEN); - when(mockSeyrenConfig.getSlackWebhook()).thenReturn(""); + // Given + when(mockSeyrenConfig.getSlackToken()).thenReturn(SLACK_TOKEN); + when(mockSeyrenConfig.getSlackWebhook()).thenReturn(""); - Check check = givenCheck(); - Subscription subscription = givenSlackSubscriptionWithTarget("target!"); - Alert alert = givenAlert(); + Check check = givenCheck(); + Subscription subscription = givenSlackSubscriptionWithTarget("target!"); + Alert alert = givenAlert(); - List alerts = Arrays.asList(alert); + List alerts = Arrays.asList(alert); - StringBodyCapture bodyCapture = new StringBodyCapture(); + StringBodyCapture bodyCapture = new StringBodyCapture(); - clientDriver.addExpectation( - onRequestTo("/api/chat.postMessage") - .withMethod(ClientDriverRequest.Method.POST) - .capturingBodyIn(bodyCapture) - .withHeader("accept", "application/json"), - giveEmptyResponse()); + clientDriver.addExpectation(onRequestTo("/api/chat.postMessage").withMethod(ClientDriverRequest.Method.POST) + .capturingBodyIn(bodyCapture).withHeader("accept", "application/json"), giveEmptyResponse()); - // When - notificationService.sendNotification(check, subscription, alerts); + // When + notificationService.sendNotification(check, subscription, alerts); - // Then - String content = bodyCapture.getContent(); - //System.out.println(decode(content)); + // Then + String content = bodyCapture.getContent(); + // System.out.println(decode(content)); - assertContent(content, check, subscription); - assertThat(content, containsString("&channel=" + StringUtils.removeEnd(subscription.getTarget(), "!"))); - assertThat(content, containsString(encode(""))); + assertContent(content, check, subscription); + assertThat(content, containsString("&channel=" + StringUtils.removeEnd(subscription.getTarget(), "!"))); + assertThat(content, containsString(encode(""))); } @Test public void useSlackWebHookTest() throws JsonParseException, JsonMappingException, IOException { - // Given - when(mockSeyrenConfig.getSlackToken()).thenReturn(""); - when(mockSeyrenConfig.getSlackWebhook()).thenReturn(clientDriver.getBaseUrl() + SLACK_WEBHOOK_URI_TO_POST); - when(mockSeyrenConfig.getSlackDangerColor()).thenReturn("danger"); - - Check check = givenCheck(); - - Subscription subscription = givenSlackSubscriptionWithTarget("target"); - - Alert alert = givenAlert(); - List alerts = Arrays.asList(alert); - - StringBodyCapture bodyCapture = new StringBodyCapture(); - - clientDriver.addExpectation( - onRequestTo(SLACK_WEBHOOK_URI_TO_POST) - .withMethod(ClientDriverRequest.Method.POST) - .capturingBodyIn(bodyCapture) - .withHeader("accept", "application/json"), - giveEmptyResponse()); - - // When - notificationService.sendNotification(check, subscription, alerts); - - // Then - String content = bodyCapture.getContent(); - assertThat(content, is(notNullValue())); - - Map map = new HashMap(); - ObjectMapper mapper = new ObjectMapper(); - TypeReference> typeRef = new TypeReference>() {}; - map = mapper.readValue(content, typeRef); - - assertThat((String) map.get("channel"), is(subscription.getTarget())); - assertThat((String) map.get("username"), is(SLACK_USERNAME)); - assertThat((String) map.get("icon_url"), isEmptyString()); - - @SuppressWarnings("unchecked") - List> attachments = (List>) map.get("attachments"); - Map attachment = (Map) attachments.get(0); - - assertThat((String)attachment.get("fallback"), containsString(check.getName())); - assertThat((String)attachment.get("title"), is(check.getName())); - assertThat((String)attachment.get("color"), is("danger")); // AlertType.ERROR - assertThat((String)attachment.get("title_link"), containsString("/#/checks/" + check.getId())); - - @SuppressWarnings("unchecked") - List> fields = (List>) attachment.get("fields"); - - // There should be four fields: description, trigger, from, and to - assertThat(fields.size(), is(4)); - - for(Map field: fields) { - if ("Description".equals(field.get("title"))) { - assertThat((String)field.get("value"), is("A description")); - assertThat((Boolean)field.get("short"), is(false)); - } else if ("Trigger".equals(field.get("title"))) { - assertThat((String)field.get("value"), is("`some.graphite.target = 1.0`")); - assertThat((Boolean)field.get("short"), is(false)); - } else if ("From".equals(field.get("title"))) { - assertThat((String)field.get("value"), is("OK")); - assertThat((Boolean)field.get("short"), is(true)); - } else if ("To".equals(field.get("title"))) { - assertThat((String)field.get("value"), is("ERROR")); - assertThat((Boolean)field.get("short"), is(true)); - } else { - fail("Unexpected field " + field.get("title")); - } - } + // Given + when(mockSeyrenConfig.getSlackToken()).thenReturn(""); + when(mockSeyrenConfig.getSlackWebhook()).thenReturn(clientDriver.getBaseUrl() + SLACK_WEBHOOK_URI_TO_POST); + when(mockSeyrenConfig.getSlackDangerColor()).thenReturn("danger"); + + Check check = givenCheck(); + + Subscription subscription = givenSlackSubscriptionWithTarget("target"); + + Alert alert = givenAlert(); + List alerts = Arrays.asList(alert); + + StringBodyCapture bodyCapture = new StringBodyCapture(); + + clientDriver.addExpectation(onRequestTo(SLACK_WEBHOOK_URI_TO_POST).withMethod(ClientDriverRequest.Method.POST) + .capturingBodyIn(bodyCapture).withHeader("accept", "application/json"), giveEmptyResponse()); + + // When + notificationService.sendNotification(check, subscription, alerts); + + // Then + String content = bodyCapture.getContent(); + assertThat(content, is(notNullValue())); + + Map map = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + TypeReference> typeRef = new TypeReference>() { + }; + map = mapper.readValue(content, typeRef); + + assertThat((String) map.get("channel"), is(subscription.getTarget())); + assertThat((String) map.get("username"), is(SLACK_USERNAME)); + assertThat((String) map.get("icon_url"), isEmptyString()); + + @SuppressWarnings("unchecked") + List> attachments = (List>) map.get("attachments"); + Map attachment = (Map) attachments.get(0); + + assertThat((String) attachment.get("fallback"), containsString(check.getName())); + assertThat((String) attachment.get("title"), is(check.getName())); + assertThat((String) attachment.get("color"), is("danger")); // AlertType.ERROR + assertThat((String) attachment.get("title_link"), containsString("/#/checks/" + check.getId())); + + @SuppressWarnings("unchecked") + List> fields = (List>) attachment.get("fields"); + + // There should be four fields: description, trigger, from, and to + assertThat(fields.size(), is(4)); + + for (Map field : fields) { + if ("Description".equals(field.get("title"))) { + assertThat((String) field.get("value"), is("A description")); + assertThat((Boolean) field.get("short"), is(false)); + } else if ("Trigger".equals(field.get("title"))) { + assertThat((String) field.get("value"), is("`some.graphite.target = 1.0`")); + assertThat((Boolean) field.get("short"), is(false)); + } else if ("From".equals(field.get("title"))) { + assertThat((String) field.get("value"), is("OK")); + assertThat((Boolean) field.get("short"), is(true)); + } else if ("To".equals(field.get("title"))) { + assertThat((String) field.get("value"), is("ERROR")); + assertThat((Boolean) field.get("short"), is(true)); + } else { + fail("Unexpected field " + field.get("title")); + } + } } Check givenCheck() { - Check check = new Check() - .withId("123") - .withEnabled(true) - .withName("test-check") - .withDescription("A description") - .withState(AlertType.ERROR); - return check; + Check check = new Check().withId("123").withEnabled(true).withName("test-check") + .withDescription("A description").withState(AlertType.ERROR); + return check; } Subscription givenSlackSubscriptionWithTarget(String target) { - Subscription subscription = new Subscription() - .withEnabled(true) - .withType(SubscriptionType.SLACK) - .withTarget(target); - return subscription; + Subscription subscription = new Subscription().withEnabled(true).withType(SubscriptionType.SLACK) + .withTarget(target); + return subscription; } Alert givenAlert() { - Alert alert = new Alert() - .withTarget("some.graphite.target") - .withValue(new BigDecimal("1.0")) - .withTimestamp(new DateTime()) - .withFromType(AlertType.OK) - .withToType(AlertType.ERROR); - return alert; + Alert alert = new Alert().withTarget("some.graphite.target").withValue(new BigDecimal("1.0")) + .withTimestamp(new DateTime()).withFromType(AlertType.OK).withToType(AlertType.ERROR); + return alert; } private void assertContent(String content, Check check, Subscription subscription) { - assertThat(content, containsString("token=" + SLACK_TOKEN)); - assertThat(content, containsString(encode("*" + check.getState().name() + "* " + check.getName()))); - assertThat(content, containsString(encode("/#/checks/" + check.getId()))); - assertThat(content, containsString("&username=" + SLACK_USERNAME)); - assertThat(content, containsString("&icon_url=")); + assertThat(content, containsString("token=" + SLACK_TOKEN)); + assertThat(content, containsString(encode("*" + check.getState().name() + "* " + check.getName()))); + assertThat(content, containsString(encode("/#/checks/" + check.getId()))); + assertThat(content, containsString("&username=" + SLACK_USERNAME)); + assertThat(content, containsString("&icon_url=")); } String encode(String data) { - try { - return URLEncoder.encode(data, CONTENT_ENCODING); - } catch (UnsupportedEncodingException e) { - return null; - } + try { + return URLEncoder.encode(data, CONTENT_ENCODING); + } catch (UnsupportedEncodingException e) { + return null; + } } String decode(String data) { - try { - return URLDecoder.decode(data, CONTENT_ENCODING); - } catch (UnsupportedEncodingException e) { - return null; - } + try { + return URLDecoder.decode(data, CONTENT_ENCODING); + } catch (UnsupportedEncodingException e) { + return null; + } } }