Real-time automation results in Slack channel

     We know that Slack is a powerful communication tool that brings the team together, wherever you are. Slack offers channels to stay organized and focused on central spaces for conversations, files, tools, and people. Slack provides workspaces, applications, and various team collaboration options. Slack applications help to act as chatbots on various occasions.

     The major advantages of Slack include all team communication in one place, integration with various services, one-to-one, and private groups, and the ability to integrate various bots or apps into your slack channel depending on your needs.

    Nowadays, we know that most CI tools have the capability to integrate with slack to share real-time test execution results. In this article, I would like to share a couple of utilities written in Java that describe how to send real-time automation test results via slack channels. The automation results included both plain text results and the attached reports.

Prerequisites

  • You must have a slack account.
  • Add the latest jslack dependency into pom.xml if you are using Maven.
  • Add the latest version of the following dependencies to pom.xml to handle the API operations,
    • httpclient
    • httpmime  
  • Add extentreports dependency to the pom.xml file to generate the HTML automation report.

Step-by-step procedure

  1. Create an account in Slack and then create a Slack workspace. Use https://slack.com/get-started#/
  2. Create a Slack application to communicate with your channel about the automation execution status. Use https://api.slack.com/apps
  3. Create a Slack channel by clicking plus icon right to Channels in your slack workspace. Keep the Slack channel name in mind and it is useful during the scripting.
  4. Add created Slack application to your Slack channel by clicking Add an app link from the slack channel.
  5. Go to https://api.slack.com/apps and select your Slack application. Select Incoming Webhooks and activate it. Scroll down the page and you will get Webhook URL for your channel. This Webhook URL is an important parameter in your script which helps to send the messages to your Slack channel.
  6. Go to OAuth & Permissions section, there you will get Bot User OAuth Token and User OAuth Token which helps the Slack application to send files into your Slack Channel. Copy the Bot User OAuth Token and you can use it in the script. Sometimes the Bot User OAuth Token has some restrictions, in that case, you can use the User OAuth Token value in the script to upload the file.
  7. Scroll down on OAuth & Permissions page to reach the Scopes section. Make sure that the following scopes are added,
    • Bot Token Scopes:
      • file:write
      • incoming:webhook
    • User Token Scopes:
      • file:write

  I have created two Slack utilities to send real-time test results and the test execution reports to the Slack channel. Following are the methods:

  • sendTestExecutionStatusToSlack helps to send the test results to the Slack channel with the help of the Webhook URL and channel name.
  • sendTestExecutionReportToSlack helps to send the automation test execution report with the help of file upload API, Bot User OAuth Token, and channel name. Following are the detailed implementation of both methods,
private static String urlSlackWebHook = "YOUR_WEBHOOK_URL";
private static String channelName = "YOUR_CHANNEL_NAME";
private static String userOAuthToken= "YOUR_USER_OAuth_TOKEN";

//Send test execution status to the Slack channel
public void sendTestExecutionStatusToSlack(String message) throws Exception {
try {
StringBuilder messageBuider = new StringBuilder();
messageBuider.append(message);
Payload payload = Payload.builder().channel(channelName).text(messageBuider.toString()).build();

WebhookResponse webhookResponse = Slack.getInstance().send(urlSlackWebHook, payload);
webhookResponse.getMessage();
} catch (IOException e) {
System.out.println("Unexpected Error! WebHook:" + urlSlackWebHook);
}
}

//Upload test execution reports to the Slack channel
public void sendTestExecutionReportToSlack(String testReportPath) throws Exception {
String url = "https://slack.com/api/files.upload ";
try {
HttpClient httpclient = HttpClientBuilder.create().disableContentCompression().build();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody fileBody = new FileBody(new File(testReportPath));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", fileBody);
builder.addTextBody("channels", channelName);
builder.addTextBody("token", userOAuthToken);
httppost.setEntity(builder.build());
HttpResponse response = null;
response = httpclient.execute(httppost);
HttpEntity result = response.getEntity();
} catch (Exception e) {
e.printStackTrace();
}
}

     You can use above both methods based on your convenience in the automation listener class. If you are using the TestNG framework then you can implement the ITestListener interface and use both methods inside the implemented methods of ITestListener to send real-time test execution results to your Slack channel.

Sample Output: Slack View

Slack Automation Flow

    Try to use the above methods to send real-time test results to the Slack channel and enjoy your automation.

make it perfect!

Advertisement

22 thoughts on “Real-time automation results in Slack channel

Add yours

  1. String url = “https://slack.com/api/files.upload?token=” + botUserOAuthAccessToken + “&channels=” + channelName
    + “”;

    in this url… what is this ‘token=”’ ? how to get it from?

    Liked by 1 person

    1. Bot user access tokens, if your Slack app includes a bot user, upon approval the JSON response will contain an additional node containing an access token to be specifically used for your bot user, within the context of the approving workspace.

      To get this, login to https://api.slack.com/ and go to “Your Apps”, select your app. Left side you can see “OAuth & Permissions”, select that option; scroll down and you can see Bot User OAuth Access Token and copy that value, then paste into inseat of “botUserOAuthAccessToken” in code.

      Like

      1. String url = “https://slack.com/api/files.upload?token=” ”
        + botUserOAuthAccessToken + “&channels = ” + channelName + “”;

        I tried like this but this is not working, I dont know why is mistake.?

        Like

    1. I got report generated in Slack, I am fetching the HTML report pushed by extent report. Sorry, what’s the error on your side? please check the report generated inthe folder. Are you getting the counts in the slack?

      Like

  2. Hi Sanoj, I am able to publish the message on slack channel but unable to publish my extent report . Could you please guide me on the report should be fetched from the reports folders and sent to sendTestExecutionReportToSlack method with the report path?

    Like

    1. Hi Nikhil,

      Messages are dealing with help of Webhook URL. But attachment report, we can do with Bot application. For me its working and able to publish the HTML report into slack channel with help of the Bot app. You need to make sure that steps 6 and step 7 configured properly. I am using Bot User OAuth Access Token from OAuth & Permissions section of my Bot app.

      Like

  3. private static String channelName = “automation-report”;
    private static String botUserOAuthAccessToken = “xoxb-XXXXXXXXX-2287604583447-07rlMaceowTubmqIhGGCLz0d”;
    public static void main(String[] arg){
    String url = “https://slack.com/api/files.upload?token=”+ botUserOAuthAccessToken + “&channels=” + channelName + “”;
    try {
    HttpClient httpclient = HttpClientBuilder.create().disableContentCompression().build();
    HttpPost httppost = new HttpPost(url);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody fileBody = new FileBody(new File(System.getProperty(“user.dir”)+”\\test-output\\extentReports\\extentreport.html”));
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart(“file”, fileBody);
    builder.addTextBody(“channels”, channelName);
    builder.addTextBody(“token”, botUserOAuthAccessToken);
    httppost.setEntity(builder.build());
    HttpResponse response = null;
    response = httpclient.execute(httppost);
    HttpEntity result = response.getEntity();
    System.out.println(result);
    System.out.println(response.getStatusLine().getReasonPhrase());
    } catch (Exception e) {
    e.printStackTrace();
    }
    RESPONSE:
    ResponseEntityProxy{[Content-Type: application/json; charset=utf-8,Chunked: true]}
    OK
    Hi @Sanoj I am also not able to receive files on Slack

    Like

  4. I have used both methods in Listeners class, but unable to send message to the slack channel, in slack channel added integration with workspace is shown

    Like

  5. A humble request, can you please post the updated code for this? I am unable to post report in slack channel.

    Like

      1. Really appreciate that you keep your content updated. Looking forward for the update this weekend. Thanks 🙂

        Liked by 1 person

    1. Slack not generating any kind of report. Your framework generate some report and that report posting to the channels. I have used extent report in this case. I am on writing one article to generate PDF report with pie-chart. It will come soon.

      Like

    1. You can use the same methods and logic, only thing you have to pass the report path into sendTestExecutionReportToSlack method. It will publish to the slack, there is not dependency with TestNG or JUnit. We should aware about the report path where it generating in the project structure. For real-time results we need the connection with Listeners. In case of Junit you can extends your report class with RunListener.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: