I want to test that the job has been released back onto the queue in certain circumstances.
This is my job class:
class ChargeOrder extends Job
{
use InteractsWithQueue, SerializesModels;
/**
* The order model which is to be charged
*/
protected $order;
/**
* The token or card_id which allows us to take payment
*/
protected $source;
/**
* Create a new job instance.
*
* #param App\Order $order;
* #param string $source;
* #return array
*/
public function __construct($order, $source)
{
$this->order = $order;
$this->source = $source;
}
/**
* Execute the job.
*
* #return void
*/
public function handle(Charge $charge)
{
$result = $charge->execute($this->source, $this->order->totalInclVat());
$exception_errors = config('payment.errors.exception_errors');
// If we have an error that isn't caused by the user (anything but a card error)
// We're going to notify ourselves via slack so we can investigate.
if (array_key_exists('error', $result) && in_array($result['error']['code'], array_keys(config('payment.errors.other_error'))))
{
$client = new Client(config('services.slack.channels.payment_errors.url'), config('services.slack.channels.payment_errors.settings'));
$client->send(app()->environment() . ": " . $result['error']['code']);
}
// If the error is in the list of errors that throw an exception, then throw it.
if (array_key_exists('error', $result) && (in_array($result['error']['type'], $exception_errors) || in_array($result['error']['code'], $exception_errors)))
{
$status_code = config('payment.errors')[$result['error']['type']][$result['error']['code']]['status_code'];
$message = config('payment.errors')[$result['error']['type']][$result['error']['code']]['message'];
throw new BillingErrorException($status_code, $message);
}
// If we still have an error, then it something out of the user's control.
// This could be a network error, or an error with the payment system
// Therefore, we're going to throw this job back onto the queue so it can be processed later.
if (array_key_exists('error', $result) && in_array($result['error']['code'], array_keys(config('payment.errors.other_error'))))
{
$this->release(60);
}
}
}
I need to test that "$this->release(60)" is called in certain circumstances.
I'm trying to mock the job contract as so, in my tests:
// Set Up
$this->job = Mockery::mock('Illuminate\Contracts\Queue\Job');
$this->app->instance('Illuminate\Contracts\Queue\Job', $this->job);
And then
// During Test
$this->job->shouldReceive('release')->once();
But this isn't working.
Anybody have any ideas?
Try adding the following in you test before dispatching the job:
Queue::after(function (JobProcessed $event) {
$this->assertTrue($event->job->isReleased());
});
The code above will be triggered after the job is done and checks that the job has been released.
Make sure to remove any calls to Queue::fake()and $this->expectsJob() since these will prevent the actual job from being executed.
I solved this problem by creating an event that is only fired after the job is released back into the queue. Then in my tests I can use the Event mocks to watch for that event after I dispatch a job and know if we released it back into the queue or not.
// In your job
$this->release();
event(new MyJobReleasedEvent()); // Every time you have a release() call
// In your Unit Test
Event::fake([MyJobReleasedEvent::class]);
dispatch(new MyJob();
Event::assertDispatched(MyJobReleasedEvent::class);
If you wanted to get fancy I'm sure you could wire up your own Job class that did this automatically when release() was called, but I needed it infrequently enough to just do it inline as-needed.
Related
I have always used events and listeners to add tasks to the queue. Now I'm trying to use Jobs. I do it like this:
my job.
class eventJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $message;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Log::alert($this->message);
}
}
My .env file: QUEUE_CONNECTION=database
In my controller, I dispatch the event like this:
eventJob::dispatch('my message');
A new record appears in the jobs table and to execute it I run php artisan queue:work
The record is removed from the jobs table, but nothing appears in the file logs
I tried in the handle method and the constructor to do throw new \Exception("Error Processing the job", 1); But nothing is written in the filed_jobs table, from which I made the assumption that the handle method and the constructor do not execute.
I also tried running my job like this:
$job = new eventJob('my test message'); dispatch($job);
But it does not change anything
I don't know why but when I changed config/queue.php file from 'default' => env('QUEUE_CONNECTION', 'sync') to 'default' => env('QUEUE_CONNECTION', 'database') everything started working as it should
I have a listener in laravel 9 that transfer posts, but I want to handle a custom error if the destination user is deleted
my listener currently implements ShouldQueue and actually in my method handle I have this
public function handle(TransferPostEvent $transferPostsEvent)
{
$toUser = $this->userService->getUserById($transferPostsEvent->toUserId);
if ($toUser->trashed()) {
$errorMessage = ('*** DESTINATION USER WAS DELETED BEFORE TRANSFER THE POST user id: ' . $toUser->id . '***');
$errorException = new Exception(message: $errorMessage);
$this->failed($transferPostsEvent, $errorException);
} else {
//transfer post...
}
}
and this is my failed method
/**
* #param TransferPostEvent $event
* #param \Throwable $exception
*/
public function failed(TransferPostEvent $event, \Throwable $exception)
{
Log::error($exception);
}
It seems fine, logs are ok, but the console shows 'Processed:Modules\Admin\Listeners\TransferPostListener' message and I would like to show 'Failed:'? is it ok to show 'Failed:' in the console for this type of error? How could I cause it manually?
I am trying to learn about Jobs and queues in Laravel , when i try to learn something new i always take a basic example by myself and try to understand the workflow better.
Okay here is the problem
I have created a Job in Laravel as you can see in the handle method i am just trying to print a simple message on the laravel.logger , this works totally fine.
class SendEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $email;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($email)
{
$this->email = $email;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Log::info($this->email . '<<<<<<<<<<<<<<<');
}
}
My problem is that i want to delay this job for 2 minutes then to dispatch it ,
i have tried it this way but without success both logs are printed immediately when index method is being called but i want $job = new SendEmailJob("This will show after 2 minutes"); to be called after 2 minutes an not printed immediately
public function index(){
$on = Carbon::now()->addMinutes(2);
Log::info('Test');
$job = new SendEmailJob("This will show after 2 minutes");
$job->delay($on);
dispatch($job);
return "none";
}
You can take a look at the documentation: https://laravel.com/docs/8.x/queues#delayed-dispatching
You can do following: (new SendEmailJob("This will show after 2 minutes"))->delay(now()->addMinutes(2)); or
SendEmailJob::dispatch("This will show after 2 minutes")->delay(now()->addMinutes(2));
I have implemented queue jobs in my lumen v5.6 projecs. For queue jobs i am using database driver. But the problem is that when I dispatch job and put sleep method for 15 seconds in job handle() method then job api response hold for 15 second untile the whole job is fired. But I have to sent back api response immediatly as I dispatch job in background.
namespace App\Jobs;
use App\Helpers\NotificationProcess;
class SendPushNotification extends Job {
protected $queueData;
protected $activity;
protected $activity_user;
protected $post;
protected $mentions;
protected $noti;
protected $mention_activities;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($data) {
\Log::info("Queue Start Time:: " . microtime());
$this->queueData = $data;
$this->activity = $data['activity'];
$this->activity_user = $data['user'];
$this->post = $data['post'];
$this->mentions = $data['mentions'];
$this->mention_activities = $data['mention_activities'];
$this->noti = new NotificationProcess();
}
/**
* Execute the job.
*
* #return void
*/
public function handle() {
try {
\Log::info("wait for 15 seconds");
sleep(15);
$receiver = \App\Models\DeviceToken::getDeviceTokensByUsers([$this->post->user_id], $this->activity_user->id, $this->activity['domain']);
if (!$receiver->isEmpty() && !empty($this->activity))
$this->noti->sendCommentPushNotification($this->activity, $receiver[0]->toArray(), $this->activity_user);
if (!empty($this->mentions)) {
$receivers = \App\Models\DeviceToken::getDeviceTokensByUsers($this->mentions, $this->activity_user->id, 'M');
if (!$receivers->isEmpty() && !empty($this->mention_activities))
$this->noti->sendMentionPushNotifications($this->mention_activities, $receivers->toArray(), $this->activity_user);
}
\Log::info("==== Notifications sent ===");
return true;
} catch (\Exception $ex) {
\Log::info("Exception::".$ex->getMessage());
return false;
}
}
}
Now I just want to send back response immediatly to api as I dispatch job for background process it should not hold the response of api.
Note: One job can be processed in 2 min but it should not effect the response of api
I'm writing a simple queue.
namespace App\Jobs;
use App\SomeMessageSender;
class MessageJob extends Job
{
protected $to;
protected $text;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($to, $text)
{
$this->to = $to;
$this->text = $text;
}
/**
* Execute the job.
*
* #return void
*/
public function handle(SomeMessageSender $sender)
{
if ($sender->paramsAreValid($this->to, $this->text) {
$sender->sendMessage($this->to, $this->text);
}
else {
// Fail without being attempted any further
throw new Exception ('The message params are not valid');
}
}
}
If the params are not valid the above code will throw an exception which causes the job to fail but if it still has attempts left, it will be tried again. Instead I want to force this to fail instantly and never attempt again.
How can I do this?
Use the InteractsWithQueue trait and call either delete() if you want to delete the job, or fail($exception = null) if you want to fail it. Failing the job means it will be deleted, logged into the failed_jobs table and the JobFailed event is triggered.
You can specify the number of times the job may be attempted by using $tries in your job.
namespace App\Jobs;
use App\SomeMessageSender;
class MessageJob extends Job
{
/**
* The number of times the job may be attempted.
*
* #var int
*/
public $tries = 1;
}