php laravel api test always returns 404 in the second call after a first successful call - codeception

I am making an API test function that includes sending a post request twice in the same test.
the first request is successful and has no problem, and i can assert the response without any issue. however, in the second request, the route is not found and the response returns 404 error right away. even though i use the same request.
here is how the test function looks like:
public function tesAbc(\ApiTester $I)
{
$I->haveHttpHeader('Accept', 'application/json');
$request = [
'username' => 'abc',
'password' => 'testABc',
'data' => [
'param1' => '123',
'param2' => '456'
]
];
/* the first request, response always 200 */
$I->sendPOST('confirmation/slot', $request);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
/* the second request, response always 404 */
$I->sendPOST('confirmation/slot', $request);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
$I->dontSeeResponseJsonMatchesJsonPath('$.data[*]');
}

The problem is that you used relative URI confirmation/slot.
The first request goes to /confirmation/slot then second request is relative to that and it goes to `/confirmation/confirmation/slot.
Solution is simple, use leading / in URI:
$I->sendPOST('/confirmation/slot', $request);

Related

How to read the contents of a Post request on Postman?

In the systems I am testing, there are cases that the response informs 200 (ok), but the content may indicate an error in the internal validations of the backend service. How can I read the contents of the response with Postman and schedule a successful validation if this service error code comes as expected?
You can use the tests tab in Postman to run checks on the body (JSON and XML). There are snippets which show you the syntax. You can adapt them to check for the element of the response body which indicates the error.
Postman has a tab called "Tests" where you can provide you test script for execution.
If you want to validate your request responded with 200 OK, following is the script
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
If you want to validate the response contains any specified string,
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
In your case am assuming the above script can be used. In case the response body is JSON,
pm.test("JSON Body match", function () {
var respBody = pm.response.json();
pm.expect(respBody.<json node>).is.to.equal("Error_name");
});
Example JSON response body
{
"id" : 100,
"status" : "Bad Request"
}
pm.test("JSON Body matches string", function () {
var respBody = pm.response.json();
pm.expect(respBody.status).is.to.equal("Bad Request");
});

express cookie not set in response, not shown in next request

There are several moving parts, so it's difficult to know what to debug here.
I have a web application on one localhost port, and a simple helper on another localhost running an express NodeJS application with a couple of endpoints.
The basic issue I'm seeing is that my cookie session on the express application is empty for subsequent calls, and I don't even see it being sent back in the first response.
The setup
The client makes basic GET ajax calls (jQuery at the moment) to the express application.
I have set http allowance for session cookies:
app.use(cookieSession({
name: 'session',
keys: ['abcdefg'],
maxAge: 24 * 60 * 60 * 1000, // 24 hours,
secure: false
}))
I have set cross-origin requests on the express application:
app.use((req, res, next) => {
const corsWhitelist = [
'http://localhost:8000',
'http://localhost:8777'
];
if (corsWhitelist.indexOf(req.headers.origin) !== -1) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
}
next();
});
And the requests are completed seemingly without issue, as the response bodies are what I expect.
The meat of the request handler is:
app.get('/initialize', (req, res) => {
console.log(req.session);
//if we have a session with verified status
if (req.session.hasOwnProperty("userId") && req.session.userId){
res.send({result: 'OK', message: 'good - 1'});
return;
}
const id = uuid.v4();
req.session.userId = id;
res.send({result: 'OK', message: 'good - 2'});
return;
});
I always always get the second response 'good - 2' from the ajax call. The log always shows the session as {}
It's probably worth noting that Chrome devtools shows "Provisional headers are shown" for the request headers, and set-cookie is not shown in the response headers. The AJAX is a simple GET to an endpoint with one parameter passed in.
Update
Just now occurred to me to try without using the AJAX call. Hitting the URL directly gets the cookie and keeps the session as expected. That will probably change the dynamic of the issue.
The fix was to use jsonp request/response to get cookies to pass around the ajax call. Nothing to do with express really.
https://samueleresca.net/2015/07/json-and-jsonp-requests-using-expressjs/

How can I mock an http error response in dart?

So I'm doing some unit tests for my http provider.
In one of my tests I want to verify that when I do a POST call and I get an error response with status 409 I do then a call to PATCH and everything works.
This is my code
Future<IdentityResponse> _createUser(dynamic body) {
return http
.post(api, body: json.encode(body))
.catchError((err) {
return _isStatusCode(err, 409) ? _patchUser(body) : throw (err);
});
}
I'm using mockito, and tried first returning a Response like this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) async => Response("user exists", 409);
And it works... kind of. I catch the error, but then I can't get the status code, I get only the message 'user exists'
If I change to the structure that the backend returns, which is {"error": { "code": 409 }} and I do this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) async => Response(json.encode(fakeErrorResponse), 409);
Then my catch does not work anymore (??)
I tried then to return an error instead of a response, like this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) => Future.error(fakeErrorResponse));
Now my catch works again, but the error I get is an _ImmutableMap and I see no easy way to retrieve my data from there.
How can I mock an http error that returns the body that I want and not a simple String?
Thanks

Passport - "Unauthenticated." - Laravel 5.3

I hope someone could explain why I'm unauthenticated when already has performed a successfull Oauth 2 authentication process.
I've set up the Passport package like in Laravel's documentation and I successfully get authenticated, receives a token value and so on. But, when I try to do a get request on, let say, /api/user, I get a Unauthenticated error as a response. I use the token value as a header with key name Authorization, just as described in the docs.
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware("auth:api");
This function is suppose to give back my self as the authenticated user, but I'm only getting Unauthenticated. Likewise, if I just return the first user, I'm again getting Unauthenticated.
Route::get('/test', function(Request $request) {
return App\User::whereId(1)->first();
})->middleware("auth:api");
In a tutorial from Laracast, guiding through the setup of Passport, the guider doesn't have the ->middleware("auth:api") in his routes. But if its not there, well then there's no need for authentication at all!
Please, any suggestions or answers are more then welcome!
You have to set an expiration date for the tokens you are generating,
set the boot method in your AuthServiceProvider to something like the code below and try generating a new token. Passports default expiration returns a negative number
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(15));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
Check your user model and the database table, if you have modified the primary id field name to say something other than "id" or even "user_id" you MIGHT run into issues. I debugged an issue regarding modifying the primary id field in my user model and database table to say "acct_id" instead of keeping it as just "id" and the result was "Unauthenticated" When I tried to get the user object via GET /user through the auth:api middleware. Keep in mind I had tried every other fix under the sun until I decided to debug it myself.
ALSO Be sure to UPDATE your passport. As it has had some changes made to it in recent weeks.
I'll link my reference below, it's VERY detailed and well defined as to what I did and how I got to the solution.
Enjoy!
https://github.com/laravel/passport/issues/151
I had this error because of that I deleted passport mysql tables(php artisan migrate:fresh), php artisan passport:install helps me. Remember that after removing tables, you need to re-install passport!
I had exactly the same error because I forgot to put http before the project name.
use Illuminate\Http\Request;
Route::get('/', function () {
$query = http_build_query([
'client_id' => 3,
'redirect_uri' => 'http://consumer.dev/callback',
'response_type' => 'code',
'scope' => '',
]);
// The redirect URL should start with http://
return redirect('passport.dev/oauth/authorize?'.$query);
});
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://passport.dev/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 3,
'client_secret' => 'M8y4u77AFmHyYp4clJrYTWdkbua1ftPEUbciW8aq',
'redirect_uri' => 'http://consumer.dev/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});

CAS authentication and redirects with jQuery AJAX

I've got an HTML page that needs to make requests to a CAS-protected (Central Authentication Service) web service using the jQuery AJAX functions. I've got the following code:
$.ajax({
type: "GET",
url: request,
dataType: "json",
complete: function(xmlHttp) {
console.log(xmlHttp);
alert(xmlHttp.status);
},
success: handleRedirects
});
The request variable can be either to the CAS server (https://cas.mydomain.com/login?service=myServiceURL) or directly to the service (which should then redirect back to CAS to get a service ticket). Firebug shows that the request is being made and that it comes back as a 302 redirect. However, the $.ajax() function isn't handling the redirect.
I wrote this function to work around this:
var handleRedirects = function(data, textStatus) {
console.log(data, textStatus);
if (data.redirect) {
console.log("Calling a redirect: " + data.redirect);
$.get(data.redirect, handleRedirects);
} else {
//function that handles the actual data processing
gotResponse(data);
}
};
However, even with this, the handleRedirects function never gets called, and the xmlHttp.status always returns 0. It also doesn't look like the cookies are getting sent with the cas.mydomain.com call. (See this question for a similar problem.)
Is this a problem with the AJAX calls not handling redirects, or is there more going on here than meets the eye?
There is indeed more going on than meets the eye.
After some investigation, it appears that jQuery AJAX requests made in this way fail if they're not made to the same subdomain. In this example, requests are being made to cas.mydomain.com from a different server. Even if it is also on mydomain.com, the request will fail because the subdomain doesn't match.
jQuery AJAX does handle redirects properly. I did some testing with scripts on the same subdomain to verify that. In addition, cookies are also passed as you would expect. See my blog post for this research.
Also keep in mind that the protocols must be the same. That is, since cas.mydomain.com is using HTTPS, the page from which you are calling it must also be on HTTPS or the request will fail.
Cross domain calls are not allowed by the browser. The simplest way would be to use JSONP on the mobile application end and use a CAS gateway to return a ticket.
You can make such cross-domain AJAX calls with a PHP proxy. In the following example the proxy is capable of calling REST web services that return a JSON string.
wsproxy.php
<?php
if (!isset($_POST["username"]) || !isset($_POST["password"]))
die("Username or password not set.");
$username = $_POST["username"];
$password = $_POST["password"];
if (!isset($_GET['url'])
die("URL was not set.");
//Rebuild URL (needed if the url passed as GET parameter
//also contains GET parameters
$url = $_GET['url'];
foreach ($_GET as $key => $value) {
if ($key != 'url') {
$url .= "&" . $key . "=" . $value;
}
}
//Set username and password for HTTP Basic Authentication
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode("$username:$password")
)
));
//Call WS
$json = file_get_contents($url, false, $context);
// Read HTTP Status
if(isset($http_response_header[0]))
list($version,$status_code,$msg) =
explode(' ',$http_response_header[0], 3);
// Check HTTP Status
if($status_code != 200) {
if($status_code == 404) {
die("404 - Not Found");
} else {
die($status_code . " - Error");
}
}
//Add content header
header('Content-Type: application/json');
print $json;
?>
URL usage
http://yourDomain.com/wsproxy.php?url=https://wsToCall.com/ws/resource?param1=false&param2=true
jQuery $.ajax or $.post
Note that if you don't need to pass username and password, then a GET request is sufficient.
$.ajax({
type : "POST",
url : "http://" + document.domain +
"/wsproxy.php?url=http://wsToCall.com/ws/resource?param1=false&param2=true",
dataType : "json",
success : handleRedirects,
data: { username: "foo", password: "bar" }
});