For the automated testing of a laravel API I am using the 'laravel' action on github actions, the one made by github actions.
The tests keep failing telling me invalid JSON returned from route, expected response code 200 but got 500, cannot read property status on null and cannot find in json
I'm using laravel sanctum. Could it be a csrf-token problem?
My action yml: https://gist.github.com/I2EJeffrey/77df8faac1b0f86623e2e4449f98d858
My response function:
* success response method.
*
* #return \Illuminate\Http\Response
*/
public function sendResponse($result, $message, $code = 200)
{
$response = [
'success' => true,
'data' => $result, // result is most often one or 2 arrays
'message' => $message,
];
return response()->json($response, 200);
}
Example test:
public function testSuccessfullyCreateAccommodationType()
{
$this->login(); // Login function that lots of tests need.
$response = $this->postJson('/api/v5/accommodations/1/types', ['accommodation_name'=>$this->createName()]);
$response
->assertJsonFragment(['success' => true])
->assertJsonStructure(['success', 'data' =>
[], 'message']); // The array is filled with keys
}
EDIT: 2 errors that I got by using withoutExceptionHandling: https://gist.github.com/I2EJeffrey/da23bfbdf5fba155456bd799a34f6276
EDIT 2: I also get the following warning: TTY mode requires /dev/tty to be read/writable.
EDIT 3: The client model and the client seeder. Whenever I run the tests a mysql docker container starts that gets a db migrated and seeded into it:
https://gist.github.com/I2EJeffrey/39c779df217c9a75a7569f6fa3957d77
https://gist.github.com/I2EJeffrey/41cbbdba8025d38547059d3a6f4d4392
My problem was that the DB didn't get seeded due to not having added $this->call(ClientSeeder::class); to the DatabaseSeeder. Which caused the routes to return null and thus wrong json.
Related
I would like to separate Tests and Data Providers. Using PHP 8 attributes, I cannot get the following test to run when referencing an external Data Provider:
#[Test]
#[DataProviderExternal(RouterDataProvider::class, 'registerGetRouteData')]
public function itRegistersGetRoute(Route $route, array $expectedResult)
{
$this->router->get($route);
$this->assertEquals($expectedResult, $this->router->getRoutes());
}
My data provider class:
class RouterDataProvider
{
public static function registerGetRouteData(): array
{
return [
$route = new Route('/', ['IndexController', 'index']),
[
'GET' => [
'/' => $route,
],
'POST' => []
]
];
}
}
How could I get this test to run with the desired provider method?
By running PHPUnit with the following flags, I was able to see exactly what my issue was:
./vendor/bin/phpunit --display-deprecations --display-warnings --diplay-errors --display-notices
The data set was invalid. Changing the return to yield and updating the return type for the registerGetRouteData method from array to \Generator resolved this.
I was running phpunit with the --testdox flag, so I'm not sure if this is what stopped me seeing any errors initially and assume the test was being skipped.
I use Laravel 9, but it is updated version. I mean, the project was written in laravel 5.4 and updated it to 9 later.
Here's my routes
Route::group(['middleware' => 'locale', 'prefix' => '{locale?}'], function () {
Route::get('/signin', 'Front\UsersController#getSignin');
Route::post('/signin', 'Front\UsersController#postSignin');
});
Here's my tests
public function test_get_signin(){
$response = $this->get('/signin');
$response->assertStatus(302);
}
public function test_post_signin(){
$response = $this->post('am/signin');
$response->assertStatus(302);
}
It works well when I do $this->post('am/signin');
But it is not correct. By the idea it must work when I write $this->post('/signin') without manually adding what should be added automatically. But in fact I get status code 405.
UsersController method for post('/signin) route.
public function postSignin($lang, Request $request){
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if (Auth::validate(['email' => $request['email'],'password' => $request['password']])
|| Auth::validate(['username' => $request['email'],'password' => $request['password']])) {
$verify = User::where(['email'=> $request['email']])->first();
$verify = $verify?$verify:User::where(['username'=> $request['email']])->first();
if($verify->status =='blocked'){
if ($request->expectsJson()) {
return response()->json(array('verify'=> trans('email.profile-block')), 422);
}
}elseif(!$verify->verified){
return response()->json(array('verify'=> trans('validation.active_account').' '
.trans('car.click').' <a class="resend-link" href="/'.$lang.'/resendtoken/'.$verify->email_token
.'">'.trans('car.here1').'</a> '.trans('validation.resend_link')), 422);
}elseif($verify->status =='pending'){
return response()->json(array('verify'=> trans('car.company_napp')), 422);
}elseif($verify->status =='active'){
if(filter_var($request->email, FILTER_VALIDATE_EMAIL)){
$field = 'email';
}else{
$field = 'username';
}
if (Auth::attempt([$field => $request->email, 'password'=>$request->password],$request->remember)) {
UserLoginInfo::create(['user_id'=>Auth::id(),'ip_address'=> $request->ip(),
'info'=>json_encode(self::get_user_info())]);
if ($request->remember) {
User::where('id', Auth::id())->update(array('signed_in_for_remember_me' => Carbon::now()));
}
return Auth::user()->balance;
}
}
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
more short:
$this->get('/signin'); gives status code 302
$this->post('am/signin'); gives status code 302
$this->post('/signin'); gives status code 405
I tried
to use withoutMiddleware() - no positive result.
public function test_get_signin(){
$response = $this->withoutMiddleware('locale')->get('/signin');
$response->assertStatus(302);
}
public function test_post_signin(){
$response = $this->withoutMiddleware('locale')->post('/signin');
$response->assertStatus(302);
}
removed "?" symbol from 'prefix' => '{locale?}' in route group - no use.
commented the : Route::get('/signin', 'Front\UsersController#getSignin'); - no use again.
instead of withoutMiddleware('locale') I also used just a withoutMiddleware() - no use again.
IMPORTANT!
Both routes work well when testing with browser. I mean. User can enter his signin page and also successfully be signed in.
What's going on? How can I force post to work automatically with "/signin"? It's also weird, if I manually have to write "am/" then why it returns 302 instead of 200?
Update
I created a new project and tried to experiment there with route group and get, post methods.
Here's the routes
Route::group(['middleware' => 'locale', 'prefix' => '{locale?}'], function () {
Route::get('/test', function () {
return view('welcome');
});
Route::post('/test', function () {
return view('welcome');
});
});
here's the tests
public function test_1()
{
$response = $this->get('/test');
$response->assertStatus(200);
}
public function test_2()
{
$response = $this->post('/test');
$response->assertStatus(200);
}
test1 and test2, both of them return status 404
And when I use tests like this, I mean, adding a prefix manually
public function test_1()
{
$response = $this->get('/am/test');
$response->assertStatus(200);
}
public function test_2()
{
$response = $this->post('/am/test');
$response->assertStatus(200);
}
both of them return 200
This is good, very good. But why in my situation of my current project I get for get method 200 instead of 404 and for post 405 instead of 404, I don't have an idea. The interesting fact. I commented the whole exceptions Handler.php's code and no use. The get method everytime returns 200 when it must return 404.
Update 2
I've got some new interesting info from my experiments. If in my current project I want to test get method with uri "/signin" without '/am' part with $this->withoutMiddleware(); then I get 500, but without $this->withoutMiddleware(); I get 200
And to know what 500 want to say I used $response->dd(); and got this result
Spatie\LaravelIgnition\Exceptions\ViewException: Undefined variable
$errors in file
C:\xampp\htdocs\dashboard\test\hayvcar\storage\framework\views\7ced869fcb986989ef0f5838d6567d1b5fa4f895.php
on line 1
And if use $this->withoutExceptionHandling(); instead of $response->dd();
We'll get this result
Illuminate\View\ViewException : Undefined variable $errors (View: C:\xampp\htdocs\dashboard\test\hayvcar\resources\views\front\transport\index.blade.php)
C:\xampp\htdocs\dashboard\test\hayvcar\storage\framework\views\7ced869fcb986989ef0f5838d6567d1b5fa4f895.php:1
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\Engines\PhpEngine.php:60
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\Engines\CompilerEngine.php:61
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:139
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:122
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:91
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Http\Response.php:69
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Http\Response.php:35
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:833
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:802
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:725
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:141
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:116
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:726
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:703
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:667
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:656
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:167
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:141
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:116
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:142
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:111
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:526
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:293
C:\xampp\htdocs\dashboard\test\hayvcar\tests\Feature\RoutesTesting.php:1718
Caused by
ErrorException: Undefined variable $errors
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php:255
C:\xampp\htdocs\dashboard\test\hayvcar\storage\framework\views\7ced869fcb986989ef0f5838d6567d1b5fa4f895.php:1
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:107
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:108
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\Engines\PhpEngine.php:58
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\Engines\CompilerEngine.php:61
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:139
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:122
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:91
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Http\Response.php:69
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Http\Response.php:35
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:833
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:802
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:725
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:141
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:116
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:726
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:703
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:667
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:656
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:167
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:141
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:116
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:142
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:111
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:526
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:293
C:\xampp\htdocs\dashboard\test\hayvcar\tests\Feature\RoutesTesting.php:1718
Have you tried delete cached files?
Delete everything in bootstrap\cache and try again on host.
I've explained the whole situation here, for another question, which in this case, it doesn't matter if it's testing or using in browser, when you cache your routes, laravel look for the cached file, instead of defined routes in web.php and api.php.
So if in cached file, you've had route with am/signin then, doesn't matter if you change it to signin or not, in web.php/api.php, it always looking for cached file, which in this case is am/signin.
Temporary questions, answer them by question number :
So you've commented everything in postSignin method, and didn't worked or just a part of it?
You said in browser is working, method is getting $lang from route? because in tests, as far as i can see, you're not passing anything.
Have you tried to change post to patch just for test? (that's because of Patch verb)
You might also try withoutExceptionHandling(); to get more details on error and test output. are you posting full test or just a basic test?
You can add this line to top of your test, $this->withoutExceptionHandling(); and get more details.
Remove $lang from method or just try a new method like below:
public function postSignin(Request $request){
return something or return $this->sendFailedLoginResponse($request); or etc.
}
How did you upgraded your project to Laravel 9? Create a new Laravel project and only test these two routes, get and post.
So I'm making unit tests using laravel, I have 50 tests. but when a test that requires auth, the test automatically fails and raises a 401 error
Expected status code 404 but received 401. Failed asserting that 404 is identical to 401.
for the failed test, like this is the code. I use actingAs to work around auth, but it always fails
public function testDenyNonAdminUserAccess()
{
$user = factory(User::class)->create();
$author = factory(Author::class)->create();
$response = $this
->actingAs($user)
->postJson('/api/books', [
'isbn' => '9788328302341',
'title' => 'Clean code',
'description' => 'Lorem ipsum',
'authors' => [$author->id],
]);
$response->assertStatus(403);
}
even though when I use postman to insert data, it always works and there are no problems. is there any solution?
I also put the middleware in the controller
public function __construct()
{
$this->middleware(['auth:api', 'auth.admin'])->except('index');
}
is there any solution?
To me, It seems there is no user in your memory database.
Try this one to check whether there are users saved in your DB or not.
User::factory(10)->create();
$this->assertEquals(10, User::get()->count());
If it is, try to login a specific user like this:
$user = User::find(1);
$this->actingAs($user);
I am a newbie in PHP.
I created a Laravel project using *composer**.
My controller has two endpoint uploadFile and testpost:
public function uploadFile(Request $request) {
//there are more code about reading uploaded file here. Everything is OK here.
$request = Request::create('/api/testpost', 'POST',
[],[],[],[],'{"this is" : "my test content"}');
return Route::dispatch($request);
}
public function testpost(Request $request){
Log::info($request->all());
return response()->json(["title"=>"this is the test get method"]);
}
uploadFile is invoked by POST action from a form which carries an uploaded JSON file.
I want to call testpost inside of uploadFile method using Request::create(...) and Route::dispatch(...).
testpost is invoked however the body of request is not as expected. The log file shows me that $request->all() does not return the request body which I expect to be {"this is" : "my test content"}.
My log file:
[2019-02-23 12:16:47] local.INFO: array (
'_token' => 'JzQjclRD4WaTkezqLxlU48D1dM7S3X2X3hok3kr4',
'employee_file' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'test_input_file.txt',
'mimeType' => 'text/plain',
'error' => 0,
'hashName' => NULL,
)),
)
What wrong in my code? API invocation or request body retrieval?
I know that we can call testpost method directly instead of calling API. However, I ultimate purpose is to know how to call an internal API.
You don't need to use internal API calls for this.
If both methods are in the same class you can invoke directly with
$this->methodName($args);
and it will return the result directly to the calling function. (provided you have a return statement in the method you are invoking)
i recently moved from laravel 5.2 to laravel 5.4. In 5.2 all testcases were working fine. After upgrading to new version i am facing issues with testcases. Below is my sample code that was working fine in 5.2.
$params = [
'id' => 'asddsdsd'
];
$response1 = $this->call('GET', '/user/getInfo', $params);
$this->assertArrayHasKey('status', $response1);
$this->assertTrue($response1['status'] == 400);
$params2 = [
'id' => '23'
];
$response2 = $this->call('GET', '/user/getInfo', $params2);
$this->assertArrayHasKey('status', $response2);
$this->assertTrue($response2['status'] == 200);
in laravel 5.2 both used to have seperate response, in first case i used to get Failure response and second case, i was getting Success response.
After upgrading to 5.4, i am gettign same response for two testcases. Basically, the first call response is copied to second response because of calling same URl. This is happening for all the testcases.
Note: I added second case in different method, but still facing the same issue
Can anyone suggest me how to fix this??
Looks like the call() method returns a Response object in 5.2, but a TestResponse object in 5.4. To make your code comparable in 5.4, you could try using the baseResponse property of your TestResponse object:
$this->assertArrayHasKey('status', $response1->baseResponse);
You might also need to separate your 2 requests into separate modular test cases and then link them using #depends annotation.
public function testRequest1()
{
$params = [
'id' => 'asddsdsd'
];
$response1 = $this->call('GET', '/user/getInfo', $params);
//$this->assertWhatever()
return $dataIfYouWantIt
}
/**
* #depends testRequest1
*/
public function testRequest2($dataIfYouWantIt)
{
$params2 = [
'id' => '23'
];
$response2 = $this->call('GET', '/user/getInfo', $params2);
//$this->assertWhatever()
}