Creating integration test - java

I am new to writing integration tests. I must write code to check if my get method returns code 200. The problem is that this method is very complicated. I use 3 APIs to make it run.
Below I leave code of test method:
#Test
#WithUserDetails("operator")
public void getAnalysesByTagId_shouldReturn200() throws Exception {
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
MvcResult mvcResult = mockMvc.perform(multipart("/documents")
.file(getMetaDataFile("fileForAnalysisAndTags" + new Random().nextInt() + ".xlsx")))
.andExpect(status().isCreated()).andReturn();
DocumentCreateResponse document = parseResponse(mvcResult, DocumentCreateResponse.class);
MvcResult mvcDocumentDetails = mockMvc.perform(get("/documents/" + document.getId() + "/details")).andReturn();
DocumentDetailsResponse documentDetailsResponse = parseResponse(mvcDocumentDetails, DocumentDetailsResponse.class);
MvcResult mvcResultTag = mockMvc.perform(get("/tags/" + documentDetailsResponse.getAreaId() + "/children")).andReturn();
List<TagResponse> tagResponses = parseResponseList(mvcResultTag, TagResponse.class);
mockMvc.perform(get(TAGS_API + 1 + ANALYSES_API)).andExpect(status().isOk());
}
It returns code 404 instead of 200, I do something wrong in last line. I also leave the code of method thats being tested:
#GetMapping("tags/{tagId}/analyses")
#ApiOperation(value = "Find analyses associated with tag", produces = MediaType.APPLICATION_JSON_VALUE, notes = "Required Role: OPERATOR/USER")
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Analyses found"),
#ApiResponse(code = 404, message = "Not found, incorrect tag ID"),
#ApiResponse(code = 500, message = "Server error, something went wrong"),
#ApiResponse(code = 401, message = "Request lacks valid authentication credentials.")
})
public ResponseEntity<List<FindAnalysisResponse>> getAnalysesByTagId(
#PathVariable("tagId") Long tagId) throws NotFoundException {
var analyses = service.getAnalysesByTagId(tagId)
.stream()
.map(findAnalysisMapper::fromAnalysis)
.collect(Collectors.toList());
return new ResponseEntity<>(analyses, HttpStatus.OK);
}
In logs I can see, that only last lines are generating error:
Async:
Async started = false
Async result = null
Resolved Exception:
Type = com.name.common.domain.NotFoundException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"text/plain;charset=UTF-8", Content-Length:"15", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = text/plain;charset=UTF-8
Body = "Tag not found"
Forwarded URL = null
Redirected URL = null
Cookies = []
What should I do to make it work?

May be there is no tag 1 present?
mockMvc.perform(get(TAGS_API + 1 + ANALYSES_API)).andExpect(status().isOk());

Related

Getting "Invalid JSON payload received. Unexpected token.\ncode=4%2***\n^" error

So I am trying to make a HTTP request to get access token and refresh token using following java code.
String url = "https://oauth2.googleapis.com/token?";
Map<String, String> parameters = new HashMap<>();
parameters.put("code", "4%2******");
parameters.put("client_id", "*****");
parameters.put("client_secret", "*****");
parameters.put("redirect_uri", "http://localhost");
parameters.put("grant_type","authorization_code");
parameters.put("access_type","offline");
String form = parameters.keySet().stream()
.map(key -> key + "=" + URLEncoder.encode(parameters.get(key), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
.headers("Content-Type", "application/json")
.POST(BodyPublishers.ofString(form)).build();
HttpResponse<?> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode() + response.body().toString());
But using this code gives the following error,
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\ncode=4%2****\n^",
"status": "INVALID_ARGUMENT"
}
}
What is the mistake that I have done here and should rectify in order to get proper results?
You are sending application/x-www-form-urlencoded data format but according to the response message you should send json. Try to change definition of form:
String form = new ObjectMapper().writeValueAsString(parameters);

Swagger annotations for fixed set of Strings for input

Currently I have API which have something like below
#GetMapping("/list/{type}")
#ApiOperation(nickname = "reportUnits", httpMethod = "GET", produces = "application/json", responseContainer = "List", response = ReportFormatDTO.class, value = "Returns all available report Units", notes = "Returns all available report Units", consumes = "text")
#ApiResponses({ #ApiResponse(code = 404, message = "No data found"),
#ApiResponse(code = 500, message = "Error getting Report Units"), })
Flux<ReportFormatDTO> getList(#PathVariable("type") String type);
I need to tell swagger about fixed set of String to be passed in the Path variable.

Send the API Headers in Rest Assured using java

API Headers have two parameter Content-Type=application/json and also accesstoken = "some_token"
I trying to automate the API using Rest assured but not successful.
Below is the code
RestAssured.baseURI = prop.getProperty("serviceurl1");
//2. define the http request:
RequestSpecification httpRequest = RestAssured.given()
.filter(new ResponseLoggingFilter())
.filter(new RequestLoggingFilter());
JSONObject requestParams = new JSONObject();
requestParams.put("longitude", eLongitude);
requestParams.put("latitude", eLaititude);
requestParams.put("country", eCity);
httpRequest.headers("Content-Type", "application/json");
httpRequest.headers("accesstoken", "some_token.");
httpRequest.body(requestParams.toJSONString());
int statusCode = response.getStatusCode();
System.out.println("the status code is: "+ statusCode);
Assert.assertEquals(statusCode, TestUtil.RESPONSE_CODE_200);
System.out.println("the status line is: "+ response.getStatusLine());
//6. get the headers:
Headers headers = response.getHeaders();
System.out.println(headers);
String contentType = response.getHeader("Content-Type");
System.out.println("the value of content-type header is: "+ contentType);
String contentLength = response.getHeader("Content-Length");
System.out.println("the value of Content-Length header is: "+ contentLength);
Getting error message as "Provide Application Token" and 404 error code display.
Your httpRequest.headers("accesstoken", "kggkgkgkgketdfgxgcccvcdftfty."); is wrong. It should be:
httpRequest.headers("Authorization", "Bearer "+token);
can you try this once
Response resp = given().when().contentType(ContentType.JSON).header("accesstoken", "token").body(body).put("url");
You can pass the HashMap as body
These are the issues I can think of
This might be an internal API and it is expecting "Provide Application Token" and not the "accesstoken"
The error code you are getting is 404. So either the service is down or the URL you are using is not correct.
Hope this helps :)

How to duplicate a sheet in google spreadsheet api

I have used below code to do that.
BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
DuplicateSheetRequest requestBody = new DuplicateSheetRequest();
requestBody.setNewSheetName("test");
requestBody.setSourceSheetId(sheetId);
Sheets sheetsService = createSheetsService();
batchUpdateSpreadsheetRequest.set("duplicateSheet", requestBody);
Sheets.Spreadsheets.BatchUpdate request = sheetsService.spreadsheets().
batchUpdate(spreadsheetId,batchUpdateSpreadsheetRequest);
BatchUpdateSpreadsheetResponse response = request.execute();
When I execute this, I get below error.
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid JSON payload received. Unknown name \"duplicate_sheet\": Cannot find field.",
"reason" : "badRequest"
} ],
"message" : "Invalid JSON payload received. Unknown name \"duplicate_sheet\": Cannot find field.",
"status" : "INVALID_ARGUMENT"
}
what am I doing wrong here? What is the correct way to create duplicate of sheet?
I have managed to overcome this problem by following something similar from google documentation. Below is the code I used.
BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new
BatchUpdateSpreadsheetRequest();
List<Request> requests = new ArrayList<>();
DuplicateSheetRequest requestBody = new DuplicateSheetRequest();
requestBody.setNewSheetName("test");
requestBody.setSourceSheetId(sheetId);
requests.add(new Request().setDuplicateSheet(requestBody));
Sheets sheetsService = createSheetsService();
batchUpdateSpreadsheetRequest.setRequests(requests);
Sheets.Spreadsheets.BatchUpdate request =
sheetsService.spreadsheets().batchUpdate(spreadsheetId, batchUpdateSpreadsheetRequest);
BatchUpdateSpreadsheetResponse response = request.execute();
Here is the PHP version of creating a sheet duplicate in case you need:
//Assuming you already have a $spreadsheet
$spreadsheetId = $spreadsheet->spreadsheetId;
$body = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => array(
'duplicateSheet' => array(
'sourceSheetId' => 0, //Source sheet id goes here as an integer
'insertSheetIndex' => 1, //Position where the new sheet should be inserted
'newSheetName' => 'test' //Set new name if you want
)
)
));
$spreadsheet = $service->spreadsheets->batchUpdate($spreadsheetId, $body);
Here is a C# (.net 6) version:
public void Duplicate(int SourceSheetId, string NewSheetName) {
BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
batchUpdateSpreadsheetRequest.Requests = new List<Request>();
batchUpdateSpreadsheetRequest.Requests.Add(new Request() {
DuplicateSheet = new DuplicateSheetRequest() {
NewSheetName = NewSheetName,
SourceSheetId = SourceSheetId
},
});
var req = Service.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, SheetID); //public SheetsService Service; property of parent class
BatchUpdateSpreadsheetResponse response = req.Execute();
}

Connect to json-rpc interface

I'm trying to connect to the transmission rpc interface via C#/Java to get some informations back.
https://trac.transmissionbt.com/browser/trunk/extras/rpc-spec.txt
Unfortunatly I have problems to get the correct HTTP-Post to access the interface.
For example if I try this in C#:
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["torrent-get"] = "id";
var response = client.UploadValues("http://ip:9091/transmission/rpc", values);
var responseString = Encoding.Default.GetString(response);
Console.WriteLine("" + responseString);
}
Or if i use:
using (var webClient = new WebClient())
{
String json = "{\"arguments\": {\"fields\": [ \"id\", \"name\", \"totalSize\" ],\"ids\": [ 7, 10 ]},\"method\": \"torrent-get\",\"tag\": 39693}";
var response = webClient.UploadString("http://192.168.240.171:9091/transmission/rpc", "POST", json);
Console.WriteLine(""+response);
}
I get the following error:
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The Remoteserver returned an exception: (409) conflict.
You must save the X-Transmission-Session-Id provided in the 409 response and resubmit the request with a X-Transmission-Session-Id property added to your request header.
Example in java :
int index = responseString.indexOf("X-Transmission-Session-Id:");
String sessionId = responseString.substring(index + 27, index + 75);
connection.setRequestProperty("X-Transmission-Session-Id", sessionId);

Categories