Laravel dusk if browser->assertSee then do this - laravel

Is there a way to proceed with a test even if assertSee returns with an error.
This is my current code:
$browser->visit('https://urltotest.co.uk/find-an-engineer/')
->type("EngineerId", $engineerId)
->click('#checkEngineer');
$test = $browser->assertSee("Engineer cannot be found");
What I would like to be able to do is go:
if ($test == false) {
return false;
} else {
return $browser->text('.engineer-search-results-container .search-result .col-md-8 .row .col-xs-10 h3');
}
But when the assertSee fails all I get back is:
Did not see expected text [Engineer cannot be found] within element [body].
As an exception. Any way I can proceed if it can't find that element?

You should be able to achieve this using a try catch to catch the exception:
try {
$browser->assertSee("Engineer cannot be found");
} catch(\Exception $e) {
return false;
}
To note, I do not know if there is a method such as $browser->fail() (like phpunit's $this->fail()) which will fail the test for you.

Related

Laravel 8 - Conditionally remember a value in cache [duplicate]

I'm developing one of my first applications with the Laravel 4 framework (which, by the way, is a joy to design with). For one component, there is an AJAX request to query an external server. The issue is, I want to cache these responses for a certain period of time only if they are successful.
Laravel has the Cache::remember() function, but the issue is there seems to be no "failed" mode (at least, none described in their documentation) where a cache would not be stored.
For example, take this simplified function:
try {
$server->query();
} catch (Exception $e) {
return Response::json('error', 400);
}
I would like to use Cache::remember on the output of this, but only if no Exception was thrown. I can think of some less-than-elegant ways to do this, but I would think that Laravel, being such an... eloquent... framework, would have a better way. Any help? Thanks!
This is what worked for me:
if (Cache::has($key)) {
$data = Cache::get($key);
} else {
try {
$data = longQueryOrProcess($key);
Cache::forever($key, $data); // only stored when no error
} catch (Exception $e) {
// deal with error, nothing cached
}
}
And of course you could use Cache::put($key, $data, $minutes); instead of forever
I found this question, because I was looking for an answer about this topic.
In the meanwhile I found a solution and like to share it here:
(also check out example 2 further on in the code)
<?php
/**
* Caching the query - Example 1
*/
function cacheQuery_v1($server)
{
// Set the time in minutes for the cache
$minutes = 10;
// Check if the query is cached
if (Cache::has('db_query'))
{
return Cache::get('db_query');
}
// Else run the query and cache the data or return the
// error response if an exception was catched
try
{
$query = $server->query(...);
}
catch (Exception $e)
{
return Response::json('error', 400);
}
// Cache the query output
Cache::put('db_query', $query, $minutes);
return $query;
}
/**
* Caching the query - Example 2
*/
function cacheQuery_v2($server)
{
// Set the time in minutes for the cache
$minutes = 10;
// Try to get the cached data. Else run the query and cache the output.
$query = Cache::remember('db_query', $minutes, function() use ($server) {
return $server->query(...);
});
// Check if the $query is NULL or returned output
if (empty($query))
{
return Response::json('error', 400);
}
return $query;
}
I recommend you to use Laravel's Eloquent ORM and/or the Query Builder to operate with the Database.
Happy coding!
We're working around this by storing the last good value in Cache::forever(). If there's an error in the cache update callback, we just pull the last value out of the forever key. If it's successful, we update the forever key.

Is there any way to verify dynamic pop-up that does not appear everytime

var name = element(by.xpath("//p[contains(text(),'We will be adding this information')]"));
if ( browser.isElementPresent(name)) {
try {
element(by.xpath("//button[#class='ok-btn']")).click();
} catch (error) {
console.log('Not able to click on duplicate pop-up '+error);
}
} else {
console.log('Fresh');
}
Above code works perfectly fine in Protractor jasmine framework, if popup appears but it fails when pop-up doesn't appear and scripts execution stops there.
Popup comes only when certain condition matches.
Can you try this using the elementFinder method isPresent() instead of the browser method.
const name = element(by.xpath("//p[contains(text(),'We will be adding this information')]"));
if (name.isPresent()) {
try {
element(by.xpath("//button[#class='ok-btn']")).click();
} catch (error) {
console.log('Not able to click on duplicate pop-up '+error);
}
} else {
console.log('Fresh');
}

How to handle 'throw new DecryptException('The payload is invalid.')' on Laravel

I have small Laravel project working on Crypt class. It work fine for both Crypt::encrypt(..) and Crypt::decrypt(..). But I have problem if I directly change on crypted value then try to capture exception. For example, my crypted value is
zczc1234j5j3jh38234wsdfsdf214
Then I directly add some words as below.
zczc1234j5j3jh38234wsdfsdf214_addsometext
I try to decrypt and get error as below
throw new DecryptException('The payload is invalid.')
So, I try to capture exception with render method.
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Contracts\Encryption\DecryptException) {
dd("error");
return route('login')->withError('Your DB may be hacked');
}
return parent::render($request, $exception);
}
I do not known why method not fire, Appreciated&thanks for all comment.
You should handle this with
use Illuminate\Contracts\Encryption\DecryptException;
try {
$decrypted = decrypt($encryptedValue);
} catch (DecryptException $e) {
//
}
check https://laravel.com/docs/5.8/encryption

Laravel custom error page if authorization fails

I am trying to show a custom 403 file in laravel when authorization fails in my edit request.
I tried forbiddenResponse() but as it turns out it has been eliminated.
Then I tried failedauthorization() but this does not redirect as well and allows me to edit.
here is my request file
public function authorize()
{
$job_posting_id = $this->route('id');
$job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();
if($job_posting){
return true;
}
return false;
}
public function failedAuthorization()
{
return redirect('errors.dashboard.parent.403');
}
I have a folder called errors and inside there I have dashboard folder and parent where the error file is located.
How can I redirect to that page if authorization fails?
return abort('403')
Laravel documentation:
https://laravel.com/docs/5.4/errors#http-exceptions
if you make everything like in docs, you'll achieve:
url will stay the same.
template resources/views/errors/403.blade.php will be shown.
aslo response will have Status Code:403 Forbidden
do you want change url into http://www.examlpe.com/error403 ?
return abort('403') doesn't make redirect. It just shows a client that error has occured.
In your case it is easier to show different content in single script, than different scripts. Try to leave single error script as an "entry point". And in that script change output for different users. Imagine that 403.blade.php is a layout for a number of 403 error pages.
In your laravel folder open app/Exceptions/Handler.php paste the following code. That will return custom error page for 403 and 500 error.
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.custom_all', [], 500);
}
if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
return response()->view('errors.custom', [], 403);
}
return parent::render($request, $exception);
}
public function authorize()
{
$job_posting_id = $this->route('id');
$job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();
if($job_posting){
return true;
}
return redirect('/error');
}
public function failedAuthorization()
{
return view('errors.dashboard.parent.403');
}
In your route
Route::get('error', 'YourController#failedAuthorization');
Go to the file Exceptions/Handler.php's report method.
public function report(Exception $e)
{
if(!Auth::check())
{
// Do whatever you want - redirect or return something
}
if($e instanceof HttpException && $e->getStatusCode() == 403)
{
// Do whatever you want - redirect or return something
}
return parent::report($e);
}
And wherever your authorisation failed, just write abort(403)
Hope this will help :)

unassign order status from status

I need to unassign status from state in migration.
$status->setStatus('approved')
->unassignState(Mage_Sales_Model_Order::STATE_NEW)
->assignState(Mage_Sales_Model_Order::STATE_PROCESSING, false)
->save();
If status is assigned to migration, it works. But if state is not assigned, there is exception and
migrations fails.
What is the best way to solve this problem?
The only solution that occured to me, is to create function trapper that catches exception. I this case
it seems that migration works even if status is not assigned to state.
function unAssignStatusFromState($status, $state)
{
try {
$status->unassignState($state);
return true;
} catch(Exception $e) {
return false;
}
}

Resources