Create Post Api in Java for Test Rail - java

Im trying to create a java post request to create a test run on test rail, however it doesn't seem to be working heres my code:
public class create_run {
public JSONObject AddTestRunTest() throws IOException, APIException {
JSONObject jsonobject = new JSONObject();
APIClient client = new APIClient("https://stdec.testrail.com/");
client.setUser("fea#sportdec.com");
client.setPassword("Fa1");
Map<String, Object> map = new HashMap<String, Object>();
map.put("suite_id", 829);
map.put("assignedto_id", 1);
map.put("name", "Regression Test");
map.put("include_all", true);
map.put({"17082","17085"});
client.sendPost("index.php?/api/v2/add_run/24", map);
return jsonobject;
}
}
The testrail documentation is here im looking for the add run http://docs.gurock.com/testrail-api2/reference-runs
Any help here how to make this actually work , is completing but nothing is happening. I'm a tester but struggling with this pat of the Java

Have sorted this problem by :
public static String TEST_RUN_ID = "27";
public static String TESTRAIL_USERNAME = "xxx#yahoo.com";
public static String TESTRAIL_PASSWORD = "jdNnNt0OKyNnVA0BW";
public static String RAILS_ENGINE_URL = "https://axulxharmx.testrail.io/";
public static final int TEST_CASE_PASSED_STATUS = 1;
public static final int TEST_CASE_FAILED_STATUS = 5;
public static void addResultForTestCase(String testCaseId, int status,
String error) throws IOException, APIException {
String testRunId = TEST_RUN_ID;
APIClient client = new APIClient(RAILS_ENGINE_URL);
client.setUser(TESTRAIL_USERNAME);
client.setPassword(TESTRAIL_PASSWORD);
HashMap data = new HashMaps();
data.put("status_id", status);
data.put("comment", "Test Executed- Status updated test automation framework.");
client.sendPost("add_result_for_case/"+testRunId+"/"+testCaseId+"",data );
}
**It's working fine in java code as well as POSTMAN and pushing the results to my TestRail instance.

Related

Mocking JIRA java client objects using mockito

We are integrating our application with JIRA, to create an issue with attachment.
Method 1:
public JSONObject createIssue() {
IssueRestClient issueClient = restClient.getIssueClient();
MetadataRestClient metadataClient = restClient.getMetadataClient();
Map<String, Long> priorityMap = new HashMap<>();
Map<String, Long> issueMap = new HashMap<>();
Map<String, String> fieldsMap = new HashMap<>();
// To get the list of all types of priorities
metadataClient.getPriorities().claim().forEach(priorityType -> priorityMap.put(priorityType.getName(), priorityType.getId()));
// To get the list of all issue types
metadataClient.getIssueTypes().claim().forEach(issueType -> issueMap.put(issueType.getName(), issueType.getId()));
// To get the list of all fields, which includes the custom fields
metadataClient.getFields().claim().forEach(fieldType -> fieldsMap.put(fieldType.getName(), fieldType.getId()));
// skipped the remaining code
}
Method 2:
public void addAttachmentToIssue(String issueId, InputStream inputStream, String fileNameWithExtension) {
Issue issue = null;
IssueRestClient issueClient = restClient.getIssueClient();
  Promise<Issue> promiseIssue = issueClient.getIssue(issueId);
  issue = promiseIssue.claim();
  issueClient.addAttachment(issue.getAttachmentsUri(), inputStream, fileNameWithExtension);
}
I'm writing unit tests using Mockito.
public class JIRATest{
#InjectMocks
JIRAService mockJiraService;
JiraRestClient mockJiraRestClient;
IssueRestClient mockIssueRestClient;
Promise mockPromise;
Issue mockIssue;
#BeforeEach
public void setup() {
mockJiraService = new JIRAService();
mockJiraRestClient = mock(JiraRestClient.class);
mockIssueRestClient = mock(IssueRestClient.class);
mockJiraService.setRestClient(mockJiraRestClient);
mockPromise = mock(Promise.class);
mockIssue = mock(Issue.class);
}
#Test
public void addAttachmentTest(){
Mockito.when(mockJiraRestClient.getIssueClient()).thenReturn(mockIssueRestClient);
Mockito.when(mockIssueRestClient.getIssue("DCU")).thenReturn(mockPromise);
Mockito.when(mockPromise.claim()).thenReturn(mockIssue);
Mockito.when(mockIssueRestClient.addAttachment(any(), any(), any()));
String webSite = "https://www.google.com";
URL url = new URL(webSite);
InputStream stream = url.openStream();
mockJiraService.addAttachmentToIssue("issueId", stream, "lowes-webpage.html");
}
}
How to mock these below objects, so that i wanted to use it in thenReturn() of Mockito?
1. Promise<Issue>
2. metadataClient.getPriorities() return Promise<Iterable<Priority>>
3. metadataClient.getPriorities().claim() return Iterable<Priority>
4. metadataClient.getIssueTypes() return Promise<Iterable<IssueType>>
5. metadataClient.getPriorities().claim() return Iterable<IssueType>
6. metadataClient.getFields() return Promise<Iterable<Field>>
7. metadataClient.getFields().claim() return Iterable<Field>

Grouping and sorting Lists into a Map

Before anything, the title doesn't convey what I really want to ask.
What I want to know is, how can I make a map, where for several users, it collects their Data and then groups it all together. I'm currently using two lists, one for the users' names and another for their works. I tried using a map.put but it kept overwriting the previous entry. So what I'd like to obtain is as follows;
Desired output:
{user1 = work1, work2, work3 , user2 = work1, work2 , userN = workN}
Current output:
{[user1, user2, user3, user4]=[work1, work2, work3, work4, work5 (user1) , work1 (user2), work1, work2, work3 ( user3 )]}
This is the code that I'm currently using to achieve the above.
private static Map<List<String>, List<String>> repositoriesUserData = new HashMap<>();
private static Set<String> collaboratorNames = new HashSet<>();
public static void main(String[] args) throws Exception {
login();
getCollabs(GITHUB_REPO_NAME);
repositoriesUnderUser();
}
public GitManager(String AUTH, String USERNAME, String REPO_NAME) throws IOException {
this.GITHUB_LOGIN = USERNAME;
this.GITHUB_OAUTH = AUTH;
this.GITHUB_REPO_NAME = REPO_NAME;
this.githubLogin = new GitHubBuilder().withOAuthToken(this.GITHUB_OAUTH, this.GITHUB_LOGIN).build();
this.userOfLogin = this.githubLogin.getUser(GITHUB_LOGIN);
}
public static void login() throws IOException {
new GitManager(GIT_TOKEN, GIT_LOGIN, GITHUB_REPO_NAME);
connect();
}
public static void connect() throws IOException {
if (githubLogin.isCredentialValid()) {
valid = true;
githubLogin.connect(GITHUB_LOGIN, GITHUB_OAUTH);
userOfLogin = githubLogin.getUser(GITHUB_LOGIN);
}
}
public static String getCollabs(String repositoryName) throws IOException {
GHRepository collaboratorsRepository = userOfLogin.getRepository(repositoryName);
collaboratorNames = collaboratorsRepository.getCollaboratorNames();
String collaborators = collaboratorNames.toString();
System.out.println("Collaborators for the following Repository: " + repositoryName + "\nAre: " + collaborators);
String out = "Collaborators for the following Repository: " + repositoryName + "\nAre: " + collaborators;
return out;
}
public static List<String> fillList() {
List<String> collaborators = new ArrayList<>();
collaboratorNames.forEach(s -> {
collaborators.add(s);
});
return collaborators;
}
public static String repositoriesUnderUser() throws IOException {
GHUser user;
List<String> names = new ArrayList<>();
List<String> repoNames = new ArrayList<>();
for (int i = 0; i < fillList().size(); i++) {
user = githubLogin.getUser(fillList().get(i));
Map<String, GHRepository> temp = user.getRepositories();
names.add(user.getLogin());
temp.forEach((c, b) -> {
repoNames.add(b.getName());
});
}
repositoriesUserData.put(names,repoNames);
System.out.println(repositoriesUserData);
return "temporaryReturn";
}
All help is appreciated!
I'll give it a try (code in question still not working for me):
If I understood correctly, you want a Map, that contains the repositories for each user.
So therefore i think the repositoriesUserData should be a Map<String, List<String>.
With that in mind, lets fill the map in each loop-cycle with the user from the lists as key and the list of repository-names as value.
The method would look like this (removed the temporary return and replaced it with void)
public static String repositoriesUnderUser() throws IOException {
for (int i = 0; i < fillList().size(); i++) {
GHUser user = githubLogin.getUser(fillList().get(i));
Map<String, GHRepository> temp = user.getRepositories();
repositoriesUserData.put(user.getLogin(), temp.values().stream().map(GHRepository::getName).collect(Collectors.toList()));
}
return "temporaryReturn";
}
Edit: (Short explanation what is happening in your code)
You are collecting all usernames to the local List names and also adding all repository-names to the local List 'repoNames'.
At the end of the method you put a new entry to your map repositoriesUserData.
That means at the end of the method you just added one single entry to the map where
key = all of the users
value = all of the repositories from the users (because its a list, if two users have the same repository, they are added twice to this list)

Unable to get data from java web service

Someone please help me i keep trying but not able to find out why i am unable to get the results.
I have created this java springboot web service where when I run the java application, a web browser page will open and when I type in the URL e.g localhost:8080/runbatchfileparam/test.bat the program will check if the test.bat file exist first. If it does, the web page will show a JSON result {“Result”: true} and the command in the batch file will be executed. If it does not exist, the web page will show {“Result”: false}.
I want to create an ASP.NET Web Service that will use the function created in the java web service. When I run the ASP.NET Web Application, a web browser page will open. User will type in URL something like this: localhost:12345/api/callbatchfile/test.bat. The java web service should be running and I should get either {“Result”: true} or {“Result”: false} when I run the C# ASP.NET Web Application too.
However I only get an empty {} without anything inside the brackets. Why is that so?
Here are my code in ASP.NET
TestController.cs
private TestClient testClient = new TestClient();
public async Task<IHttpActionResult> GET(string fileName)
{
try
{
var result = await testClient.runbatchfile(fileName);
var resultDTO = JsonConvert.DeserializeObject<TestVariable>(result);
return Json(resultDTO);
}
catch (Exception e)
{
var result = "Server is not running";
return Ok(new { ErrorMessage = result });
}
}
TestVariable.cs
public class TestVariable
{
public static int fileName { get; set; }
}
TestClient.cs
private static HttpClient client;
private static string BASE_URL = "http://localhost:8080/";
static TestClient()
{
client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> runbatchfile(string fileName)
{
var endpoint = string.Format("runbatchfile/{0}", fileName);
var response = await client.GetAsync(endpoint);
return await response.Content.ReadAsStringAsync();
}
WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "TestBatchClient",
routeTemplate: "api/runbatchfile/{fileName}",
defaults: new { action = "GET", controller = "Test" }
);
Someone please do help me. Thank you so much.
EDIT
Java web service
Application.java
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
BatchFileController.java
private static final String template = "Sum, %s!";
#RequestMapping("/runbatchfile/{param:.+}")
public ResultFormat runbatchFile(#PathVariable("param") String fileName) {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch(fileName);
}
ResultFormat
private boolean result;
public ResultFormat(boolean result) {
this.result = result;
}
public boolean getResult() {
return result;
}
RunBatchFile.java
public ResultFormat runBatch(String fileName) {
String var = fileName;
String filePath = ("C:/Users/attsuap1/Desktop/" + var);
try {
Process p = Runtime.getRuntime().exec(filePath);
int exitVal = p.waitFor();
return new ResultFormat(exitVal == 0);
} catch (Exception e) {
e.printStackTrace();
return new ResultFormat(false);
}
}
I am not sure if this helps.. but I suspect that the AsyncTask is not really executing...
var result = await testClient.testCallBatchProject(fileName);
I would try something like below:
await testClient.testCallBatchProject(fileName).Delay(1000);
Can you try and check if the same happens for a synchronous call? .. if it does, we can zero down on the above.

Server address or IP for the servlet weather service is currently still hard-coded

Hello to all you Java and Android experts, I can really use your help with some project for my school, since I am stuck with no clue.
In the activity ServletWeatherAPI, the server address or IP for the servlet weather service is currently still hard-coded, for example:
Private final static String baseURL = "http://192.168.178.21:8080/WeatherService/weather? ";
In the Settings tab of the MultiWeatherApp, I need to add an option to specify the address or IP of my server (without the servlet path "/ WeatherService /
Weather? ").
A web request for this weather service should use the address stored in the SharedPreferences.
Any one have an idea how can I do this? since I have none.
I know how to add to the preferences.xml the option but no idea about the rest.
I attach my project from github and the calls ServletWeatherAPI.
Any help will be much appreciated, I am no expert so a pseudocode will be very helpful to understand it.
my app in Github
public class ServletWeatherAPI implements IWeatherAPI {
private final static String baseURL = "http://localhost:8080/WeatherService/weather?";
private JSONObject weatherdata;
private ServletWeatherAPI(String queryString) throws
IOException, JSONException {
String result = HttpRequest.request(baseURL + queryString);
weatherdata = new JSONObject(result);
}
public static IWeatherAPI fromLocationName(String locationName) throws IOException, JSONException {
return new ServletWeatherAPI("q=" + URLEncoder.encode(locationName, "UTF-8"));
}
public static IWeatherAPI fromLatLon(double lat, double
lon) throws IOException, JSONException {
return new ServletWeatherAPI("lat=" + lat + "&lon=" + lon);
}
#Override
public double getTemperature() throws JSONException {
return weatherdata.getDouble("tempC");
}
#Override
public String getDescription() throws JSONException {
return weatherdata.getString("description");
}
#Override
public String getError() {
return "";
}
#Override
public String getProviderInfo() {
return "ServletWeatherService";
}
#Override
public String getIconPath() throws JSONException {
return "serlvetweatherservice/" +
weatherdata.getString("icon");
}
}
I have found the solution if anyone will be interested, here's my git:
MultiWeatherApp

How to use Authentication with JIRA REST API in Java

hi im creating a simple tool using java to create,update and delete issues(tickets) in jira. i am using rest api following code is im using to authenticate jira and issue tickets.
public class JiraConnection {
public static URI jiraServerUri = URI.create("http://localhost:8090/jira/rest/api/2/issue/HSP-1/");
public static void main(String args[]) throws IOException {
final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri,"vinuvish92#gmail.com","vinu1994");
System.out.println("Sending issue creation requests...");
try {
final List<Promise<BasicIssue>> promises = Lists.newArrayList();
final IssueRestClient issueClient = restClient.getIssueClient();
System.out.println("Sending issue creation requests...");
for (int i = 0; i < 100; i++) {
final String summary = "NewIssue#" + i;
final IssueInput newIssue = new IssueInputBuilder("TST", 1L, summary).build();
System.out.println("\tCreating: " + summary);
promises.add(issueClient.createIssue(newIssue));
}
System.out.println("Collecting responses...");
final Iterable<BasicIssue> createdIssues = transform(promises, new Function<Promise<BasicIssue>, BasicIssue>() {
#Override
public BasicIssue apply(Promise<BasicIssue> promise) {
return promise.claim();
}
});
System.out.println("Created issues:\n" + Joiner.on("\n").join(createdIssues));
} finally {
restClient.close();
}
}
}
according this code i couldn't connect to the jira
**following exception i am getting **
please suggest me best solution to do my task
It seems to me that your error is clearly related to url parameter. The incriminated line and the fact that the error message is about not finding the resource are good indications of it.
You don't need to input the whole endpoint since you are using the JiraRestClient. Depending on the method that you call it will resolve the endpoint. Here is an example that works: as you can see I only input the base url

Categories

Resources