Recive CSV by API in Symfony using Postman - api

Im using Symfony3 and i have this route:
/**
* Recive a file
*
* #Route("/get/file", name="get-file")
* #Method("POST")
* #param Request $request
* #return Response
*/
public function getFileAction (Request $request) {
foreach($request->files as $key => $uploadedFile) {
$name = "westSummary".date("Y-m-d")."_".$key.".csv";
$file = $uploadedFile->move($destiny, $name); //Save the file in server, Where $destiny says.
}
return $this->json(array(
'status' => 'success',
'code' => 200,
'data' => $request,
));
}
And i create a Collection in Postman calling this route and that return the JSON object correctly:
But i cant test if the CSV arrives to the request object.
I have tryed this:
But the Response is the same in both cases
- How can i send a CSV to and API using POSTMAN?

If you’re trying to do this via the collection runner, this functionality isn’t supported.
That collection runner option relates to the data file you want to use to populate the request variables and not a file upload.
This is a issue being recently discussed on the Postman GitHub account.
https://github.com/postmanlabs/postman-app-support/issues/3137
To upload a file in the request - You can do this by selecting the form-data option in the request body. There is a text/file dropdown - By selecting file you will get the option to choose one for the request.
One other way that you can achieve this using a collection is by installing Newman and using this to create a script to upload the file during the test run.

Related

How to add an attachment to Testrail using the Testrail API

I have tried the following API endpoint to add an attachment to Testrail via their API.
But it is not very clear how to name the said file attachment (I am using Postman)
API endpoint:
[POST]
https:///{{testrail link}}/index.php?/api/v2/add_attachment_to_result/449
Headers:
{
"Content-Type","value":"multipart/form-data"
}
What must the body params be?
I have currently selected the file and multipart/form-data for Content-type. Please help!
The error right now on Postman :
{
"error": "No file attached or upload size was exceeded."
}
The upload size is just fine (under 256 MB)
using postman you need to pass the file through the body by adding a file type key named 'attachment' and value:{select your file}
eg:
key: attachment | value:myfile.txt
Here is a working Java example - I know it's a little late, but it may be useful for reference:
public void uploadScreenshot(long resultId, String screenshotFile) {
String url = String.format("add_attachment_to_result/%d", resultId);
try {
client.sendPost(url, screenshot);
}
catch(Exception e) {
e.printStackTrace();
}
}
You can add an attachment to various assets within TestRail, in this example I am adding a screenshot to a result, which has to be passed in (when you add a result you can get the JSON response and store the 'id' of the newly created result.

How to obtain response to be used on hooks

I am trying to make a simplified version of test report where I am generating a single HTML file report containing only assertion and error response message when there is any (attempting to not publish all the logs and steps).
I understand that we have hooks in karate. However I have looked for karate objects in the github but unable to found any objects where I can extract the response from (to be passed to the js function called on hook)
What I am doing right now is this:
Config:
//karate-config.js
karate.configure('afterScenario', karate.call('classpath:hooks.js'));
Hook:
//hooks.js
//Looking on how to extract the response and log it here
function(){
var info = karate.tags;
karate.log('Tags', info);
}
Am I missing anything on the karate objects? Or this should be achieved in another way?
Thanks a lot!
Try this:
var response = karate.get('response');
EDIT better example:
Background:
* configure afterScenario = function(){ karate.log('***', karate.get("response.headers['X-Karate']")) }
Scenario:
Given url 'http://httpbin.org'
And path 'headers'
And header X-Karate = 'test'
When method get
# this will fail
Then status 400
I have tried with both karate.get('response') and response directly, and both work. If you use karate.call() pass the response as a parameter.

Using placeholders in feature file of Behat

I have a feature file as below
Feature: Test send API request
In order to test my API
As a Tester
I want to be able to perform HTTP request
Scenario:Sending GET request to activate user after registration api to verify whether the response code is 403 when 'X-Auth-Token' is missing
When I have a request "GET /api/activateuser?token=:tokenhash"
And I set the "Accept" header to "application/json"
And I set the "X-Auth-Token" header to "0125ee8dfe42bafbec95aa0d2676c91d8a780715b76504cf798aae6e74c08a30"
.
.
Scenario:Sending GET request to activate user after registration api to verify whether the response code is 403 when 'X-Auth-Token' is invalid
When I have a request "GET /api/activateuser?token=:tokenhash"
And I set the "Accept" header to "application/json"
And I set the "X-Auth-Token" header to "0125ee8dfe42bafbec95aa0d2676c91d8a780715b76504cf798aae6e74c08a30"
.
.
Scenario:Sending GET request to activate user after registration api to verify whether the response code is 404 when userid is invalid
When I have a request "GET /api/activateuser?token=:tokenhash"
And I set the "Accept" header to "application/json"
And I set the "X-Auth-Token" header to "0125ee8dfe42bafbec95aa0d2676c91d8a780715b76504cf798aae6e74c08a30"
.
.
In the request 'X-Auth-Token' parameter will be same for all scnerios, which will not change frequently. So I was thinking of setting it to some variable and use that variable in the scenarios. But havent found any method to do this in behat. It is okay evenif we can set the value in behat.yml and use it in the scenario, but even that was not possible.
Also i have more than one parameters that needed to be set like this.
So is there any method to set the value once and resuse it in every scenario?
You can use combination of two.
A Background where you run all common steps for all scenarios.
A BeforeFeature hook that prepares your current test scope.
What happens below is this.
#BeforeScenario tag runs prepare() method before everything else to set your variable for current feature session.
Step definitions under Background task run before each scenarios so you don't have to duplicate them in each scenarios.
NOTE: If your X-Auth-Token won't change frequently then just hard-code the value in your FeatureContext file and don't implement step 2 above at all. My example is there to give you an idea of some useful features of Behat.
EXAMPLE
Adjust it for your need!
FeatureContext
namespace Your\Bundle\Features\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
...
class FeatureContext ...
{
private static $xAuthToken;
/**
* #BeforeFeature
*/
public static function prepare()
{
self::setXAuthToken();
}
private static function setXAuthToken()
{
self::$xAuthToken = 123;
}
/**
* #Given /^I set the header "([^"]*)" to "([^"]*)"$/
*/
public function iSetTheHeader($header, $value)
{
// Do whatever you want
}
/**
* #Given /^I send "([^"]*)" request to "([^"]*)"$/
*/
public function iSendRequest($method, $url)
{
// Do whatever you want
}
/**
* #Given /^the X-Auth-Token is available$/
*/
public function theXAuthTokenIsAvailable()
{
echo self::$xAuthToken;
}
}
Feature file
Feature: Shared token
Background: I am common to all scenarios
Given I set the header "Accept" to "application/json"
When I send "GET" request to "/api/hello-world"
Scenario: 1
Given the X-Auth-Token is available
Scenario: 2
Given the X-Auth-Token is available
RESULT

Jsreport : Cannot get certain Respond Header

I am using Jsreport via API.
From the browser, a ajax call is made to jsreport server. The server answers with POST respond with data and a Header tag Permanent-Link which has the file locaton.
Copy paste it to the browser allow me to view the pdf file.
The problem it that I want to view it automatically in success handler of ajax call, but xhr.getRespondHeader() does not allow any other header than Content-Type. The respond header even have "Access-Control-Allow-Origin: *" already.
How can I get the pdf out for user?
You can use official jsreport browser client - http://jsreport.net/learn/browser-client
If it is loaded in the page, opening a report is as simple as this
jsreport.serverUrl = 'http://localhost:3000';
var request = {
template: {
content: 'foo', engine: 'none', recipe: 'phantom-pdf'
}
};
//display report in the new tab
jsreport.render('_blank', request);
You can also check its source code if you are curious how it is handling AJAX
https://github.com/jsreport/jsreport-browser-client-dist

Enable CORS in lumen

I have API developed using lumen. I can get request using postman. But when request using Jquery.ajax it is not working. So I need to know how to enable CORS in lumen API.
Consider creating a CorsMiddleware.php file with the following code. Find detail here.
<?php namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}
After saving it in your middleware folder, enable it by adding it to your bootstap/app.php file, on the list of you middleware like this
$app->middleware([
...
App\Http\Middleware\CorsMiddleware::class // Add this
]);
I hope it helps.
I'd recommend using the CORS package by Barry vd. Heuvel:
https://github.com/barryvdh/laravel-cors#lumen
It has configurable and supports Pre-flight request handling for ajax.
For Enable CORS policy inside Lumen you need to add a package via composer
Run the command for install cors package : composer require nordsoftware/lumen-cors
After that you need to configure service in bootstrap/app.php : $app->register('Nord\Lumen\Cors\CorsServiceProvider');
And Last one for middleware registration for application use :
$app->middleware([
'Nord\Lumen\Cors\CorsMiddleware', // top of all middleware
....... // rest of middlewares
]);
#The Oracle answer works properly to many, the problem is what surfaces as CORS problem might be something else. Please be informed that PHP errors in your code could emerge as CORS problem but it's actually not. Make use of different tools to troubleshoot if it's CORS or not.
For example to prove if it's CORS use postman, ex. GET method should work properly because postman is exempted from CORS as it's not a browser. Refer https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for reference
You may sometimes drop your API url in the browser to check for such errors, if it's a backend error or specifically PHP error it normally displays/outputs on the browser with details like what caused the error and on which line etc. Enable Debugging in PHP if you think it's not enabled.