i am using laravel framework ,for testing API's i am using postman.i have one registration api which receives an input and storing the data based on some checks ,it's not passing the condition of $request->has('phone') can you please help me how to resolve this issue..?
UserRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserRequest extends FormRequest
{
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'phone' =>'required|integer'
];
}
}
controller.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
use App\Models\User;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use JWTAuth;
class UserController extends Controller
{
public function register(UserRequest $request){
if($request->has('phone')){
// some logic
}
if($request->has('user_name'){
//some logic
}
}
CURL Request
curl --location --request POST 'http://127.0.0.1:8000/api/register' \
--header 'Cookie: XSRF-TOKEN=eyJpdiI6InlXRkRCSVJyQ2xpWDA3WnZmY3BnMXc9PSIsInZhbHVlIjoiOGM5TnJkUTNHRjBtZk81ZjE2dEo4L29YZ3lkbnVWTWdidmlQb0N0Z29tSERHU1EvaXBXbWlLa3RsdTljVzlrUVNjZU9xSDJPRzJQUXJjSDE5UThCYmtVMDlGV1hONVg2N0s2bWY4bGY2NEhidVczYXlPZVNRSS9zNjlCNWJ0WGIiLCJtYWMiOiI4MjczYzE1ZTAxNDJmYmNiYTI4OTIzZjlhYWIxYzJkMjZmNzk1NDFiOGZlODBiZjFmYmY2NzdjNjNiMTZmY2QyIiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6IkRyUTRVN0RSUStBK2pmakRnUDFmbmc9PSIsInZhbHVlIjoiWlNZWXVhVWlOSXhXOEhoNjNUQktyb1BEaEQvekhaWFphMVk5NVZKaFdzZ2VtL0FqVUlUMXJ4THJLSjdkZHhmYTA1eUUyeVNhdUp6UncwczN2OGZDcTVrOS9WVzJQRUxHbm40cnE3ZjJkd2ZZY0J1UlgvQWdyWTdJMVVnejY0cDgiLCJtYWMiOiJmYzdhZGMzZmY3MWRiYTc1YjZjZThjZWFiMzk0ZTBhMjM3ZGU3OGFjYTJmN2Q3MmU3ZDVlMjYwZTUyM2ZjYjVkIiwidGFnIjoiIn0%3D' \
--form 'phone="56788988"'
dd($request)
Illuminate\Http\Request {#43
#json: null
#convertedFiles: null
#userResolver: Closure($guard = null) {#262
class: "Illuminate\Auth\AuthServiceProvider"
this: Illuminate\Auth\AuthServiceProvider {#150 …}
use: {
$app: Illuminate\Foundation\Application {#2 …}
}
file: "/home/payarc/SHARE-COST/lemonpeak_sharecost/vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
line: "96 to 98"
}
#routeResolver: Closure() {#270
class: "Illuminate\Routing\Router"
this: Illuminate\Routing\Router {#26 …}
use: {
$route: Illuminate\Routing\Route {#250 …}
}
file: "/home/payarc/SHARE-COST/lemonpeak_sharecost/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "691 to 693"
}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#45
#parameters: []
}
+request: Symfony\Component\HttpFoundation\InputBag {#44
#parameters: array:1 [
"phone" => "7901002572"
]
}
+query: Symfony\Component\HttpFoundation\InputBag {#51
#parameters: []
}
+server: Symfony\Component\HttpFoundation\ServerBag {#47
#parameters: array:27 [
"DOCUMENT_ROOT" => "/home/payarc/SHARE-COST/lemonpeak_sharecost/public"
"REMOTE_ADDR" => "127.0.0.1"
"REMOTE_PORT" => "37410"
"SERVER_SOFTWARE" => "PHP 7.4.16 Development Server"
"SERVER_PROTOCOL" => "HTTP/1.1"
"SERVER_NAME" => "127.0.0.1"
"SERVER_PORT" => "8000"
"REQUEST_URI" => "/api/register"
"REQUEST_METHOD" => "POST"
"SCRIPT_NAME" => "/index.php"
"SCRIPT_FILENAME" => "/home/payarc/SHARE-COST/lemonpeak_sharecost/public/index.php"
"PATH_INFO" => "/api/register"
"PHP_SELF" => "/index.php/api/register"
"HTTP_USER_AGENT" => "PostmanRuntime/7.28.4"
"HTTP_ACCEPT" => "*/*"
"HTTP_CACHE_CONTROL" => "no-cache"
"HTTP_POSTMAN_TOKEN" => "a67d63c4-d560-4867-a066-5d9d81c38e99"
"HTTP_HOST" => "127.0.0.1:8000"
"HTTP_ACCEPT_ENCODING" => "gzip, deflate, br"
"HTTP_CONNECTION" => "keep-alive"
"CONTENT_TYPE" => "multipart/form-data; boundary=--------------------------727143787238577144588277"
"HTTP_CONTENT_TYPE" => "multipart/form-data; boundary=--------------------------727143787238577144588277"
"HTTP_COOKIE" => "XSRF-TOKEN=eyJpdiI6ImtJMkhNOXBvbjZYMzNFejRNbUpsemc9PSIsInZhbHVlIjoiT21ScElGOUprdnVVY2MxMFpreEVCVTlzS2RGM09Ed1ZQWk1IYnA3L1ZjK2ZoOXA0eUxwVSthRG53cWRydmVNZEJGNlVDUmM0V1NZTU1VOWNraE9yRWE3dGhLQXFubVZoczZ5TFgzSTlXK2UvUlRsTFpxNzgxeHE1d2loRXdWTnYiLCJtYWMiOiIzNGYyYTZjMWE2NDIxNjYxYTI1Nzc0YTI1OGIxMGRlNDhlOWEyZGVkZmI2ODNiM2M2ZmI4MTM2MjAxZjM0YTg0IiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6IkRqWXVYakNaRXVZdCtpUUlmMExZd1E9PSIsInZhbHVlIjoiZmJsQzVRWEhVM0IwYWVVeTZEMnRnQ3Qva1B6NWZLMkJYZWgvcHZONVYwd3VuZnN6cGYzZVJRMzdsUVZvSlJDR01jd1RxZHRNMCtRY3doZDRFZzlmc1MycTlvbDNKTUcyaE9wb2lZZDJqMTJKNmxZVjRGNVM1YzE5cHhjRklvU3MiLCJtYWMiOiI3MmU1OWJhOGEwNTFmYmE2OWQ4OWI1OGMzYTFiMDAyN2NlNWViY2MyMzBmNmIxODAyZThlODA3Y2NjZTYyYjRlIiwidGFnIjoiIn0%3D"
"CONTENT_LENGTH" => "170"
"HTTP_CONTENT_LENGTH" => "170"
"REQUEST_TIME_FLOAT" => 1655210722.3332
"REQUEST_TIME" => 1655210722
]
}
+files: Symfony\Component\HttpFoundation\FileBag {#48
#parameters: []
}
+cookies: Symfony\Component\HttpFoundation\InputBag {#46
#parameters: array:2 [
"XSRF-TOKEN" => "eyJpdiI6ImtJMkhNOXBvbjZYMzNFejRNbUpsemc9PSIsInZhbHVlIjoiT21ScElGOUprdnVVY2MxMFpreEVCVTlzS2RGM09Ed1ZQWk1IYnA3L1ZjK2ZoOXA0eUxwVSthRG53cWRydmVNZEJGNlVDUmM0V1NZTU1VOWNraE9yRWE3dGhLQXFubVZoczZ5TFgzSTlXK2UvUlRsTFpxNzgxeHE1d2loRXdWTnYiLCJtYWMiOiIzNGYyYTZjMWE2NDIxNjYxYTI1Nzc0YTI1OGIxMGRlNDhlOWEyZGVkZmI2ODNiM2M2ZmI4MTM2MjAxZjM0YTg0IiwidGFnIjoiIn0="
"laravel_session" => "eyJpdiI6IkRqWXVYakNaRXVZdCtpUUlmMExZd1E9PSIsInZhbHVlIjoiZmJsQzVRWEhVM0IwYWVVeTZEMnRnQ3Qva1B6NWZLMkJYZWgvcHZONVYwd3VuZnN6cGYzZVJRMzdsUVZvSlJDR01jd1RxZHRNMCtRY3doZDRFZzlmc1MycTlvbDNKTUcyaE9wb2lZZDJqMTJKNmxZVjRGNVM1YzE5cHhjRklvU3MiLCJtYWMiOiI3MmU1OWJhOGEwNTFmYmE2OWQ4OWI1OGMzYTFiMDAyN2NlNWViY2MyMzBmNmIxODAyZThlODA3Y2NjZTYyYjRlIiwidGFnIjoiIn0="
]
}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49
#headers: array:10 [
"user-agent" => array:1 [
0 => "PostmanRuntime/7.28.4"
]
"accept" => array:1 [
0 => "*/*"
]
"cache-control" => array:1 [
0 => "no-cache"
]
"postman-token" => array:1 [
0 => "a67d63c4-d560-4867-a066-5d9d81c38e99"
]
"host" => array:1 [
0 => "127.0.0.1:8000"
]
"accept-encoding" => array:1 [
0 => "gzip, deflate, br"
]
"connection" => array:1 [
0 => "keep-alive"
]
"content-type" => array:1 [
0 => "multipart/form-data; boundary=--------------------------727143787238577144588277"
]
"cookie" => array:1 [
0 => "XSRF-TOKEN=eyJpdiI6ImtJMkhNOXBvbjZYMzNFejRNbUpsemc9PSIsInZhbHVlIjoiT21ScElGOUprdnVVY2MxMFpreEVCVTlzS2RGM09Ed1ZQWk1IYnA3L1ZjK2ZoOXA0eUxwVSthRG53cWRydmVNZEJGNlVDUmM0V1NZTU1VOWNraE9yRWE3dGhLQXFubVZoczZ5TFgzSTlXK2UvUlRsTFpxNzgxeHE1d2loRXdWTnYiLCJtYWMiOiIzNGYyYTZjMWE2NDIxNjYxYTI1Nzc0YTI1OGIxMGRlNDhlOWEyZGVkZmI2ODNiM2M2ZmI4MTM2MjAxZjM0YTg0IiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6IkRqWXVYakNaRXVZdCtpUUlmMExZd1E9PSIsInZhbHVlIjoiZmJsQzVRWEhVM0IwYWVVeTZEMnRnQ3Qva1B6NWZLMkJYZWgvcHZONVYwd3VuZnN6cGYzZVJRMzdsUVZvSlJDR01jd1RxZHRNMCtRY3doZDRFZzlmc1MycTlvbDNKTUcyaE9wb2lZZDJqMTJKNmxZVjRGNVM1YzE5cHhjRklvU3MiLCJtYWMiOiI3MmU1OWJhOGEwNTFmYmE2OWQ4OWI1OGMzYTFiMDAyN2NlNWViY2MyMzBmNmIxODAyZThlODA3Y2NjZTYyYjRlIiwidGFnIjoiIn0%3D"
]
"content-length" => array:1 [
0 => "170"
]
]
#cacheControl: array:1 [
"no-cache" => true
]
}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/api/register"
#requestUri: "/api/register"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: null
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
In postman headers you have to add Accept as a application\json and select as form-data in body section
After that please verify your passing the has check request key has matched to the form-data one.let me know if this will work
Under Rules of your userRequest.php, u set integer validation but not defined the integer length. for example, if you processing the integer value between 1 to 10, do this
public function rules()
{
return [
'phone' =>'required|integer|between:1,10'
];
}
or you can change
public function register(UserRequest $request){
if($request->has('phone')){
// some logic
}
if($request->has('user_name'){
//some logic
}
to
public function register(Request $request){
if($request->has('phone')){
// some logic
}
if($request->has('user_name'){
//some logic
}
to get your value, but it bypasses the validation
Related
public function test_show_role_should_return_actions()
{
$this->actingAs($this->user, 'api');
$this->withHeaders(['Accept' => 'application/json',])
->get(route('roles.show', ['role' => $this->role->id]))
->assertJsonStructure([
"data" => [
"name",
"actions" => [
"name",
"code"
]
]
]);
}
when I run the test,I have this error:
Tests\Feature\Role\RoleTest::test_show_role_should_return_actions
Failed asserting that an array has the key 'name'.
Even when I remove the "name",I get an error for the "actions" key.
public function test_show_role_should_return_actions()
{
$this->actingAs($this->user, 'api');
$this->getJson(route('roles.show', ['role' => $this->role->id]))
->assertJsonStructure([
'data' => [
'*' => [
'name',
'actions' => [
'*' => [
'name',
'code'
]
]
]
]
]);
}
I'm trying to create a feature test and I'm trying to post to a route, but I'm not hitting that route and what I mean by that
is, when I dd() in that function that I need to get into, I'm not getting the output from the dd() that lets me know that I've hit my function.
Here is my test function
<?php
namespace Tests\Feature;
class CategoryTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$user = User::create([
'name' => 'Test User',
'email' => 'test#test.com'
'password' => bcrypt('password')
]);
$this->actingAs($user, 'web');
}
private function createTestCategory()
{
$category = Category::create([
'name' => 'Category 1'
]);
return $category;
}
public function testCategoryVersion()
{
$category = $this->createTestCategory();
$version = [
'version' => 'v1'
];
$response = $this->call('POST', "/api/project/{$category->id}/version", [
'version' => $version
]);
dd($response);
}
}
and this is what I get in return
Illuminate\Testing\TestResponse^ {#12704
+baseResponse: Illuminate\Http\RedirectResponse^ {#13339
#request: Illuminate\Http\Request^ {#13504
#json: Symfony\Component\HttpFoundation\ParameterBag^ {#14972
#parameters: array:1 [
"version" => array:1 [
"version" => "v1"
]
]
}
#convertedFiles: null
#userResolver: Closure($guard = null)^ {#14453
class: "Illuminate\Auth\AuthServiceProvider"
this: Illuminate\Auth\AuthServiceProvider {#16961 …}
use: {
$app: Illuminate\Foundation\Application {#17080 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
line: "105 to 107"
}
#routeResolver: Closure()^ {#15018
class: "Illuminate\Routing\Router"
this: Illuminate\Routing\Router {#16256 …}
use: {
$route: Illuminate\Routing\Route {#14382 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "655 to 657"
}
+attributes: Symfony\Component\HttpFoundation\ParameterBag^ {#12703
#parameters: []
}
+request: Symfony\Component\HttpFoundation\ParameterBag^ {#14972}
+query: Symfony\Component\HttpFoundation\InputBag^ {#11883
#parameters: []
}
+server: Symfony\Component\HttpFoundation\ServerBag^ {#14949
#parameters: array:19 [
"SERVER_NAME" => "localhost"
"SERVER_PORT" => 80
"HTTP_HOST" => "localhost"
"HTTP_USER_AGENT" => "Symfony"
"HTTP_ACCEPT" => "application/json"
"HTTP_ACCEPT_LANGUAGE" => "en-us,en;q=0.5"
"HTTP_ACCEPT_CHARSET" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
"REMOTE_ADDR" => "127.0.0.1"
"SCRIPT_NAME" => ""
"SCRIPT_FILENAME" => ""
"SERVER_PROTOCOL" => "HTTP/1.1"
"REQUEST_TIME" => 1644936692
"REQUEST_TIME_FLOAT" => 1644936692.2835
"HTTP_CONTENT_LENGTH" => 28
"CONTENT_TYPE" => "application/json"
"PATH_INFO" => ""
"REQUEST_METHOD" => "POST"
"REQUEST_URI" => "/api/project/1/version"
"QUERY_STRING" => ""
]
}
+files: Symfony\Component\HttpFoundation\FileBag^ {#14964
#parameters: []
}
+cookies: Symfony\Component\HttpFoundation\InputBag^ {#16109
#parameters: []
}
+headers: Symfony\Component\HttpFoundation\HeaderBag^ {#11625
#headers: array:8 [
"host" => array:1 [
0 => "localhost"
]
"user-agent" => array:1 [
0 => "Symfony"
]
"accept" => array:1 [
0 => "application/json"
]
"accept-language" => array:1 [
0 => "en-us,en;q=0.5"
]
"accept-charset" => array:1 [
0 => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
]
"content-length" => array:1 [
0 => 28
]
"content-type" => array:1 [
0 => "application/json"
]
"origin" => array:1 [
0 => ""
]
]
#cacheControl: []
}
#content: "{"version":{"version":"v1"}}"
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: array:1 [
0 => "application/json"
]
#pathInfo: "/api/project/1/version"
#requestUri: "/api/project/1/version"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: null
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
#session: Illuminate\Session\Store^ {#11680
#id: "sGsZ8cj5iRPLBjfLT4quiaal9LjdOEJUakzno0CU"
#name: "laravel_session"
#attributes: array:2 [
"error" => "Your account has been disabled. Please contact us at test#test.com"
"_flash" => array:2 [
"new" => array:1 [
0 => "error"
]
"old" => []
]
]
#handler: Illuminate\Session\ArraySessionHandler^ {#11912
#storage: []
#minutes: "120"
}
#started: false
}
#targetUrl: "http://localhost/login"
+headers: Symfony\Component\HttpFoundation\ResponseHeaderBag^ {#14761
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: []
#headerNames: array:5 [
"cache-control" => "Cache-Control"
"date" => "Date"
"location" => "Location"
"content-type" => "Content-Type"
"access-control-allow-origin" => "Access-Control-Allow-Origin"
]
#headers: array:5 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Tue, 15 Feb 2022 14:51:32 GMT"
]
"location" => array:1 [
0 => "http://localhost/login"
]
"content-type" => array:1 [
0 => "text/html; charset=UTF-8"
]
"access-control-allow-origin" => array:1 [
0 => ""
]
]
#cacheControl: []
}
#content: """
<!DOCTYPE html>\n
<html>\n
<head>\n
<meta charset="UTF-8" />\n
<meta http-equiv="refresh" content="0;url='http://localhost/login'" />\n
\n
<title>Redirecting to http://localhost/login</title>\n
</head>\n
<body>\n
Redirecting to http://localhost/login.\n
</body>\n
</html>
"""
#version: "1.1"
#statusCode: 302
#statusText: "Found"
#charset: null
+original: null
+exception: null
}
#streamedContent: null
}
I want to compare two columns of a collection.I don't want to do this in db level, only in collection level.
I have a collection like this (I returned it in array model for readability)
array:3 [
0 => array:5 [
"total_amount" => 200000.0
"admin_max_amount" => "200000000"
]
1 => array:5 [
"total_amount" => 100000.0
"admin_max_amount" => "200000000"
]
2 => array:5 [
"total_amount" => 100000.0
"admin_max_amount" => "0"
]
]
I want to get first of them where total_amount > admin_max_amount.
Here is a more 'Laravel' way to do it:
$items = collect([
[
"total_amount" => 200000.0,
"admin_max_amount" => "200000000",
],
[
"total_amount" => 100000.0,
"admin_max_amount" => "200000000",
],
[
"total_amount" => 100000.0,
"admin_max_amount" => "0",
],
]);
$result = $items->first(function ($item)
{
return (float)$item['total_amount'] > (float)$item['admin_max_amount'];
});
dump($result);
I have this route:
Route::delete('product/{product}/attachments/{attachment}', 'AttachmentsController#destroy');
public function destroy(Product $product, Attachment $attachment)
{
dd($product);
}
and dd shows:
App\Models\Product^ {#1059
#fillable: array:3 [
0 => "title"
1 => "section_id"
2 => "sortOrder"
]
#attributes: []
#original: []
... etc
}
I can't access model data such as $product->title it will return null, so I tried to change destory method to:
public function destroy($product, Attachment $attachment)
{
$product = Product::whereId($product)->firstOrFail();
dd($product);
}
and now I can access/see the model data:
"section_id" => 18
"title" => "test product"
"sortOrder" => 217645360
"created_at" => "2020-05-05 13:34:54"
"updated_at" => "2020-05-05 13:34:54"
]
#original: array:8 [
"id" => 18
"section_id" => 18
"title" => "test product"
"sortOrder" => 217645360
"created_at" => "2020-05-05 13:34:54"
"updated_at" => "2020-05-05 13:34:54"
]
Why doesn't the model binding work? I even tried to add
public function boot()
{
parent::boot();
Route::model('product', App\Models\Product::class);
}
I tried also to do: cache:clear route:clearand composer dumpautoload I cant find why the model binding doesn't work?
class ExampleTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->base_url = config('app.url');
$response = $this->post($this->base_url . '/auth/login', [
'username' => 'root',
'password' => '123',
]);
// how to get the login session cookie?
}
public function testStep1()
{
// how to set the login session to this POST request?
$response = $this->post($this->base_url . '/step1', [
'attr_1' => 'foo',
'attr_2' => 'bar',
]);
...
}
public function testStep2()
{
// how to set the login session to this POST request?
$response = $this->post($this->base_url . '/step2', [
'attr_1' => 'abc',
'attr_2' => 'xyz',
]);
...
}
}
From the sample code above, what I want to achieve is testStep1 & testStep2 must in order (wizard to create something). Thus, I must maintain the same session.
Is it possible to achieve?
Edit 2018-07-10 14:51 UTC+8
I've tried the output after call the /auth/login, the value of $response->headers->getCookies() is
array:1 [
0 => Symfony\Component\HttpFoundation\Cookie {#940
#name: "XSRF-TOKEN"
#value: "eyJpdiI6IjQwUKxYnZlQ0J3N1B0Vkp4VjBEWVE9PSIsInZhbHVlIj782RKOUh2UFhONFwvaVRPUm56YkJ1ekxxSXlCTmtYSFNyRUF3NTdCTWhBMHhEQis1VVU0OUFcL3pKQUcybTFwQjdad1I1em02V1d4bVhDZWR2NFluUTlxdz09IiwibWFjIjoiZWRjYjk2NWI1MTU3YmJlMGEwMDdiNjNkYmVkMjBjMWU3NTRmZjE5NmMyM2EwOTZlNWJmZmYwMmRmYmExMWE1MSJ9"
#domain: null
#expire: 1531218886
#path: "/"
#secure: false
#httpOnly: false
-raw: false
-sameSite: null
}
]
and the value of $response is
Illuminate\Foundation\Testing\TestResponse {#843
+baseResponse: Illuminate\Http\RedirectResponse {#1040
#request: Illuminate\Http\Request {#856
#json: null
#convertedFiles: null
#userResolver: Closure {#916
class: "Illuminate\Auth\AuthServiceProvider"
this: Illuminate\Auth\AuthServiceProvider {#52 …}
parameters: {
$guard: {
default: null
}
}
use: {
$app: Illuminate\Foundation\Application {#19 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
line: "85 to 87"
}
#routeResolver: Closure {#860
class: "Illuminate\Routing\Router"
this: Illuminate\Routing\Router {#167 …}
use: {
$route: Illuminate\Routing\Route {#204 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "527 to 529"
}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#870
#parameters: []
}
+request: Symfony\Component\HttpFoundation\ParameterBag {#867
#parameters: array:2 [
"username" => "root"
"password" => "123"
]
}
+query: Symfony\Component\HttpFoundation\ParameterBag {#911
#parameters: []
}
+server: Symfony\Component\HttpFoundation\ServerBag {#871
#parameters: array:17 [
"SERVER_NAME" => "localhost.com"
"SERVER_PORT" => 80
"HTTP_HOST" => "localhost.com"
"HTTP_USER_AGENT" => "Symfony/3.X"
"HTTP_ACCEPT" => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
"HTTP_ACCEPT_LANGUAGE" => "en-us,en;q=0.5"
"HTTP_ACCEPT_CHARSET" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
"REMOTE_ADDR" => "127.0.0.1"
"SCRIPT_NAME" => ""
"SCRIPT_FILENAME" => ""
"SERVER_PROTOCOL" => "HTTP/1.1"
"REQUEST_TIME" => 1531204718
"PATH_INFO" => ""
"REQUEST_METHOD" => "POST"
"CONTENT_TYPE" => "application/x-www-form-urlencoded"
"REQUEST_URI" => "/auth/login"
"QUERY_STRING" => ""
]
}
+files: Symfony\Component\HttpFoundation\FileBag {#878
#parameters: []
}
+cookies: Symfony\Component\HttpFoundation\ParameterBag {#869
#parameters: []
}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#913
#headers: array:6 [
"host" => array:1 [
0 => "localhost.com"
]
"user-agent" => array:1 [
0 => "Symfony/3.X"
]
"accept" => array:1 [
0 => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
]
"accept-language" => array:1 [
0 => "en-us,en;q=0.5"
]
"accept-charset" => array:1 [
0 => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
]
"content-type" => array:1 [
0 => "application/x-www-form-urlencoded"
]
]
#cacheControl: []
}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/auth/login"
#requestUri: "/auth/login"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Illuminate\Session\EncryptedStore {#924
#encrypter: Illuminate\Encryption\Encrypter {#919
#key: b"A╦k>ú8f\x10─ÌÜ8ØýxK\x01²┬Íî·»├\x1A³0▒S┘Ì"
#cipher: "AES-256-CBC"
}
#id: "XPMgecNkwFHbZbujhiuEaBqgMqFTLIqsuIzyvXv"
#name: "laravel_cookie"
#attributes: array:11 [
"_token" => "5lcOcLk9AqvSlWyLdHMKba1lJQ1UqD2rBBVCSav"
"locale" => "en"
"_previous" => array:1 [
"url" => "http://localhost.com/auth/login"
]
"_flash" => array:2 [
"old" => []
"new" => []
]
"sess_user_id" => 123
"sess_user_firstname" => "Foo"
"sess_user_lastname" => "Bar"
"sess_role" => "admin"
"login_web_59ba36add234f940abcf014c987ea4e30989d" => 123
]
#handler: Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler {#925
-sessionName: null
-prefetchId: null
-prefetchData: null
-newSessionId: null
-igbinaryEmptyData: "\x00\x00\x00\x02\x14\x00"
}
#started: false
}
#locale: null
#defaultLocale: "en"
-isHostValid: true
-isForwardedValid: true
basePath: ""
format: "html"
}
#session: Illuminate\Session\EncryptedStore {#924}
#targetUrl: "http://localhost.com/dashboard"
+headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1039
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: array:1 [
"" => array:1 [
"/" => array:1 [
"XSRF-TOKEN" => Symfony\Component\HttpFoundation\Cookie {#940
#name: "XSRF-TOKEN"
#value: "eyJpdiI6IjVyVmRNSmlcL1dYK0VOdiwj8RxamZBPT0iLCJ2YWx1ZSI6IjNSQWFzcVllSEIrSYwZnNNbk1vZ1NERVc2UVdJeGs91D6UG5hNGlHUmRnendJOUVtUnA3Rnk0TnVLYmI5UnJXSTlZR3dxS0wxMElmOFlaWDMzdG9RPT0iLCJtYWMiOiI0ZTZlNTAwNjFkZWFkOTEwN2M1Y2EzMGRjOWMzMmU4NzEzNmM5NWU2MzhhODFjOGJkYTU0YmZlMTM3M2ExNmE3In0="
#domain: null
#expire: 1531219118
#path: "/"
#secure: false
#httpOnly: false
-raw: false
-sameSite: null
}
]
]
]
#headerNames: array:5 [
"cache-control" => "Cache-Control"
"date" => "Date"
"location" => "Location"
"content-type" => "Content-Type"
"set-cookie" => "Set-Cookie"
]
#headers: array:4 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Tue, 10 Jul 2018 06:38:38 GMT"
]
"location" => array:1 [
0 => "http://localhost.com/dashboard"
]
"content-type" => array:1 [
0 => "text/html; charset=UTF-8"
]
]
#cacheControl: []
}
#content: """
<!DOCTYPE html>\n
<html>\n
<head>\n
<meta charset="UTF-8" />\n
<meta http-equiv="refresh" content="0;url=http://localhost.com/dashboard" />\n
\n
<title>Redirecting to http://localhost.com/dashboard</title>\n
</head>\n
<body>\n
Redirecting to http://localhost.com/dashboard.\n
</body>\n
</html>
"""
#version: "1.1"
#statusCode: 302
#statusText: "Found"
#charset: null
+original: null
+exception: null
}
}
So obviously, the session cookie is not in $response->headers->getCookies(), and I don't use actingAs() is because after user successful login, will set a few session values, i.e. sess_user_id, sess_user_firstname, sess_user_lastname, sess_role...
For the first case I would just make a post request and check if the cookie is present or not.
$response = $this->post($this->base_url . '/auth/login', [
'username' => 'root',
'password' => '123',
]);
$response->assertCookieNotExpired($cookieName);
Note: you can get cookies from headers using. $response->headers->getCookies(); but I don't think we need them in our case.
Now we know our authentication works we can use Laravel actingAs helper method for authentication and then make requests as follows.
$user = // get your user.
$response = $this->actingAs($user)->post($this->base_url . '/step1', [
'attr_1' => 'foo',
'attr_2' => 'bar',
]);
Make all kinds of assertion you like (check for cookies, sessions whatever you like)
$response->assertSessionHas($key, $value);
Before we move to the third case you should know that it's better to test each section separately. In simple words your tests shouldn't depend on each other, so what we can do for the third case? We know our third case depends on the second and we have already the tested the previous processes. Now we just want to test if our third case is working or not. So why not we add the session values required for this request ourselves using Laravel helper withSession.
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->post($this->base_url . '/step2', [
'attr_1' => 'abc',
'attr_2' => 'xyz',
]);
Now you can again make assertions. Check list of all available assertions.
Install Mockery Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit
composer require mockery/mockery --dev
LoginController
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
// Get the currently authenticated user...
$user = Auth::user();
return redirect()->route('profile');
}else{
return redirect()->intended('loginform');
}
}
Example Test
public function testLoginSuccess()
{
$credential = [
'email' => 'xxx',
'password' => 'yyy'
];
Auth::shouldReceive('attempt')->once()->withAnyArgs()->andReturn(true);
Auth::shouldReceive('user')->once()->withAnyArgs()->andReturn(true);
$response = $this->post('/login',$credential);
$response->assertRedirect('/profile');
}
This example show you how to mock Auth Facades in unit test.
Auth::attempt return true
Auth::user return true
You can use Mockery to mock object as you want.
Check phpunit.xml, by default the value of SESSION_DRIVER is set 'array', change it to 'file'