I am using gurock API to get the test case Status from Test Rail
The below will return the status of TC.. I will provide trRunID in the pom.xml. and TCname will be taken using method Name.
public static int FetchTestRailResult(String trRunId, String TCName, String trusername, String trpassword )
throws MalformedURLException, IOException, APIException {
int val=0;
APIClient client = new APIClient($testRailurl);
client.setUser(trusername);
client.setPassword(trpassword);
;
JSONArray array = (JSONArray) client.sendGet("get_tests/"+trRunId+"&status_id=1");
for (int i = 0; i < array.size(); i++) {
JSONObject c = (JSONObject) (array.get(i));
String testrailTestCaseName=c.get("title").toString().split("_")[1];
if (testrailTestCaseName.equals(TCName)) {
val=1;
break;
}
}
return val;
}
The below will update the results.
public static void UpdateResultToTestRail(String trusername, String trpassword, String trRunId,String testCaseName,String status, String testStepDetails)
throws MalformedURLException, IOException, APIException {
APIClient client = new APIClient($testrailurl);
client.setUser(trusername);
client.setPassword(trpassword);
HashMap data = new HashMap();
data.put("status_id", status);
data.put("comment", testStepDetails);
JSONArray array = (JSONArray) client.sendGet("get_tests/"+trRunId);
//System.out.println(array.size());
for (int i = 0; i < array.size(); i++) {
JSONObject c = (JSONObject) (array.get(i));
String testrailTestCaseName=c.get("title").toString().split("_")[1];
if (testrailTestCaseName.equals(testCaseName)) {
System.out.println(c.get("id"));
client.sendPost("add_result/" + c.get("id"), data);
break;
}
}
}
I am now migrating to maven and Now it has dependency
<!-- https://mvnrepository.com/artifact/com.codepine.api/testrail-api-java-client -->
<dependency>
<groupId>com.codepine.api</groupId>
<artifactId>testrail-api-java-client</artifactId>
<version>2.0.1</version>
</dependency>
It does not have the api methods and it has Builder and build but further could not able to check connection is successful or not.. Anyone used testrail in Maven?
I haven't used that library, but it looks fairly easy to use it and they have some docs on their githib project page: https://github.com/codepine/testrail-api-java-client
For your use case, I think you just need to do the following:
TestRail testRail = TestRail.builder("https://some.testrail.net/", "username", "password");
Tests tests = testRail.tests();
List<Test> lst = tests.list(runId).execute();
//filter it based on your conditions
I did not run the code - just composed it, so it might have some issues, but should give you an idea on how to use the library.
Please note, that as of Feb 26, TestRail is changing their HTTP response for bulk requests (like cases, tests, projects, etc), so I'm not sure if that library will still work with the next TR version - you will need to check it.
P.S. We are developing some set of products for integration with TestRail, so you might want to look at them. If you are interested, please check out our products:
https://www.agiletestware.com/pangolin
https://www.agiletestware.com/firefly
Based on your testing framework (JUnit of TestNG), try to use one of these libs:
TestRail-JUnit
TestRail-TestNG
Both of them have Medium articles on how to integrate it just in a few steps (see README.md there)
Related
If I pass a string (either in English or Arabic) as an input to the Google Translate API, it should translate it into the corresponding other language and give the translated string to me.
I read the same case in a forum but it was very hard to implement for me.
I need the translator without any buttons and if I give the input string it should automatically translate the value and give the output.
Can you help out?
You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS.
1) Create new script with such code on google script:
var mock = {
parameter:{
q:'hello',
source:'en',
target:'fr'
}
};
function doGet(e) {
e = e || mock;
var sourceText = ''
if (e.parameter.q){
sourceText = e.parameter.q;
}
var sourceLang = '';
if (e.parameter.source){
sourceLang = e.parameter.source;
}
var targetLang = 'en';
if (e.parameter.target){
targetLang = e.parameter.target;
}
var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});
return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);
}
2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.
3) Use this java code for testing your API:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Translator {
public static void main(String[] args) throws IOException {
String text = "Hello world!";
//Translated text: Hallo Welt!
System.out.println("Translated text: " + translate("en", "de", text));
}
private static String translate(String langFrom, String langTo, String text) throws IOException {
// INSERT YOU URL HERE
String urlStr = "https://your.google.script.url" +
"?q=" + URLEncoder.encode(text, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
As it is free, there are QUATA LIMITS: https://docs.google.com/macros/dashboard
Use java-google-translate-text-to-speech instead of Google Translate API v2 Java.
About java-google-translate-text-to-speech
Api unofficial with the main features of Google Translate in Java.
Easy to use!
It also provide text to speech api. If you want to translate the text "Hello!" in Romanian just write:
Translator translate = Translator.getInstance();
String text = translate.translate("Hello!", Language.ENGLISH, Language.ROMANIAN);
System.out.println(text); // "Bună ziua!"
It's free!
As #r0ast3d correctly said:
Important: Google Translate API v2 is now available as a paid service. The courtesy limit for existing Translate API v2 projects created prior to August 24, 2011 will be reduced to zero on December 1, 2011. In addition, the number of requests your application can make per day will be limited.
This is correct: just see the official page:
Google Translate API is available as a paid service. See the Pricing and FAQ pages for details.
BUT, java-google-translate-text-to-speech is FREE!
Example!
I've created a sample application that demonstrates that this works. Try it here: https://github.com/IonicaBizau/text-to-speech
Generate your own API key here. Check out the documentation here.
You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.
Below is a quick start example which translates two English strings to Spanish:
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;
public class QuickstartSample
{
public static void main(String[] arguments) throws IOException, GeneralSecurityException
{
Translate t = new Translate.Builder(
GoogleNetHttpTransport.newTrustedTransport()
, GsonFactory.getDefaultInstance(), null)
// Set your application name
.setApplicationName("Stackoverflow-Example")
.build();
Translate.Translations.List list = t.new Translations().list(
Arrays.asList(
// Pass in list of strings to be translated
"Hello World",
"How to use Google Translate from Java"),
// Target language
"ES");
// TODO: Set your API-Key from https://console.developers.google.com/
list.setKey("your-api-key");
TranslationsListResponse response = list.execute();
for (TranslationsResource translationsResource : response.getTranslations())
{
System.out.println(translationsResource.getTranslatedText());
}
}
}
Required maven dependencies for the code snippet:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-translate</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
<version>LATEST</version>
</dependency>
I’m tired of looking for free translators and the best option for me was Selenium (more precisely selenide and webdrivermanager) and https://translate.google.com
import io.github.bonigarcia.wdm.ChromeDriverManager;
import com.codeborne.selenide.Configuration;
import io.github.bonigarcia.wdm.DriverManagerType;
import static com.codeborne.selenide.Selenide.*;
public class Main {
public static void main(String[] args) throws IOException, ParseException {
ChromeDriverManager.getInstance(DriverManagerType.CHROME).version("76.0.3809.126").setup();
Configuration.startMaximized = true;
open("https://translate.google.com/?hl=ru#view=home&op=translate&sl=en&tl=ru");
String[] strings = /some strings to translate
for (String data: strings) {
$x("//textarea[#id='source']").clear();
$x("//textarea[#id='source']").sendKeys(data);
String translation = $x("//span[#class='tlid-translation translation']").getText();
}
}
}
You can use Google Translate API v2 Java. It has a core module that you can call from your Java code and also a command line interface module.
I am automating a web page which runs in multi-threading environment, so I am exporting every test result into a file system and I wanted to maintain every test result uniquely for the future reference. So is there a way to pass file name as parameter to a test method dynamically while calling it from TestNG class.
I know we can pass parameters from .xml file but if I do that the values will more like static and can be seen by all the thread running parallel.
Test class will be called from main method as bellow
public class Test {
public static void main(String[] args) throws ParseException {
try
{
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { Testing.class });
testng.run();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Bellow code is my test method
public class Testing {
#Test
#Parameters("filename")
public void testMethod(String fileName){
System.out.println("filename is: "+fileName);
// ---- remaining test logic -----
}
}
Or can we use TestListenerAdapter onStart() method to inject parameter values...?.
If you want unique file name you can just add it a time stamp
Date date = new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String timeStamp = formatter.format(date);
String fileName = "TestResults-" + timeStamp;
You can store your values into ITestContext which will be available for all tests.
You can set up the values in a configuration method (#BeforeSuite for example) or a listener.
Pass Dynamic Parameters to TestNG suite during runtime
What the below code does:
I want to add a list of parameters to each test during runtime. These parameters are passed as maven runtime arguments. They are read using System.getProperty() method as shown below. Then these parameters are added to the test inside suite and testng is ran successfully. This can be really useful in other scenarios as well.
The below code reads the testng.xml file and adds parameter to
List<String> parameters = new ArrayList<>();
parameters = Arrays.asList(System.getProperty("parameters").split(",");
TestNG tng = new TestNG();
File initialFile = new File("testng.xml");
InputStream inputStream = FileUtils.openInputStream(initialFile);
Parser p = new Parser(inputStream);
List<XmlSuite> suites = p.parseToList();
for(XmlSuite suite:suites){
List<XmlTest> tests = suite.getTests();
for (XmlTest test : tests) {
for (int i = 0; i < parameters.size(); i++) {
HashMap<String, String> parametersMap = new HashMap<>();
parametersMap.put("parameter",parameters.get(i));
test.setParameters(parametersMap);
}
}
}
tng.setXmlSuites(suites);
tng.run();
Our team uses TestNG to run some tests in Selenium. We need to be able to run a given test on 3 different browsers (Chrome, Firefox, and [sadly] IE). We have a browser parameter on our base test class and really we could just declare three tests, one each for each browser; however, we'd really like to just be able to specify the browser value as "Standard 3" and have that run the test on each browser automatically.
So, I've built a class that implements ISuiteListener and attempts to create the new tests on the fly. However, any way I try to add tests fails. That is, no new tests I try to add will be executed by the suite. It's like nothing I did actually changed anything.
Here's my code:
public class Standard3BrowserSuiteListener implements ISuiteListener {
#Override
public void onStart(final ISuite suite) {
final XmlSuite xmlSuite = suite.getXmlSuite();
final Map<String, String> suiteParameters = xmlSuite.getParameters();
final List<XmlTest> currentTests = new ArrayList<XmlTest>(xmlSuite.getTests());
final ArrayList<XmlTest> testsToRun = new ArrayList<XmlTest>(currentTests.size());
for (final XmlTest test : currentTests) {
final Browser browser;
final Map<String, String> testParameters = test.getAllParameters();
{
String browserParameter = testParameters.get("browser");
if (browserParameter == null) {
browserParameter = suiteParameters.get("browser");
}
browser = Util.Enums.getEnumValueByName(browserParameter, Browser.class);
}
if (browser == Browser.STANDARD_3) {
XmlTest nextTest = cloneTestAndSetNameAndBrowser(xmlSuite, test, testParameters, "Chrome");
xmlSuite.addTest(nextTest);
testsToRun.add(nextTest); // alternate I've tried to no avail
nextTest = cloneTestAndSetNameAndBrowser(xmlSuite, test, testParameters, "Firefox");
xmlSuite.addTest(nextTest);
testsToRun.add(nextTest); // alternate I've tried to no avail
nextTest = cloneTestAndSetNameAndBrowser(xmlSuite, test, testParameters, "IE");
xmlSuite.addTest(nextTest);
testsToRun.add(nextTest); // alternate I've tried to no avail
} else {
testsToRun.add(test);
}
}
// alternate to xmlSuite.addTest I've tried to no avail
testsToRun.trimToSize();
currentTests = xmlSuite.getTests();
currentTests.clear();
currentTests.addAll(testsToRun);
}
private XmlTest cloneTestAndSetNameAndBrowser(final XmlSuite xmlSuite, final XmlTest test,
final Map<String, String> testParameters, final String browserName) {
final XmlTest nextTest = (XmlTest) test.clone();
final Map<String, String> nextParameters = new TreeMap<String, String>(testParameters);
nextParameters.put("browser", browserName.toUpperCase());
nextTest.setName(browserName);
final List<XmlClass> testClasses = new ArrayList<XmlClass>(test.getClasses());
nextTest.setClasses(testClasses);
return nextTest;
}
#Override
public void onFinish(final ISuite suite) {}
}
How can I replace the test with the browser value "Standard 3" with 3 tests and have it run properly? Thanks!
Here's what you need to do :
Upgrade to the latest released version of TestNG.
Build an implementation of org.testng.IAlterSuiteListener
Move your implementation that you created in ISuiteListener into this listener implementation.
Wire in this listener via the <listeners> tag in your suite XML File (or) via ServiceLoaders (As described in the javadocs of this interface)
I am creating testing automation framework using java but i am not able to read excel file in cucumber.
is there any way to use #DataProvider functionality og testNG?
I do not want to use datatable of feature file.
If you use CucumberJVM, I don't think you can make use of TestNG Data Providers without major hacks. Or at least this is not a "cucumber way" of doing things. Data Table is a Cucumber equivalent of TestNG Data Provider:
https://cucumber.io/docs/reference#data-tables
This is how you parametrise tests in Cucumber. I'm not saying the solution you are looking for can't be implemented, I'm saying you are most likely looking for a wrong thing. CucumberJVM makes use of DataProviders internally, to handle features this way:
https://github.com/cucumber/cucumber-jvm/blob/master/testng/src/main/java/cucumber/api/testng/AbstractTestNGCucumberTests.java
In case it helps others:
here is described how to link a Cucumber Scenario Outline to read data from an Excel file
https://startingwithseleniumwebdriver.blogspot.com/2017/04/getting-data-from-external-file-using.html
and here is described how to load data from an Excel file in a Cucumber feature file before executing Scenario steps
https://startingwithseleniumwebdriver.blogspot.com/2017/04/loading-data-from-external-file-to.html
I my case this was very useful, as for each Scenario step I had to load Excel data (data from multiple rows having same group ID) in order to perform further validations. Like this the Cucumber feature file was a bit cleaner while the Excel had all the details under the hood.
ExcelBDD Java edition can resolve this problem gracefully. code example
static Stream<Map<String, String>> provideExampleList() throws IOException {
String filePath = TestWizard.getExcelBDDStartPath("excelbdd-test")
+ "excelbdd-test\\src\\test\\resources\\excel.xlsx";
return Behavior.getExampleStream(filePath,"Expected1","Scenario1");
}
#ParameterizedTest(name = "Test{index}:{0}")
#MethodSource("provideExampleList")
void testgetExampleWithExpected(Map<String, String> parameterMap) {
assertNotNull(parameterMap.get("Header"));
System.out.println(String.format("=======Header: %s=======", parameterMap.get("Header")));
for (Map.Entry<String, String> param : parameterMap.entrySet()) {
System.out.println(String.format("%s --- %s", param.getKey(), param.getValue()));
}
}
more detail at ExcelBDD Guideline By Java Example
Here is the example how to read TestData from excel
public class Framework {
static String TestDataPath = System.getProperty("user.dir")
+ "\\ExcelFiles\\TestData.xlsx";
public static HashMap<String, HashMap<String, String>> hm1 = new HashMap<>();
static String s3;
public static void ReadTestData() throws IOException {
FileInputStream file = new FileInputStream(TestDataPath);
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheet("Sheet1");
Row HeaderRow = sheet.getRow(0);
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
Row currentRow = sheet.getRow(i);
HashMap<String, String> currentHash = new HashMap<String, String>();
for (int j = 0; j < currentRow.getPhysicalNumberOfCells(); j++) {
Cell currentCell1 = currentRow.getCell(0);
switch (currentCell1.getCellType()) {
case Cell.CELL_TYPE_STRING:
s3 = currentCell1.getStringCellValue();
System.out.println(s3);
break;
case Cell.CELL_TYPE_NUMERIC:
s3 = String.valueOf(currentCell1.getNumericCellValue());
System.out.println(s3);
break;
}
Cell currentCell = currentRow.getCell(j);
switch (currentCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
currentHash.put(HeaderRow.getCell(j).getStringCellValue(),
currentCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
currentHash.put(HeaderRow.getCell(j).getStringCellValue(),
String.valueOf(currentCell.getNumericCellValue()));
break;
}
}
hm1.put(s3, currentHash);
}
Here is the Model cucumber file and testData.
Scenario Outline: Successful Login with Valid Credentials
Given User is on Home Page
When User Navigate to LogIn Page
And User enters mandatory details of "<TextCase>"
Then Message displayed Login Successfully
Examples:
|TextCase|
|Case1 |
|Case2 |
[Test data img Link][1]
[1]: https://i.stack.imgur.com/IjOap.png
Here is the Model Stepdefination File
#When("^User enters mandatory details of \"([^\"]*)\"$")
public void user_enters_mandatory_details_of(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
driver.FindElement("UserName").sendKeys(Framework.hm1.get(arg1).get("UserName"));
Framework.FindElement("Password").sendKeys(Framework.hm1.get(arg1).get("Password"));
}
Follow above three steps in cucumber you will able to read test data.
I'm working with Rally REST API for Java
I want get the list of actual Iterations and Releases
here is the snippet
JsonObject projects = new JsonObject();
QueryRequest queryProjects = new QueryRequest("release");
queryProjects.setPageSize(1);
queryProjects.setLimit(1000);
queryProjects.setFetch(new Fetch("_refObjectName","Name"));
QueryResponse queryResponse;
try {
queryResponse = restApi.query(queryProjects);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new ServiceException(e);
}
In result I'm getting the list with a lot of duplicates. After closer inspection it seems I'm getting all versions of object - for the same Iteration/Release I have multiple versions - I can see different "_objectVersion" attribute for such duplicates.
Why is it so?
Can you please help me with the query which will retrieve distinct list of Iterations / Releases - I'm interested in just latest versions.
I can filter it out in Java but have a feeling there is more 'proper' way of doing this. Also getting the list with whole object history is not the best for code performance.
Thanks for any help!
When Releases and Iterations are created in Rally in a top project there is an option to propagate them throughout the project hierarchy. For example, if you have top project P1 with child project P2 and grandchild projects P21 and P22, you may create 4 releases with the same name and the same start and release dates. They are not identical releases: they have ObjectID and _ref unique to them. Please verify if this applies to your scenario.
To limit release query to a specific project set request project. Here is an example that returns only three releases that I have in a top project: R1,R2, and R3. Note
String projectRef = "/project/12352608219";
that is used later in the code:
releaseRequest.setProject(projectRef);
Note also the commented out
//String workspaceRef = "/workspace/12352608129";
and
// releaseRequest.setWorkspace(workspaceRef);
If I switch the comments: comment out project reference and uncomment workspace reference I will get what you called duplicates: multiple R1, R2 and R3 releases.
public class FindReleases {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String projectRef = "/project/12352608219";
//String workspaceRef = "/workspace/12352608129";
String applicationName = "RESTExampleFindReleasesByProject";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion()); //v.2.0 by default when using 2.0.2 jar and up
QueryRequest releaseRequest = new QueryRequest("Release");
releaseRequest.setFetch(new Fetch("Name"));
releaseRequest.setLimit(1000);
releaseRequest.setScopedDown(false);
releaseRequest.setScopedUp(false);
// releaseRequest.setWorkspace(workspaceRef);
releaseRequest.setProject(projectRef);
QueryResponse releaseQueryResponse = restApi.query(releaseRequest);
int numberOfReleasesInProject = releaseQueryResponse.getTotalResultCount();
System.out.println(numberOfReleasesInProject);
if(numberOfReleasesInProject >0){
for (int i=0;i<numberOfReleasesInProject;i++){
JsonObject releaseJsonObject = releaseQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println(releaseJsonObject.get("Name"));
}
}
}
finally{
if (restApi != null) {
restApi.close();
}
}
}
}