Using the Selenium and Slack integration, you can post updates to a Slack channel when there are changes in your automated testing results
jslack Java library is a robust library that helps to send real-time information via various Slack channels. Nowadays, the usage of Slack has increased and in high demand for all areas of communication. In automation, the jslack plays an important role to send real-time test execution status, complete results, and report documents. This will helps the management level to evaluate the stability of the applications very quickly. Slack integrations into the automation framework will play a critical role in the upcoming automation world.
Step-by-step Approach to Achieve Real-time Automation Result in Slack Channel
- Create an account in Slack and then create a Slack workspace. Use https://slack.com/get-started#/
- Create a Slack application to communicate with your channel about the automation execution status. Use https://api.slack.com/apps
- Create a Slack channel by clicking plus icon right to Channels in your slack workspace. Keep the Slack channel name in your mind and it useful during the scripting.
- Add created Slack application to your Slack channel by clicking Add an app link from the slack channel.
- 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.
- Go to OAuth & Permissions section, there you will get Bot User OAuth Access Token which helps the Slack application to send files into your Slack Channel. Copy the Bot User OAuth Access Token and you can use it in the script.
- Scroll down in OAuth & Permissions page to reach the Scopes section. Make sure that following scopes are added
- Bot Token Scopes:
- file:write
- incoming:webhook
- User Token Scopes:
- file:write
- Bot Token Scopes:
Two Slack utilities have been created to send real-time test results and the test execution reports to the Slackchannel. Following are the methods:
TestStatusToSlack : helps to send the test results to the Slack channel with the help of the Webhook URL and channel name.
ReportToSlack: 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
You must have following dependencies in pom.xml file
<dependency>
<groupId>com.github.seratch</groupId>
<artifactId>jslack</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.testng.Assert;
import org.testng.ITestListener;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.github.seratch.jslack.Slack;
import com.github.seratch.jslack.api.model.Attachment;
import com.github.seratch.jslack.api.model.Field;
import com.github.seratch.jslack.api.webhook.Payload;
import com.github.seratch.jslack.api.webhook.WebhookResponse;
import org.w3c.dom.*;
public class SlackIntegration {
private static String SlackWebHook = "YOUR_WEBHOOK_URL";
private static String channelName = "YOUR_SLACK_CHANNEL_NAME";
private static String botUserOAuthAccessToken = " OAuth_TOKEN";
@Test
public void TestStatusToSlack(String message) throws Exception {
try {
//Make sure testng.xml location should be correct
String path = System.getProperty("user.dir")+"/test-output/testng-results.xml";
File testNgResultXmlFile = new File(path);
//Get Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
//Build Document
Document document = null;
try {
document = builder.parse(testNgResultXmlFile);
}
catch (SAXException e) {
e.printStackTrace();
}
//Normalize the XML Structure;
document.getDocumentElement().normalize();
//Fetch TestNG Results from XML;
String totaltest = document.getDocumentElement().getAttribute("total");
String passed = document.getDocumentElement().getAttribute("passed");
String failed = document.getDocumentElement().getAttribute("failed");
String skipped = document.getDocumentElement().getAttribute("skipped");
StringBuilder messageBuider = new StringBuilder();
messageBuider.append(methodname+"========================"+"\n\n"+"Total Number of Test Cases: " + totaltest + "\n\n"+"Passed Test Cases: "+passed+"\n\n"+"Failed Test Cases: "+failed+"\n\n"+"Skipped Test Cases: "+skipped);
WebhookResponse webhookResponse = Slack.getInstance().send(SlackWebHook,
payload);
webhookResponse.getMessage();
}
catch (IOException e) {
System.out.println("Unexpected Error! WebHook:" + SlackWebHook);
}
@Test
public void ReportToSlack(@Optional("testReportPath") String testReportPath) {
String url = "https://slack.com/api/files.upload?token="+botUserOAuthAccessToken +"&channels="+channelName+" ";
try
{
HttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(testReportPath));
builder.addPart("file", fileBody);
httppost.setEntity(builder.build());
HttpResponse response = null;
response=httpclient.execute(httppost);
HttpEntity result = response.getEntity();
System.out.println(result.toString());
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Sample Output: Slack Channel