Karate : How to use response of scenario in afterScenario - configure

What is the best way to use the response of scenario in afterScenario??
Background:
* configure afterScenario = function(response){if(response.key){ karate.log('key is present');} else{karate.log('key is not present');} }
Scenario: get all users
Given path 'users'
When method get
Then status 200

Try function without input params
* configure afterScenario = function(){if(response.key){ karate.log('key is present');} else{karate.log('key is not present');} }
if the response variable available for hooks this should work.

Related

Laravel - Get fragment from URL

I am receiving an auth code from Microsoft that looks like this:
localhost:8000/token#auth=123456
In Laravel I have a route that points to a controller:
Route::get('/token', 'AuthController#getToken');
The function looks like this:
public function getToken(Request $request) {
session([
'request' => $request->fullUrl(),
]);
}
The problem is that fullUrl() returns localhost:8000/token so I can't see the auth token.
Is there a way round this?
Assuming you get that URL as a string, you can use parse_​url to get the fragment part:
<?php
$url = 'localhost:8000/token#auth=123456';
var_dump(parse_url($url, PHP_URL_FRAGMENT));
will output: string(11) "auth=123456"
If you want to get the value after the hash mark (#) as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
So when you call :
localhost:8000/token#auth=123456
Your server get this :
localhost:8000/token
The browser delete everything from the hash (#) of your url, then it pass to the server http process

Test api returns 201 instead 200

I do not understand what happens on an API test (laravel 8).
This call (a very simple put) returns a response 200 , using postman.
The same test using phpunit, returns 201 :
public function testPutOrganizationOk()
{
$organization = Organization::factory()->create();
$superAdmin = User::factory()->create([
'organization_id' => $organization->id,
'role_id' => 'SUPERADMIN'
]);
Sanctum::actingAs($superAdmin);
$organizationToModify = [
'name' => 'mon organization moif',
'contact' => 'contact name modif',
'comment' => 'comment comment comment modif',
'ads_max' => 12345,
'state_id' => 'VALIDATED'
];
$response = $this->putJson($this->getUrl() . '/organizations/' . $organization->id, $organizationToModify);
$response->assertStatus(200);
}
The error is :
Tests\Feature\OrganizationTest::testPutOrganizationOk Expected status code 200 but received 201. Failed asserting that 200 is
identical to 201.
I tried a lot of things , without success. I really do not understand what happens. Any suggestions will be appreciated. Thanks.
EDIT :my controller
public function update(StoreOrganizationRequest $request, Organization $organization)
{
$this->authorize('update', Organization::class);
$organizationUpdated = $this->organizationRepository->updateOrganization($organization, $request->only(['name', 'contact', 'comment', 'ads_max', 'state_id']));
return new OrganizationResource($organizationUpdated);
}
EDIT 7 hours later ;-)
When I replace , in the controller, the return of the resource by a return of a simple json, then I have the same behaviour between postman and phpunit . The api call receives a 200 for the update.
Strange, it means that the problem is around the resource ?
Why a different behavior between postman and phpunit ? Who is right : postman or phpunit ?
The http code 201, it mean created success.
see here developer.mozilla.org
and you able to customize the header code by:
return Response::json(new OrganizationResource($organizationUpdated), 200);
201 Status Code says that you just create an Instance, and
200 Status Code says that already existing Instance has been update
The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI."
I might be wrong but seems like you have created the instance first and trying to modifying it then
Finally, I give up!
I will write the response with a status code like that:
return (new OrganizationResource($organization))->response()->setStatusCode(200);
instead of:
return new OrganizationResource($organization);
it's longer to write, but at least my tests are OK.

laravel api with vue 2 js not returning data - could 'localhost:8000' (or '127.0.0.1:8000') be the issue?

I am using the repo https://github.com/mschwarzmueller/laravel-ng2-vue/tree/03-vue-frontend so I have 100% confidence in the reliability of the code. I can post through the laravel api endpoint through the very simple Vue client, and also through Postman. Through Postman I can retrieve the table data array, but not so in the client app. In POSTMAN:
localhost:8000/api/quotes
works just fine.
IN THE vue 2 js CLIENT APP:
methods: {
onGetQuotes() {
axios.get('http://localhost:8000/api/quotes')
.then(
response => {
this.quotes = (response.data.quotes);
}
)
.catch(
error => console.log(error)
);
}
returns nothing. returning the response to Console.log returns nothing. The Network/XHR tab shows the table data rows, but I am not sure what that means.
I know for sure that this code works for others with their unique api endpoints, which I assume may not use localhost or '127:0.0.1:1080.
Edit: in response to request for more info
public function getQuotes()
{
$quotes = Quote::all();
$response = [$quotes];
return response()->json($response, 200);
}
and the relevant route:
Route::get('/quotes', [
'uses' => 'QuoteController#getQuotes'
]);
Just to confirm: I am using verified github repo code in which the ONLY change is my api endpoint addressas mentioned in the first line of the body of this question. . Note that the Laravel back end is also derived from a related repo in Max's fine tutorial. The running code can be seen at
So I really don't think this is a coding error- but is it a configuration error due to me using local host??
EDIT: It WAS a coding error in the laravel controller as shown below
The reason your code isn't working if because you haven't provided a key for your $quotes in your controller but you're looking for it in your vue file (response.data.quotes).
[$quotes] is essentially [0 => $quotes] so when the json response comes through it be 0: [...] not quotes: [...].
To get this to work you just need to change:
$response = [$quotes];
to:
$response = ['quotes' => $quotes];
Furthermore, just an FYI, you don't need to provide the 200 in response->json() as it's the default and you can just return an array and Laravel automatically return the correct json response e.g.:
public function getQuotes()
{
$quotes = \App\Models\Artist::all();
return compact('quotes'); //<-- This is just another way of writting ['quotes' => $quotes]
}
Obviously, you don't have to if you don't want to.
Hope this helps!

Scrapy check if image response is 404

I want to process image URLs, I enabled and configured as Scrapy Docs; but what happens if the image URL returns 404 or is redirected. I want to log that, save the failed URLs and the HTTP error/redirect code. Where can I put the code to do that?
It is completely wrong to handle that in the pipleline, because the response would go throw all the middlewares back to your spider then to your pipleline, while your purpose is just logging the failure.
You should build your own middleware to handle any HTTP response code.
By default, scrapy allows responses with statues codes between 200 and 300. You can edit that by listing the statue codes that you would like to receive like this:
class Yourspider(spider):
handle_httpstatus_list = [404, 302] #add any other code you need
Then you should build your middleware and add it to your configuration like this:
DOWNLOADER_MIDDLEWARES = {
'myProject.myMiddlewares.CustomSpiderMiddleware': SELECT_NUMBER_SUITS_FOR_YOU,
}
in your CustomSpiderMiddleware check the status like this:
process_spider_input(response, spider):
if response.status == 404
#do what ever you want
You have to create your custom pipeline, inherit it from the Imagepipeline, then override the item_completed method, as mentioned in the documentation
def item_completed(self, results, item, info):
image_paths = [x['path'] for ok, x in results if ok]
if not image_paths:
raise DropItem("Item contains no images")
item['image_paths'] = image_paths
return item
and lastly in the settings.py add your custom pipeline
ITEM_PIPELINES = {
'myproject.mypipeline': 100,
}

Check if post parameters are present

I am currently working on a Magento controller that should handle post requests.
I can check if the request is a POST and extract the parameters but I would like to know if there is a standard way to check if a specific parameter has been passed during the request.
How would you do that?
$email = $this->getRequest()->getPost('email');
OR
$email = isset($_POST['email']) ? $_POST['email'] : null;
Same thing.

Resources