How to test download api using karate - karate

I have an api for file download (txt,.doc,*.csv) using spring framework in java.i wanted to do acceptance testing using karate .how can i do that.
here is my code
#RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws
IOException {
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}

See line number 16 in this example upload.feature
It is a normal get

Related

Error when running my first pact-jvm test

I'm new to contract Testing Automation and I've written my first test using jvm-pact. I'm using junit5.
Below is the code
#ExtendWith(PactConsumerTestExt.class) #PactTestFor(providerName = "testProvider", port = "8081") public class ConsumerTests {
public static final String EXPECTED_BODY = "/integration/stubs/team_members/SingleTeamMember.json";
#Pact(consumer = "testConsumer" , provider="testProvider")
public RequestResponsePact singleTeamMemberSuccess(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return builder
.given("I have at least one team member")
.uponReceiving("a request for a single team member")
.path("/team-members/1")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body(EXPECTED_BODY)
.toPact();
}
#Test
#PactTestFor(pactMethod = "singleTeamMemberSuccess")
void testSingleTeamMemberSuccess(MockServer mockServer) throws IOException {
HttpResponse httpResponse = (HttpResponse) Request.Get(mockServer.getUrl() + "/team-members/1")
.execute().returnResponse();
assertThat(httpResponse.getStatusLine().getStatusCode(), is(equalTo(200)));
//assertThat(httpResponse.getEntity().getContent(), is(equalTo(TeamMemberSingle200.EXPECTED_BODY_SINGLE_TEAM_MEMBER)) );
}
I'm getting below error on running mvn install
ConsumerTests The following methods annotated with #Pact were not executed during the test: ConsumerTests.singleTeamMemberSuccess If these are currently a work in progress, and a #Disabled annotation to the method
[ERROR] ConsumerTests.singleTeamMemberSuccess:42 ยป NoClassDefFound Could not initialize class org.codehaus.groovy.reflection.ReflectionCache
Please can someone take a look and advise if I'm missing anything important to run the test successfully.
Thanks,
Poonam

Can you debug java code in a Bamboo java spec #BambooSpec main method?

I'm using bamboo and bamboo java-spec using the pipeline as java code in a bitbucket hosted project.
I'm trying to use a json file as a configuration file to specify which stages I want to run in my pipeline.
So I've created a configuration.json file. And i've added the following code in my #BambooSpec annotated PlanSpec class.
private static Map<?, ?> getConfiguration(String configurationFile) throws Exception {
System.out.println("Does this work at all?");
Map<?, ?> map = null;
try {
// create Gson instance
Gson gson = new Gson();
// create a reader
Reader reader = Files.newBufferedReader(Paths.get(configurationFile));
// convert JSON file to map
map = gson.fromJson(reader, Map.class);
// print map entries
for (Map.Entry<?, ?> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
// close reader
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
return map;
}
But bamboo only shows logs for what's run as part of the plan spec. The System.out.println's, are not visable.
Is there a way to debug my code at runtime?
Edit: in the mean time I found out I can just run my code locally in the IDE. And then it'll complain about not finding a .credentials file. But that doesn't matter. I can at least test the code, from before it publishes the plan.

How to read excel file in cucumber project?

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.

Spring Data Rest Content Type

I am writing unit tests for my application with Spring Data Rest MongoDB. Based on Josh's "Building REST services with Spring" get start guide, I have the following test code:
#Test
public void readSingleAccount() throws Exception {
mockMvc.perform(get("/accounts/"
+ this.account.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.id", is(this.account.getId())))
.andExpect(jsonPath("$.email", is(this.account.getEmail())))
.andExpect(jsonPath("$.password", is(this.account.getPassword())));
}
And this test fails on the content type.
Content type expected:<application/json;charset=UTF-8> but was: <application/hal+json>
Expected :application/json;charset=UTF-8
Actual :application/hal+json
I don't see MediaType come with HAL. Is the content type defined in another class?
Had the same Problem when not using tomcat (which is configured to return utf-8 using Spring Boot). The solution is to set the accept header in your GET request so the response gets the correct content type:
private MediaType contentType = new MediaType("application", "hal+json", Charset.forName("UTF-8"));
and in your request, do
#Test
public void readSingleAccount() throws Exception {
mockMvc.perform(get("/accounts/"
+ this.account.getId()).**accept(contentType)**)
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.id", is(this.account.getId())))
.andExpect(jsonPath("$.email", is(this.account.getEmail())))
.andExpect(jsonPath("$.password", is(this.account.getPassword())));
}

Programmatically upload synonyms to google search api using java

I'm having issues figuring out how to programmatically upload synonyms to the google search api from my server using java.
1. The Authorization: The description of how to do a server to google api is explained here. Where can I find a simple example of this using java?
2. Upload synonyms: I have created the xml to be uploaded, explained here. I am not able to see how I actually upload this to the google-api. Is there an example of how this is done?
1. The Authorization
public static String getAuthorizationToken() throws IOException, HttpException{
PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin");
method.addParameter("accountType", "HOSTED_OR_GOOGLE");
method.addParameter("Email", "my#gmail.com");
method.addParameter("Passwd", "myPassword");
method.addParameter("service", "cprose");
method.addParameter("source", "mySource");
String response = executeMethodAsString(method);
return retrieveAuthFromResponse(response);
}
2. Upload synonym
public static String updateSynonyms(String authToken, String xml) throws HttpException, IOException{
PostMethod method = new PostMethod("http://www.google.com/cse/api/default/synonyms/abcdefg1234");
method.addRequestHeader("Content-Type", "text/xml");
method.addRequestHeader("Authorization", "GoogleLogin auth=" + authToken);
RequestEntity entitiy = new StringRequestEntity(xml, "text/xml", "utf-8");
method.setRequestEntity(entitiy);
return executeMethodAsString(method);
}