Framework: QueueFake size method returns wrong value

Created on 27 Aug 2019  路  4Comments  路  Source: laravel/framework

  • Laravel Version: 5.8.33
  • PHP Version: 7.1.25
  • Database Driver & Version: n/a

Description:

QueueFake size returns wrong value

Steps To Reproduce:

  • Install Laravel by any means
  • make a new job by running php artisan make:job TestJob
  • make a new test by running php artisan make:test QueueSizeTest
  • copy the following test method:
   public function testQueueSize()
    {
        \Queue::fake();

        $job = new TestJob();

        dispatch($job);
        dispatch($job);
        dispatch($job)->onQueue('Q2');

        $this->assertEquals(2, \Queue::size());
        $this->assertEquals(1, \Queue::size('Q2'));
    }
  • run the test, it would fail

The flaw is in QueueFake' size method:

    /**
     * Get the size of the queue.
     *
     * @param  string|null  $queue
     * @return int
     */
    public function size($queue = null)
    {
        return count($this->jobs);
    }
  • it doesn't use $queue parameter at all and it improperly calculates amount of jobs, since
    jobs array is associative array, refer to push method:
public function push($job, $data = '', $queue = null)
    {
        $this->jobs[is_object($job) ? get_class($job) : $job][] = [
            'job' => $job,
            'queue' => $queue,
        ];
    }
bug

All 4 comments

This indeed appears to be a bug. Thanks for reporting. Appreciating a PR if you could whip one up.

I can't believe how lazy I am, I forgot that I was using a custom QueueFake for years because of this.

This code is just for inspiration, it works in my project but if you base a fix on it, please vet it it works in all cases:

    public function size($queue = null)
    {
        return collect($this->jobs)
            ->map(function (array $job) use ($queue) {
                return $job[0]['queue'] === $queue;
            })
            ->count();
    }

@mfn thanks for the inspiration, but that piece doesn't traverse through properly, I'll implement something soon

PR was merged

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JamborJan picture JamborJan  路  3Comments

shopblocks picture shopblocks  路  3Comments

lzp819739483 picture lzp819739483  路  3Comments

SachinAgarwal1337 picture SachinAgarwal1337  路  3Comments

felixsanz picture felixsanz  路  3Comments