队列

未匹配的标注

队列

Yii2 Queue extension,An extension for running tasks asynchronously via queues. It supports queues based on DB, Redis, RabbitMQ, AMQP, Beanstalk, ActiveMQ and Gearman.

安装

安装此扩展的首选方式是通过 composer,命令如下:

composer require yiisoft/yii2-queue

配置

为了使用扩展,你必须像下面这样配置它:

return [
    'bootstrap' => [
        'queue', // 组件注册它自己的控制台命令
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\<driver>\Queue::class,
            'as log' => \yii\queue\LogBehavior::class,
            // 其他队列驱动程序选项
        ],
    ],
];

A list of available drivers and their docs is available in the table of contents.

基本用法

Each task which is sent to the queue should be defined as a separate class. For example, if you need to download and save a file the class may look like the following:

class DownloadJob extends BaseObject implements \yii\queue\JobInterface
{
    public $url;
    public $file;

    public function execute($queue)
    {
        file_put_contents($this->file, file_get_contents($this->url));
    }
}

Here’s how to send a task to the queue:

Yii::$app->queue->push(new DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));

To push a job into the queue that should run after 5 minutes:

Yii::$app->queue->delay(5 * 60)->push(new DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));

Important: Not all drivers support delayed running.

You can also specify a priority when pushing a job:

Yii::$app->queue->priority(10)->push(new ErrorNotification([
    'recipient' => 'notifyme@example.com',
]));

Jobs with a lower priority will be executed first. The default priority is 1024.

Important: Not all drivers support job priorities.

队列处理

The exact way how a task is executed depends on the driver being used. Most drivers can be run using console commands, which the component registers in your application. For more details check the respective driver documentation.

作业状态

The component can track the status of a job that was pushed into the queue.

// Push a job into the queue and get a message ID.
$id = Yii::$app->queue->push(new SomeJob());

// Check whether the job is waiting for execution.
Yii::$app->queue->isWaiting($id);

// Check whether a worker got the job from the queue and executes it.
Yii::$app->queue->isReserved($id);

// Check whether a worker has executed the job.
Yii::$app->queue->isDone($id);

Important: The RabbitMQ and AWS SQS drivers don’t support job statuses.

Messaging third party workers

You may pass any data to the queue:

Yii::$app->queue->push([
    'function' => 'download',
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]);

This is useful if the queue is processed using a custom third party worker.

If the worker is not implemented in PHP you have to change the way data is serialized. For example to serialize to JSON:

return [
    'components' => [
        'queue' => [
            'class' => \yii\queue\<driver>\Queue::class,
            'strictJobType' => false,
            'serializer' => \yii\queue\serializers\JsonSerializer::class,
        ],
    ],
];

处理事件

The queue triggers the following events:

Event name Event class Triggered
Queue::EVENT_BEFORE_PUSH PushEvent before adding a job to queue using Queue::push() method
Queue::EVENT_AFTER_PUSH PushEvent after adding a job to queue using Queue::push() method
Queue::EVENT_BEFORE_EXEC ExecEvent before executing a job
Queue::EVENT_AFTER_EXEC ExecEvent after successful job execution
Queue::EVENT_AFTER_ERROR ExecEvent on uncaught exception during the job execution
cli\Queue:EVENT_WORKER_START WorkerEvent when worker has been started
cli\Queue:EVENT_WORKER_LOOP WorkerEvent on each iteration between requests to queue
cli\Queue:EVENT_WORKER_STOP WorkerEvent when worker has been stopped

You can easily attach your own handler to any of these events. For example, let’s delay the job, if its execution failed with a special exception:

Yii::$app->queue->on(Queue::EVENT_AFTER_ERROR, function ($event) {
    if ($event->error instanceof TemporaryUnprocessableJobException) {
        $queue = $event->sender;
        $queue->delay(7200)->push($event->job);
    }
});

日志记录事件

The component provides the LogBehavior to log Queue events using Yii’s built-in Logger.

To enable it, simply configure the queue component as follows:

return [
    'components' => [
        'queue' => [
            'class' => \yii\queue\redis\Queue::class,
            'as log' => \yii\queue\LogBehavior::class
        ],
    ],
];

多个队列

Configuration example:

return [
    'bootstrap' => [
        'queue1', // First component registers its own console commands
        'queue2', // Second component registers its own console commands
    ],
    'components' => [
        'queue1' => [
            'class' => \yii\queue\redis\Queue::class,
        ],
        'queue2' => [
            'class' => \yii\queue\db\Queue::class,
            'strictJobType' => false,
            'serializer' => \yii\queue\serializers\JsonSerializer::class,
        ],
    ],
];

Usage example:

// Sending a task to the queue to be processed via standard worker
Yii::$app->queue1->push(new DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));

// Sending a task to another queue to be processed by a third party worker
Yii::$app->queue2->push([
    'function' => 'download',
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]);

局限性

When using queues it’s important to remember that tasks are put into and obtained from the queue in separate processes. Therefore avoid external dependencies when executing a task if you’re not sure if they are available in the environment where the worker does its job.

All the data to process the task should be put into properties of your job object and be sent into the queue along with it.

If you need to process an ActiveRecord then send its ID instead of the object itself. When processing you have to extract it from DB.

For example:

Yii::$app->queue->push(new SomeJob([
    'userId' => Yii::$app->user->id,
    'bookId' => $book->id,
    'someUrl' => Url::to(['controller/action']),
]));

Task class:

class SomeJob extends BaseObject implements \yii\queue\JobInterface
{
    public $userId;
    public $bookId;
    public $someUrl;

    public function execute($queue)
    {
        $user = User::findOne($this->userId);
        $book = Book::findOne($this->bookId);
        //...
    }
}

错误和可重试的作业

The execution of a job can fail. This can be due to internal errors which result from poorly written code which should be fixed first. But they can also fail due to external problems like a service or a resource being unavailable. This can lead to exceptions or timeouts.

In the latter cases, it’s good to be able to retry a job after some time. There are several ways to do this.

Note: The ttr feature described below requires the PHP Process Control (pcntl) extension to be installed and the worker command has to use the --isolate option (which is enabled by default).

Retry options

The first method is to use queue component options:

'components' => [
    'queue' => [
        'class' => \yii\queue\<driver>\Queue::class,
        'ttr' => 5 * 60, // Max time for job execution
        'attempts' => 3, // Max number of attempts
    ],
],

The ttr (Time to reserve, TTR) option defines the number of seconds during which a job must be successfully completed. So two things can happen to make a job fail:

  1. The job throws an exception before ttr is over
  2. It would take longer than ttr to complete the job (timeout) and thus the job execution is stopped by the worker.

In both cases, the job will be sent back to the queue for a retry. Note though, that in the first case the ttr is still “used up” even if the job stops right after it has stared. I.e. the remaining seconds of ttr have to pass before the job is sent back to the queue.

The attempts option sets the max. number of attempts. If this number is reached, and the job still isn’t done, it will be removed from the queue as completed.

These options apply to all jobs in the queue. If you need to change this behavior for specific jobs, see the following method.

RetryableJobInterface

To have more control over the retry logic a job can implement the RetryableJobInterface. For example:

class SomeJob extends BaseObject implements RetryableJobInterface
{
    public function execute($queue)
    {
        //...
    }

    public function getTtr()
    {
        return 15 * 60;
    }

    public function canRetry($attempt, $error)
    {
        return ($attempt < 5) && ($error instanceof TemporaryException);
    }
}

The getTtr() and canRetry() methods have a higher priority than the component options mentioned above.

事件处理器

The third method to control TTR and number of retries for failed jobs involves the Queue::EVENT_BEFORE_PUSH and Queue::EVENT_AFTER_ERROR events.

The TTR can be set with the Queue::EVENT_BEFORE_PUSH event:

Yii::$app->queue->on(Queue::EVENT_BEFORE_PUSH, function (PushEvent $event) {
    if ($event->job instanceof SomeJob) {
        $event->ttr = 300;
    }
});

And the Queue::EVENT_AFTER_ERROR event can be used to decide whether to try another attempt:

Yii::$app->queue->on(Queue::EVENT_AFTER_ERROR, function (ExecEvent $event) {
    if ($event->job instanceof SomeJob) {
        $event->retry = ($event->attempt < 5) && ($event->error instanceof TemporaryException);
    }
});

Event handlers are executed after the RetryableJobInterface methods, and therefore have the highest priority.

限制条件

Full support for retryable jobs is implemented in the Beanstalk, DB, File, AMQP Interop and Redis drivers. The Sync driver will not retry failed jobs. The Gearman driver doesn’t support retryable jobs. RabbitMQ has only its basic retryable support, where the number of attempts can not be set.

AWS SQS uses Dead Letter Queue for handling messages that were failed to process. All unprocessed messages after a maximum number of attempts are moved to that queue. You should set an address of a Dead Letter Queue and a maximum number of attempts in the AWS Console while creating a queue.

启动 Workers

Supervisor

Supervisor is a process monitor for Linux. It automatically starts console processes. On Ubuntu it can be installed with this command:

sudo apt-get install supervisor

Supervisor config files are usually available in /etc/supervisor/conf.d. You can create any number of config files there.

Here’s an example:

[program:yii-queue-worker]
process_name=%(program_name)s_%(process_num)02d
command=/usr/bin/php /var/www/my_project/yii queue/listen --verbose=1 --color=0
autostart=true
autorestart=true
user=www-data
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/my_project/log/yii-queue-worker.log

In this case Supervisor should start 4 queue/listen workers. The worker output will be written to the specified log file.

For more info about Supervisor’s configuration and usage see its documentation.

Note that worker daemons started with queue/listen are only supported by the File, Db, Redis, RabbitMQ, AMQP Interop, Beanstalk, Gearman and AWS SQS drivers. For additional options see driver guide.

Systemd

Systemd is another init system used on Linux to bootstrap the user space. To configure workers startup using systemd, create a config file named yii-queue@.service in /etc/systemd/system with the following content:

[Unit]
Description=Yii Queue Worker %I
After=network.target
# the following two lines only apply if your queue backend is mysql
# replace this with the service that powers your backend
After=mysql.service
Requires=mysql.service

[Service]
User=www-data
Group=www-data
ExecStart=/usr/bin/php /var/www/my_project/yii queue/listen --verbose
Restart=on-failure

[Install]
WantedBy=multi-user.target

You need to reload systemd in order to re-read its configuration:

systemctl daemon-reload

Set of commands to control workers:

# To start two workers
systemctl start yii-queue@1 yii-queue@2

# To get the status of running workers
systemctl status "yii-queue@*"

# To stop a specific worker
systemctl stop yii-queue@2

# To stop all running workers
systemctl stop "yii-queue@*"

# To start two workers at system boot
systemctl enable yii-queue@1 yii-queue@2

To learn all features of systemd, check its documentation.

Cron

You can also start workers using cron. Here you have to use the queue/run command.

Config example:

* * * * * /usr/bin/php /var/www/my_project/yii queue/run

In this case cron will run the command every minute.

The queue/run command is supported by the File, Db, Redis, Beanstalk, Gearman, AWS SQS drivers. For additional options see driver guide.

队列驱动

Synchronous Driver

Runs tasks synchronously in the same process if the handle property is turned on. It could be used when developing and debugging an application.

Configuration example:

return [
    'components' => [
        'queue' => [
            'class' => \yii\queue\sync\Queue::class,
            'handle' => false, // whether tasks should be executed immediately
        ],
    ],
];

File Driver

The file driver uses files to store queue data.

Configuration example:

return [
    'bootstrap' => [
        'queue', // The component registers its own console commands
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\file\Queue::class,
            'path' => '@runtime/queue',
        ],
    ],
];

Console

Console commands are used to execute and manage queued jobs.

yii queue/listen [timeout]

The listen command launches a daemon which infinitely queries the queue. If there are new tasks they’re immediately obtained and executed. The timeout parameter specifies the number of seconds to sleep between querying the queue. This method is most efficient when the command is properly daemonized via supervisor or systemd.

yii queue/run

The run command obtains and executes tasks in a loop until the queue is empty. This works well with cron.

The run and listen commands have options:

  • --verbose, -v: print execution statuses to console.
  • --isolate: each task is executed in a separate child process.
  • --color: enable highlighting for verbose mode.
yii queue/info

The info command prints out information about the queue status.

yii queue/clear

The clear command clears the queue.

yii queue/remove [id]

The remove command removes a job from the queue.

DB Driver

The DB driver uses a database to store queue data.

It supports:

  • priorities
  • delays
  • ttr
  • attempts

Configuration example:

return [
    'bootstrap' => [
        'queue', // The component registers its own console commands
    ],
    'components' => [
        'db' => [
            'class' => \yii\db\Connection::class, 
            // ...
        ],
        'queue' => [
            'class' => \yii\queue\db\Queue::class,
            'db' => 'db', // DB connection component or its config 
            'tableName' => '{{%queue}}', // Table name
            'channel' => 'default', // Queue channel key
            'mutex' => \yii\mutex\MysqlMutex::class, // Mutex used to sync queries
        ],
    ],
];

You have to add a table to the database. Example schema for:

MySQL:

CREATE TABLE `queue` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `channel` varchar(255) NOT NULL,
  `job` longblob NOT NULL,
  `pushed_at` int(11) NOT NULL,
  `ttr` int(11) NOT NULL,
  `delay` int(11) NOT NULL DEFAULT 0,
  `priority` int(11) unsigned NOT NULL DEFAULT 1024,
  `reserved_at` int(11) DEFAULT NULL,
  `attempt` int(11) DEFAULT NULL,
  `done_at` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `channel` (`channel`),
  KEY `reserved_at` (`reserved_at`),
  KEY `priority` (`priority`)
) ENGINE=InnoDB

and Postgresql

-- Necessary for creating Autoincrement field
CREATE SEQUENCE queue_seq;

CREATE TABLE queue (
  id bigint NOT NULL DEFAULT NEXTVAL ('queue_seq'),
  channel varchar(255) NOT NULL,
  job bytea NOT NULL,
  pushed_at bigint NOT NULL,
  ttr bigint NOT NULL,
  delay bigint NOT NULL DEFAULT 0,
  priority bigint check (priority > 0) NOT NULL DEFAULT 1024,
  reserved_at bigint ,
  attempt bigint,
  done_at bigint,
  PRIMARY KEY (id)
);
-- Optional but good for speeding up queries
CREATE INDEX channel ON queue (channel); 
CREATE INDEX reserved_at ON queue (reserved_at);
CREATE INDEX priority ON queue (priority);

You can use migrations which are available from src/drivers/db/migrations.

To add migrations to your application, edit the console config file to configure a namespaced migration:

'controllerMap' => [
    // ...
    'migrate' => [
        'class' => 'yii\console\controllers\MigrateController',
        'migrationPath' => null,
        'migrationNamespaces' => [
            // ...
            'yii\queue\db\migrations',
        ],
    ],
],

Then issue the migrate/up command:

yii migrate/up

Console

Console commands are used to execute and manage queued jobs.

yii queue/listen [timeout]

The listen command launches a daemon which infinitely queries the queue. If there are new tasks they’re immediately obtained and executed. The timeout parameter specifies the number of seconds to sleep between querying the queue. This method is most efficient when the command is properly daemonized via supervisor or systemd.

yii queue/run

The run command obtains and executes tasks in a loop until the queue is empty. This works well with cron.

The run and listen commands have options:

  • --verbose, -v: print execution statuses to console.
  • --isolate: each task is executed in a separate child process.
  • --color: enable highlighting for verbose mode.
yii queue/info

The info command prints out information about the queue status.

yii queue/clear

The clear command clears the queue.

yii queue/remove [id]

The remove command removes a job from the queue.

Redis Driver

This driver uses Redis to store queue data.

You have to add the yiisoft/yii2-redis extension to your application in order to use it.

Configuration example:

return [
    'bootstrap' => [
        'queue', // The component registers its own console commands
    ],
    'components' => [
        'redis' => [
            'class' => \yii\redis\Connection::class,
            // ...

            // retry connecting after connection has timed out
            // yiisoft/yii2-redis >=2.0.7 is required for this.
            'retries' => 1,
        ],
        'queue' => [
            'class' => \yii\queue\redis\Queue::class,
            'redis' => 'redis', // Redis connection component or its config
            'channel' => 'queue', // Queue channel key
        ],
    ],
];

Console

Console commands are used to execute and manage queued jobs.

yii queue/listen [timeout]

The listen command launches a daemon which infinitely queries the queue. If there are new tasks they’re immediately obtained and executed. The timeout parameter specifies the number of seconds to sleep between querying the queue. This method is most efficient when the command is properly daemonized via supervisor or systemd.

yii queue/run

The run command obtains and executes tasks in a loop until the queue is empty. This works well with cron.

The run and listen commands have options:

  • --verbose, -v: print execution statuses to console.
  • --isolate: each task is executed in a separate child process.
  • --color: enable highlighting for verbose mode.
yii queue/info

The info command prints out information about the queue status.

yii queue/clear

The clear command clears the queue.

yii queue/remove [id]

The remove command removes a job from the queue.

RabbitMQ Driver

Note: This driver has been deprecated since 2.0.2 and will be removed in 2.1. Consider using the amqp_interop driver instead.

This driver works with RabbitMQ queues.

It requires the php-amqplib/php-amqplib package.

Configuration example:

return [
    'bootstrap' => [
        'queue', // The component registers its own console commands
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\amqp\Queue::class,
            'host' => 'localhost',
            'port' => 5672,
            'user' => 'guest',
            'password' => 'guest',
            'queueName' => 'queue',
        ],
    ],
];

Console

A console command is used to execute queued jobs.

yii queue/listen

The listen command launches a daemon which infinitely queries the queue. This method is most efficient when the command is properly daemonized via supervisor or systemd.

AMQP Interop

This driver works with RabbitMQ queues.

It requires an amqp interop compatible transport, for example the enqueue/amqp-lib package.

Advantages:

Configuration example:

return [
    'bootstrap' => [
        'queue', // The component registers its own console commands
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\amqp_interop\Queue::class,
            'port' => 5672,
            'user' => 'guest',
            'password' => 'guest',
            'queueName' => 'queue',
            'driver' => yii\queue\amqp_interop\Queue::ENQUEUE_AMQP_LIB,

            // or
            'dsn' => 'amqp://guest:guest@localhost:5672/%2F',

            // or, same as above
            'dsn' => 'amqp:',
        ],
    ],
];

Console

A console command is used to execute queued jobs.

yii queue/listen

The listen command launches a daemon which infinitely queries the queue. If there are new tasks they’re immediately obtained and executed. This method is most efficient when the command is properly daemonized via supervisor or systemd.

Beanstalk Driver

This driver works with Beanstalk queues.

Configuration example:

return [
    'bootstrap' => [
        'queue', // The component registers its own console commands
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\beanstalk\Queue::class,
            'host' => 'localhost',
            'port' => 11300,
            'tube' => 'queue',
        ],
    ],
];

Console

Console commands are used to execute and manage queued jobs.

yii queue/listen [timeout]

The listen command launches a daemon which infinitely queries the queue. If there are new tasks they’re immediately obtained and executed. The timeout parameter specifies the number of seconds to sleep between querying the queue. This method is most efficient when the command is properly daemonized via supervisor or systemd.

yii queue/run

The run command obtains and executes tasks in a loop until the queue is empty. This works well with cron.

The run and listen commands have options:

  • --verbose, -v: print execution status to console.
  • --isolate: each task is executed in a separate child process.
  • --color: enable highlighting for verbose mode.
yii queue/info

The info command prints out information about the queue status.

yii queue/remove [id]

The remove command removes a job from the queue.

Gearman Driver

This driver works with Gearman queues.

Configuration example:

return [
    'bootstrap' => [
        'queue', // The component registers its own console commands
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\gearman\Queue::class,
            'host' => 'localhost',
            'port' => 4730,
            'channel' => 'my_queue',
        ],
    ],
];

Console

Console commands are used to process queued tasks.

yii queue/listen

listen command launches a daemon which infinitely queries the queue. If there are new tasks they’re immediately obtained and executed. This method is most efficient when command is properly daemonized via supervisor or systemd.

yii queue/run

run command obtains and executes tasks in a loop until queue is empty. Works well with cron.

run and listen commands have options:

  • --verbose, -v: print executing statuses into console.
  • --isolate: each task is executed in a separate child process.
  • --color: highlighting for verbose mode.

AWS SQS Driver

The driver uses AWS SQS to store queue data.

You have to add aws/aws-sdk-php extension to your application in order to use it.

Configuration example for standard queues:

return [
    'bootstrap' => [
        'queue', // The component registers own console commands
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\sqs\Queue::class,
            'url' => '<sqs url>',
            'key' => '<key>',
            'secret' => '<secret>',
            'region' => '<region>',
        ],
    ],
];

Configuration example for FIFO queues:

return [
    'bootstrap' => [
        'queue', // The component registers own console commands
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\sqs\Queue::class,
            'url' => '<sqs url>',
            'key' => '<key>',
            'secret' => '<secret>',
            'region' => '<region>',
            'messageGroupId' => '<Group ID>',
        ],
    ],
];

The message group ID is required by SQS for FIFO queues. You can configure your own or use the “default” value.

The deduplication ID is generated automatically, so no matter if you have activated content-based deduplication in the SQS queue or not, this ID will be used.

Console

Console command is used to execute tasks.

yii queue/listen [timeout]

listen command launches a daemon which infinitely queries the queue. If there are new tasks they’re immediately obtained and executed. timeout parameter is number of seconds to wait a job. It uses SQS “Long Polling” feature, that holds a connection between client and a queue.

Important: timeout parameter for SQS driver must be in range between 0 and 20 seconds.

This method is most efficient when command is properly daemonized via supervisor or systemd.

yii queue/run

run command obtains and executes tasks in a loop until queue is empty. Works well with cron.

run and listen commands have options:

  • --verbose, -v: print executing statuses into console.
  • --isolate: each task is executed in a separate child process.
  • --color: highlighting for verbose mode.
yii queue/clear

clear command clears a queue.

Stomp Driver

This driver works with ActiveMQ queues.

It requires the enqueue/stomp package.

Configuration example:

return [
    'bootstrap' => [
        'queue', // The component registers its own console commands
    ],
    'components' => [
        'queue' => [
            'class' => \yii\queue\stomp\Queue::class,
            'host' => 'localhost',
            'port' => 61613,
            'queueName' => 'queue',
        ],
    ],
];

Console

A console command is used to execute queued jobs.

yii queue/listen [timeout]

The listen command launches a daemon which infinitely queries the queue. If there are new tasks they’re immediately obtained and executed. The timeout parameter specifies the number of seconds to sleep between querying the queue. This method is most efficient when the command is properly daemonized via supervisor or systemd.

Debugging

During development you may want to add a panel for the Yii2 debug module. The panel displays a counter and a list of queued tasks.

The yiisoft/yii2-debug module should be installed in your application for the panel to be displayed.

Configure your application like the following:

return [
    'modules' => [
        'debug' => [
            'class' => \yii\debug\Module::class,
            'panels' => [
                'queue' => \yii\queue\debug\Panel::class,
            ],
        ],
    ],
];

Gii Code generator

You can use the Gii code generator to create a job template.

Configuration

To use the Gii job generator you have to configure it like the following:

if (!YII_ENV_TEST) {
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        'generators' => [
            'job' => [
                'class' => \yii\queue\gii\Generator::class,
            ],
        ],
    ];
}

After doing so you’ll find the generator in the Gii menu.

default

Tests

Environment

In order to run tests, you need to install Docker, Docker Compose and the make utility. Docker configuration files are in tests/docker and Docker Compose file is tests/docker-compose.yml. There are configurations for different versions of PHP (5.6, 7.0, 7.1, 7.2, 7.3). You need to create .env file to specify where the docker-compose.yml file is. You can create .env file from .env.example in the root directory of the project.

Running Tests

To run tests execute the following command:

# for all PHP versions
make test

# for PHP 7.3 only
make test73

If you need to pass options to phpunit use the following commands (for example, to run only one test file):

docker-compose build --pull php73
docker-compose run php73 vendor/bin/phpunit tests\\drivers\\sqs\\QueueTest /code/tests/drivers/sqs/QueueTest.php
docker-compose down

Some tests can be disabled by default for various reasons (for example, the AWS SQS test require a queue set up in AWS). The test checks AWS_SQS_ENABLED environment variable (see \tests\drivers\sqs\QueueTest::setUp). If you want to run that test you need to set this variable to 1. You can specify environment variables that you need to pass to the container in the .env file in the base directory (see .env.example). AWS SQS test requires queue credentials that you also need to pass to the container via .env file (see tests/app/config/main.php).

# .env

AWS_SQS_ENABLED=1
AWS_KEY=KEY
AWS_SECRET=SECRET
AWS_REGION=us-east-1
AWS_SQS_URL=https://sqs.us-east-1.amazonaws.com/234888945020/queue1
# AWS SQS test will not be skipped now
make test73

💖喜欢本文档的,欢迎点赞、收藏、留言或转发,谢谢支持!
作者邮箱:zhuzixian520@126.com,github地址:github.com/zhuzixian520

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
zhuzixian520
讨论数量: 0
发起讨论 查看所有版本


暂无话题~