- Reformatted files to PSR2 standard

- Removed credis for native phpredis
- Tidied up some docs
- Setting up new travis.ci build
This commit is contained in:
Daniel Mason 2018-05-25 19:26:54 +12:00
parent 065d5a4c63
commit ae84530132
30 changed files with 3724 additions and 2682 deletions

View File

@ -1,4 +1,8 @@
## 1.3 (2013-??-??) - Current Master ## ## 1.4 (2018-05-25)
## 1.3 (2013) ##
**Note:** This release introduces backwards incompatible changes with all previous versions of php-resque. Please see below for details. **Note:** This release introduces backwards incompatible changes with all previous versions of php-resque. Please see below for details.

View File

@ -12,7 +12,7 @@
} }
], ],
"require": { "require": {
"php": ">=5.3.0", "php": ">=7.0.0",
"ext-pcntl": "*", "ext-pcntl": "*",
"psr/log": "~1.0" "psr/log": "~1.0"
}, },
@ -21,7 +21,7 @@
"ext-redis": "Native PHP extension for Redis connectivity. Credis will automatically utilize when available." "ext-redis": "Native PHP extension for Redis connectivity. Credis will automatically utilize when available."
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "3.7.*" "phpunit/phpunit": "^7"
}, },
"bin": [ "bin": [
"bin/resque" "bin/resque"

1577
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,379 +1,380 @@
<?php <?php
/** /**
* Base Resque class. * Base Resque class.
* *
* @package Resque * @package Resque
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque class Resque
{ {
const VERSION = '1.2'; const VERSION = '1.4';
const DEFAULT_INTERVAL = 5; const DEFAULT_INTERVAL = 5;
/** /**
* @var Resque_Redis Instance of Resque_Redis that talks to redis. * @var Resque_Redis Instance of Resque_Redis that talks to redis.
*/ */
public static $redis = null; public static $redis = null;
/** /**
* @var mixed Host/port conbination separated by a colon, or a nested * @var mixed Host/port conbination separated by a colon, or a nested
* array of server swith host/port pairs * array of server swith host/port pairs
*/ */
protected static $redisServer = null; protected static $redisServer = null;
/** /**
* @var int ID of Redis database to select. * @var int ID of Redis database to select.
*/ */
protected static $redisDatabase = 0; protected static $redisDatabase = 0;
/** /**
* Given a host/port combination separated by a colon, set it as * Given a host/port combination separated by a colon, set it as
* the redis server that Resque will talk to. * the redis server that Resque will talk to.
* *
* @param mixed $server Host/port combination separated by a colon, DSN-formatted URI, or * @param mixed $server Host/port combination separated by a colon, DSN-formatted URI, or
* a callable that receives the configured database ID * a callable that receives the configured database ID
* and returns a Resque_Redis instance, or * and returns a Resque_Redis instance, or
* a nested array of servers with host/port pairs. * a nested array of servers with host/port pairs.
* @param int $database * @param int $database
*/ */
public static function setBackend($server, $database = 0) public static function setBackend($server, $database = 0)
{ {
self::$redisServer = $server; self::$redisServer = $server;
self::$redisDatabase = $database; self::$redisDatabase = $database;
self::$redis = null; self::$redis = null;
} }
/** /**
* Return an instance of the Resque_Redis class instantiated for Resque. * Return an instance of the Resque_Redis class instantiated for Resque.
* *
* @return Resque_Redis Instance of Resque_Redis. * @return Resque_Redis Instance of Resque_Redis.
*/ */
public static function redis() public static function redis()
{ {
if (self::$redis !== null) { if (self::$redis !== null) {
return self::$redis; return self::$redis;
} }
if (is_callable(self::$redisServer)) { if (is_callable(self::$redisServer)) {
self::$redis = call_user_func(self::$redisServer, self::$redisDatabase); self::$redis = call_user_func(self::$redisServer, self::$redisDatabase);
} else { } else {
self::$redis = new Resque_Redis(self::$redisServer, self::$redisDatabase); self::$redis = new Resque_Redis(self::$redisServer, self::$redisDatabase);
} }
return self::$redis; return self::$redis;
} }
/** /**
* fork() helper method for php-resque that handles issues PHP socket * fork() helper method for php-resque that handles issues PHP socket
* and phpredis have with passing around sockets between child/parent * and phpredis have with passing around sockets between child/parent
* processes. * processes.
* *
* Will close connection to Redis before forking. * Will close connection to Redis before forking.
* *
* @return int Return vars as per pcntl_fork(). False if pcntl_fork is unavailable * @return int Return vars as per pcntl_fork(). False if pcntl_fork is unavailable
*/ */
public static function fork() public static function fork()
{ {
if(!function_exists('pcntl_fork')) { if (!function_exists('pcntl_fork')) {
return false; return false;
} }
// Close the connection to Redis before forking. // Close the connection to Redis before forking.
// This is a workaround for issues phpredis has. // This is a workaround for issues phpredis has.
self::$redis = null; self::$redis = null;
$pid = pcntl_fork(); $pid = pcntl_fork();
if($pid === -1) { if ($pid === -1) {
throw new RuntimeException('Unable to fork child worker.'); throw new RuntimeException('Unable to fork child worker.');
} }
return $pid; return $pid;
} }
/** /**
* Push a job to the end of a specific queue. If the queue does not * Push a job to the end of a specific queue. If the queue does not
* exist, then create it as well. * exist, then create it as well.
* *
* @param string $queue The name of the queue to add the job to. * @param string $queue The name of the queue to add the job to.
* @param array $item Job description as an array to be JSON encoded. * @param array $item Job description as an array to be JSON encoded.
*/ */
public static function push($queue, $item) public static function push($queue, $item)
{ {
$encodedItem = json_encode($item); $encodedItem = json_encode($item);
if ($encodedItem === false) { if ($encodedItem === false) {
return false; return false;
} }
self::redis()->sadd('queues', $queue); self::redis()->sadd('queues', $queue);
$length = self::redis()->rpush('queue:' . $queue, $encodedItem); $length = self::redis()->rpush('queue:' . $queue, $encodedItem);
if ($length < 1) { if ($length < 1) {
return false; return false;
} }
return true; return true;
} }
/** /**
* Pop an item off the end of the specified queue, decode it and * Pop an item off the end of the specified queue, decode it and
* return it. * return it.
* *
* @param string $queue The name of the queue to fetch an item from. * @param string $queue The name of the queue to fetch an item from.
* @return array Decoded item from the queue. * @return array Decoded item from the queue.
*/ */
public static function pop($queue) public static function pop($queue)
{ {
$item = self::redis()->lpop('queue:' . $queue); $item = self::redis()->lpop('queue:' . $queue);
if(!$item) { if (!$item) {
return; return;
} }
return json_decode($item, true); return json_decode($item, true);
} }
/** /**
* Remove items of the specified queue * Remove items of the specified queue
* *
* @param string $queue The name of the queue to fetch an item from. * @param string $queue The name of the queue to fetch an item from.
* @param array $items * @param array $items
* @return integer number of deleted items * @return integer number of deleted items
*/ */
public static function dequeue($queue, $items = Array()) public static function dequeue($queue, $items = Array())
{ {
if(count($items) > 0) { if (count($items) > 0) {
return self::removeItems($queue, $items); return self::removeItems($queue, $items);
} else { } else {
return self::removeList($queue); return self::removeList($queue);
} }
} }
/** /**
* Remove specified queue * Remove specified queue
* *
* @param string $queue The name of the queue to remove. * @param string $queue The name of the queue to remove.
* @return integer Number of deleted items * @return integer Number of deleted items
*/ */
public static function removeQueue($queue) public static function removeQueue($queue)
{ {
$num = self::removeList($queue); $num = self::removeList($queue);
self::redis()->srem('queues', $queue); self::redis()->srem('queues', $queue);
return $num; return $num;
} }
/** /**
* Pop an item off the end of the specified queues, using blocking list pop, * Pop an item off the end of the specified queues, using blocking list pop,
* decode it and return it. * decode it and return it.
* *
* @param array $queues * @param array $queues
* @param int $timeout * @param int $timeout
* @return null|array Decoded item from the queue. * @return null|array Decoded item from the queue.
*/ */
public static function blpop(array $queues, $timeout) public static function blpop(array $queues, $timeout)
{ {
$list = array(); $list = array();
foreach($queues AS $queue) { foreach ($queues AS $queue) {
$list[] = 'queue:' . $queue; $list[] = 'queue:' . $queue;
} }
$item = self::redis()->blpop($list, (int)$timeout); $item = self::redis()->blpop($list, (int)$timeout);
if(!$item) { if (!$item) {
return; return;
} }
/** /**
* Normally the Resque_Redis class returns queue names without the prefix * Normally the Resque_Redis class returns queue names without the prefix
* But the blpop is a bit different. It returns the name as prefix:queue:name * But the blpop is a bit different. It returns the name as prefix:queue:name
* So we need to strip off the prefix:queue: part * So we need to strip off the prefix:queue: part
*/ */
$queue = substr($item[0], strlen(self::redis()->getPrefix() . 'queue:')); $queue = substr($item[0], strlen(self::redis()->getPrefix() . 'queue:'));
return array( return array(
'queue' => $queue, 'queue' => $queue,
'payload' => json_decode($item[1], true) 'payload' => json_decode($item[1], true)
); );
} }
/** /**
* Return the size (number of pending jobs) of the specified queue. * Return the size (number of pending jobs) of the specified queue.
* *
* @param string $queue name of the queue to be checked for pending jobs * @param string $queue name of the queue to be checked for pending jobs
* *
* @return int The size of the queue. * @return int The size of the queue.
*/ */
public static function size($queue) public static function size($queue)
{ {
return self::redis()->llen('queue:' . $queue); return self::redis()->llen('queue:' . $queue);
} }
/** /**
* Create a new job and save it to the specified queue. * Create a new job and save it to the specified queue.
* *
* @param string $queue The name of the queue to place the job in. * @param string $queue The name of the queue to place the job in.
* @param string $class The name of the class that contains the code to execute the job. * @param string $class The name of the class that contains the code to execute the job.
* @param array $args Any optional arguments that should be passed when the job is executed. * @param array $args Any optional arguments that should be passed when the job is executed.
* @param boolean $trackStatus Set to true to be able to monitor the status of a job. * @param boolean $trackStatus Set to true to be able to monitor the status of a job.
* *
* @return string|boolean Job ID when the job was created, false if creation was cancelled due to beforeEnqueue * @return string|boolean Job ID when the job was created, false if creation was cancelled due to beforeEnqueue
*/ */
public static function enqueue($queue, $class, $args = null, $trackStatus = false) public static function enqueue($queue, $class, $args = null, $trackStatus = false)
{ {
$id = Resque::generateJobId(); $id = Resque::generateJobId();
$hookParams = array( $hookParams = array(
'class' => $class, 'class' => $class,
'args' => $args, 'args' => $args,
'queue' => $queue, 'queue' => $queue,
'id' => $id, 'id' => $id,
); );
try { try {
Resque_Event::trigger('beforeEnqueue', $hookParams); Resque_Event::trigger('beforeEnqueue', $hookParams);
} } catch (Resque_Job_DontCreate $e) {
catch(Resque_Job_DontCreate $e) { return false;
return false; }
}
Resque_Job::create($queue, $class, $args, $trackStatus, $id); Resque_Job::create($queue, $class, $args, $trackStatus, $id);
Resque_Event::trigger('afterEnqueue', $hookParams); Resque_Event::trigger('afterEnqueue', $hookParams);
return $id; return $id;
} }
/** /**
* Reserve and return the next available job in the specified queue. * Reserve and return the next available job in the specified queue.
* *
* @param string $queue Queue to fetch next available job from. * @param string $queue Queue to fetch next available job from.
* @return Resque_Job Instance of Resque_Job to be processed, false if none or error. * @return Resque_Job Instance of Resque_Job to be processed, false if none or error.
*/ */
public static function reserve($queue) public static function reserve($queue)
{ {
return Resque_Job::reserve($queue); return Resque_Job::reserve($queue);
} }
/** /**
* Get an array of all known queues. * Get an array of all known queues.
* *
* @return array Array of queues. * @return array Array of queues.
*/ */
public static function queues() public static function queues()
{ {
$queues = self::redis()->smembers('queues'); $queues = self::redis()->smembers('queues');
if(!is_array($queues)) { if (!is_array($queues)) {
$queues = array(); $queues = array();
} }
return $queues; return $queues;
} }
/** /**
* Remove Items from the queue * Remove Items from the queue
* Safely moving each item to a temporary queue before processing it * Safely moving each item to a temporary queue before processing it
* If the Job matches, counts otherwise puts it in a requeue_queue * If the Job matches, counts otherwise puts it in a requeue_queue
* which at the end eventually be copied back into the original queue * which at the end eventually be copied back into the original queue
* *
* @private * @private
* *
* @param string $queue The name of the queue * @param string $queue The name of the queue
* @param array $items * @param array $items
* @return integer number of deleted items * @return integer number of deleted items
*/ */
private static function removeItems($queue, $items = Array()) private static function removeItems($queue, $items = Array())
{ {
$counter = 0; $counter = 0;
$originalQueue = 'queue:'. $queue; $originalQueue = 'queue:' . $queue;
$tempQueue = $originalQueue. ':temp:'. time(); $tempQueue = $originalQueue . ':temp:' . time();
$requeueQueue = $tempQueue. ':requeue'; $requeueQueue = $tempQueue . ':requeue';
// move each item from original queue to temp queue and process it // move each item from original queue to temp queue and process it
$finished = false; $finished = false;
while (!$finished) { while (!$finished) {
$string = self::redis()->rpoplpush($originalQueue, self::redis()->getPrefix() . $tempQueue); $string = self::redis()->rpoplpush($originalQueue, self::redis()->getPrefix() . $tempQueue);
if (!empty($string)) { if (!empty($string)) {
if(self::matchItem($string, $items)) { if (self::matchItem($string, $items)) {
self::redis()->rpop($tempQueue); self::redis()->rpop($tempQueue);
$counter++; $counter++;
} else { } else {
self::redis()->rpoplpush($tempQueue, self::redis()->getPrefix() . $requeueQueue); self::redis()->rpoplpush($tempQueue, self::redis()->getPrefix() . $requeueQueue);
} }
} else { } else {
$finished = true; $finished = true;
} }
} }
// move back from temp queue to original queue // move back from temp queue to original queue
$finished = false; $finished = false;
while (!$finished) { while (!$finished) {
$string = self::redis()->rpoplpush($requeueQueue, self::redis()->getPrefix() .$originalQueue); $string = self::redis()->rpoplpush($requeueQueue, self::redis()->getPrefix() . $originalQueue);
if (empty($string)) { if (empty($string)) {
$finished = true; $finished = true;
} }
} }
// remove temp queue and requeue queue // remove temp queue and requeue queue
self::redis()->del($requeueQueue); self::redis()->del($requeueQueue);
self::redis()->del($tempQueue); self::redis()->del($tempQueue);
return $counter; return $counter;
} }
/** /**
* matching item * matching item
* item can be ['class'] or ['class' => 'id'] or ['class' => {:foo => 1, :bar => 2}] * item can be ['class'] or ['class' => 'id'] or ['class' => {:foo => 1, :bar => 2}]
* @private * @private
* *
* @params string $string redis result in json * @params string $string redis result in json
* @params $items * @params $items
* *
* @return (bool) * @return (bool)
*/ */
private static function matchItem($string, $items) private static function matchItem($string, $items)
{ {
$decoded = json_decode($string, true); $decoded = json_decode($string, true);
foreach($items as $key => $val) { foreach ($items as $key => $val) {
# class name only ex: item[0] = ['class'] # class name only ex: item[0] = ['class']
if (is_numeric($key)) { if (is_numeric($key)) {
if($decoded['class'] == $val) { if ($decoded['class'] == $val) {
return true; return true;
} }
# class name with args , example: item[0] = ['class' => {'foo' => 1, 'bar' => 2}] # class name with args , example: item[0] = ['class' => {'foo' => 1, 'bar' => 2}]
} elseif (is_array($val)) { } elseif (is_array($val)) {
$decodedArgs = (array)$decoded['args'][0]; $decodedArgs = (array)$decoded['args'][0];
if ($decoded['class'] == $key && if ($decoded['class'] == $key &&
count($decodedArgs) > 0 && count(array_diff($decodedArgs, $val)) == 0) { count($decodedArgs) > 0 && count(array_diff($decodedArgs, $val)) == 0) {
return true; return true;
} }
# class name with ID, example: item[0] = ['class' => 'id'] # class name with ID, example: item[0] = ['class' => 'id']
} else { } else {
if ($decoded['class'] == $key && $decoded['id'] == $val) { if ($decoded['class'] == $key && $decoded['id'] == $val) {
return true; return true;
} }
} }
} }
return false; return false;
} }
/** /**
* Remove List * Remove List
* *
* @private * @private
* *
* @params string $queue the name of the queue * @params string $queue the name of the queue
* @return integer number of deleted items belongs to this list * @return integer number of deleted items belongs to this list
*/ */
private static function removeList($queue) private static function removeList($queue)
{ {
$counter = self::size($queue); $counter = self::size($queue);
$result = self::redis()->del('queue:' . $queue); $result = self::redis()->del('queue:' . $queue);
return ($result == 1) ? $counter : 0; return ($result == 1) ? $counter : 0;
} }
/* /*
* Generate an identifier to attach to a job for status tracking. * Generate an identifier to attach to a job for status tracking.
* *
* @return string * @return string
*/ */
public static function generateJobId() public static function generateJobId()
{ {
return md5(uniqid('', true)); return md5(uniqid('', true));
} }
} }

View File

@ -1,88 +1,90 @@
<?php <?php
/** /**
* Resque event/plugin system class * Resque event/plugin system class
* *
* @package Resque/Event * @package Resque/Event
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Event class Resque_Event
{ {
/** /**
* @var array Array containing all registered callbacks, indexked by event name. * @var array Array containing all registered callbacks, indexked by event name.
*/ */
private static $events = array(); private static $events = [];
/** /**
* Raise a given event with the supplied data. * Raise a given event with the supplied data.
* *
* @param string $event Name of event to be raised. * @param string $event Name of event to be raised.
* @param mixed $data Optional, any data that should be passed to each callback. * @param mixed $data Optional, any data that should be passed to each callback.
* @return true * @return true
*/ */
public static function trigger($event, $data = null) public static function trigger($event, $data = null)
{ {
if (!is_array($data)) { if (!is_array($data)) {
$data = array($data); $data = [$data];
} }
if (empty(self::$events[$event])) { if (empty(self::$events[$event])) {
return true; return true;
} }
foreach (self::$events[$event] as $callback) { foreach (self::$events[$event] as $callback) {
if (!is_callable($callback)) { if (!is_callable($callback)) {
continue; continue;
} }
call_user_func_array($callback, $data); call_user_func_array($callback, $data);
} }
return true; return true;
} }
/** /**
* Listen in on a given event to have a specified callback fired. * Listen in on a given event to have a specified callback fired.
* *
* @param string $event Name of event to listen on. * @param string $event Name of event to listen on.
* @param mixed $callback Any callback callable by call_user_func_array. * @param mixed $callback Any callback callable by call_user_func_array.
* @return true * @return true
*/ */
public static function listen($event, $callback) public static function listen($event, $callback)
{ {
if (!isset(self::$events[$event])) { if (!isset(self::$events[$event])) {
self::$events[$event] = array(); self::$events[$event] = [];
} }
self::$events[$event][] = $callback; self::$events[$event][] = $callback;
return true; return true;
} }
/** /**
* Stop a given callback from listening on a specific event. * Stop a given callback from listening on a specific event.
* *
* @param string $event Name of event. * @param string $event Name of event.
* @param mixed $callback The callback as defined when listen() was called. * @param mixed $callback The callback as defined when listen() was called.
* @return true * @return true
*/ */
public static function stopListening($event, $callback) public static function stopListening($event, $callback)
{ {
if (!isset(self::$events[$event])) { if (!isset(self::$events[$event])) {
return true; return true;
} }
$key = array_search($callback, self::$events[$event]); $key = array_search($callback, self::$events[$event]);
if ($key !== false) { if ($key !== false) {
unset(self::$events[$event][$key]); unset(self::$events[$event][$key]);
} }
return true; return true;
} }
/** /**
* Call all registered listeners. * Call all registered listeners.
*/ */
public static function clearListeners() public static function clearListeners()
{ {
self::$events = array(); self::$events = [];
} }
} }

View File

@ -1,11 +1,13 @@
<?php <?php
/** /**
* Resque exception. * Resque exception.
* *
* @package Resque * @package Resque
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Exception extends Exception class Resque_Exception extends Exception
{ {
} }

View File

@ -3,54 +3,55 @@
/** /**
* Failed Resque job. * Failed Resque job.
* *
* @package Resque/Failure * @package Resque/Failure
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Failure class Resque_Failure
{ {
/** /**
* @var string Class name representing the backend to pass failed jobs off to. * @var string Class name representing the backend to pass failed jobs off to.
*/ */
private static $backend; private static $backend;
/** /**
* Create a new failed job on the backend. * Create a new failed job on the backend.
* *
* @param object $payload The contents of the job that has just failed. * @param object $payload The contents of the job that has just failed.
* @param \Exception $exception The exception generated when the job failed to run. * @param \Exception $exception The exception generated when the job failed to run.
* @param \Resque_Worker $worker Instance of Resque_Worker that was running this job when it failed. * @param \Resque_Worker $worker Instance of Resque_Worker that was running this job when it failed.
* @param string $queue The name of the queue that this job was fetched from. * @param string $queue The name of the queue that this job was fetched from.
*/ */
public static function create($payload, Exception $exception, Resque_Worker $worker, $queue) public static function create($payload, Exception $exception, Resque_Worker $worker, $queue)
{ {
$backend = self::getBackend(); $backend = self::getBackend();
new $backend($payload, $exception, $worker, $queue); new $backend($payload, $exception, $worker, $queue);
} }
/** /**
* Return an instance of the backend for saving job failures. * Return an instance of the backend for saving job failures.
* *
* @return object Instance of backend object. * @return object Instance of backend object.
*/ */
public static function getBackend() public static function getBackend()
{ {
if(self::$backend === null) { if (self::$backend === null) {
self::$backend = 'Resque_Failure_Redis'; self::$backend = 'Resque_Failure_Redis';
} }
return self::$backend; return self::$backend;
} }
/** /**
* Set the backend to use for raised job failures. The supplied backend * Set the backend to use for raised job failures. The supplied backend
* should be the name of a class to be instantiated when a job fails. * should be the name of a class to be instantiated when a job fails.
* It is your responsibility to have the backend class loaded (or autoloaded) * It is your responsibility to have the backend class loaded (or autoloaded)
* *
* @param string $backend The class name of the backend to pipe failures to. * @param string $backend The class name of the backend to pipe failures to.
*/ */
public static function setBackend($backend) public static function setBackend($backend)
{ {
self::$backend = $backend; self::$backend = $backend;
} }
} }

View File

@ -1,20 +1,21 @@
<?php <?php
/** /**
* Interface that all failure backends should implement. * Interface that all failure backends should implement.
* *
* @package Resque/Failure * @package Resque/Failure
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
interface Resque_Failure_Interface interface Resque_Failure_Interface
{ {
/** /**
* Initialize a failed job class and save it (where appropriate). * Initialize a failed job class and save it (where appropriate).
* *
* @param object $payload Object containing details of the failed job. * @param object $payload Object containing details of the failed job.
* @param object $exception Instance of the exception that was thrown by the failed job. * @param object $exception Instance of the exception that was thrown by the failed job.
* @param object $worker Instance of Resque_Worker that received the job. * @param object $worker Instance of Resque_Worker that received the job.
* @param string $queue The name of the queue the job was fetched from. * @param string $queue The name of the queue the job was fetched from.
*/ */
public function __construct($payload, $exception, $worker, $queue); public function __construct($payload, $exception, $worker, $queue);
} }

View File

@ -2,32 +2,32 @@
/** /**
* Redis backend for storing failed Resque jobs. * Redis backend for storing failed Resque jobs.
* *
* @package Resque/Failure * @package Resque/Failure
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Failure_Redis implements Resque_Failure_Interface class Resque_Failure_Redis implements Resque_Failure_Interface
{ {
/** /**
* Initialize a failed job class and save it (where appropriate). * Initialize a failed job class and save it (where appropriate).
* *
* @param object $payload Object containing details of the failed job. * @param object $payload Object containing details of the failed job.
* @param object $exception Instance of the exception that was thrown by the failed job. * @param object $exception Instance of the exception that was thrown by the failed job.
* @param object $worker Instance of Resque_Worker that received the job. * @param object $worker Instance of Resque_Worker that received the job.
* @param string $queue The name of the queue the job was fetched from. * @param string $queue The name of the queue the job was fetched from.
*/ */
public function __construct($payload, $exception, $worker, $queue) public function __construct($payload, $exception, $worker, $queue)
{ {
$data = new stdClass; $data = new stdClass;
$data->failed_at = strftime('%a %b %d %H:%M:%S %Z %Y'); $data->failed_at = strftime('%a %b %d %H:%M:%S %Z %Y');
$data->payload = $payload; $data->payload = $payload;
$data->exception = get_class($exception); $data->exception = get_class($exception);
$data->error = $exception->getMessage(); $data->error = $exception->getMessage();
$data->backtrace = explode("\n", $exception->getTraceAsString()); $data->backtrace = explode("\n", $exception->getTraceAsString());
$data->worker = (string)$worker; $data->worker = (string)$worker;
$data->queue = $queue; $data->queue = $queue;
$data = json_encode($data); $data = json_encode($data);
Resque::redis()->rpush('failed', $data); Resque::redis()->rpush('failed', $data);
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Resque job. * Resque job.
* *
@ -6,6 +7,7 @@
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Job class Resque_Job
{ {
/** /**

View File

@ -1,10 +1,11 @@
<?php <?php
/** /**
* Runtime exception class for a job that does not exit cleanly. * Runtime exception class for a job that does not exit cleanly.
* *
* @package Resque/Job * @package Resque/Job
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Job_DirtyExitException extends RuntimeException class Resque_Job_DirtyExitException extends RuntimeException
{ {

View File

@ -1,10 +1,11 @@
<?php <?php
/** /**
* Exception to be thrown if while enqueuing a job it should not be created. * Exception to be thrown if while enqueuing a job it should not be created.
* *
* @package Resque/Job * @package Resque/Job
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Job_DontCreate extends Exception class Resque_Job_DontCreate extends Exception
{ {

View File

@ -1,11 +1,13 @@
<?php <?php
/** /**
* Exception to be thrown if a job should not be performed/run. * Exception to be thrown if a job should not be performed/run.
* *
* @package Resque/Job * @package Resque/Job
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Job_DontPerform extends Exception class Resque_Job_DontPerform extends Exception
{ {

View File

@ -2,11 +2,11 @@
interface Resque_Job_FactoryInterface interface Resque_Job_FactoryInterface
{ {
/** /**
* @param $className * @param $className
* @param array $args * @param array $args
* @param $queue * @param $queue
* @return Resque_JobInterface * @return Resque_JobInterface
*/ */
public function create($className, $args, $queue); public function create($className, $args, $queue);
} }

View File

@ -1,142 +1,144 @@
<?php <?php
/** /**
* Status tracker/information for a job. * Status tracker/information for a job.
* *
* @package Resque/Job * @package Resque/Job
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Job_Status class Resque_Job_Status
{ {
const STATUS_WAITING = 1; const STATUS_WAITING = 1;
const STATUS_RUNNING = 2; const STATUS_RUNNING = 2;
const STATUS_FAILED = 3; const STATUS_FAILED = 3;
const STATUS_COMPLETE = 4; const STATUS_COMPLETE = 4;
/** /**
* @var string The ID of the job this status class refers back to. * @var string The ID of the job this status class refers back to.
*/ */
private $id; private $id;
/** /**
* @var mixed Cache variable if the status of this job is being monitored or not. * @var mixed Cache variable if the status of this job is being monitored or not.
* True/false when checked at least once or null if not checked yet. * True/false when checked at least once or null if not checked yet.
*/ */
private $isTracking = null; private $isTracking = null;
/** /**
* @var array Array of statuses that are considered final/complete. * @var array Array of statuses that are considered final/complete.
*/ */
private static $completeStatuses = array( private static $completeStatuses = array(
self::STATUS_FAILED, self::STATUS_FAILED,
self::STATUS_COMPLETE self::STATUS_COMPLETE
); );
/** /**
* Setup a new instance of the job monitor class for the supplied job ID. * Setup a new instance of the job monitor class for the supplied job ID.
* *
* @param string $id The ID of the job to manage the status for. * @param string $id The ID of the job to manage the status for.
*/ */
public function __construct($id) public function __construct($id)
{ {
$this->id = $id; $this->id = $id;
} }
/** /**
* Create a new status monitor item for the supplied job ID. Will create * Create a new status monitor item for the supplied job ID. Will create
* all necessary keys in Redis to monitor the status of a job. * all necessary keys in Redis to monitor the status of a job.
* *
* @param string $id The ID of the job to monitor the status of. * @param string $id The ID of the job to monitor the status of.
*/ */
public static function create($id) public static function create($id)
{ {
$statusPacket = array( $statusPacket = array(
'status' => self::STATUS_WAITING, 'status' => self::STATUS_WAITING,
'updated' => time(), 'updated' => time(),
'started' => time(), 'started' => time(),
); );
Resque::redis()->set('job:' . $id . ':status', json_encode($statusPacket)); Resque::redis()->set('job:' . $id . ':status', json_encode($statusPacket));
} }
/** /**
* Check if we're actually checking the status of the loaded job status * Check if we're actually checking the status of the loaded job status
* instance. * instance.
* *
* @return boolean True if the status is being monitored, false if not. * @return boolean True if the status is being monitored, false if not.
*/ */
public function isTracking() public function isTracking()
{ {
if($this->isTracking === false) { if ($this->isTracking === false) {
return false; return false;
} }
if(!Resque::redis()->exists((string)$this)) { if (!Resque::redis()->exists((string)$this)) {
$this->isTracking = false; $this->isTracking = false;
return false; return false;
} }
$this->isTracking = true; $this->isTracking = true;
return true; return true;
} }
/** /**
* Update the status indicator for the current job with a new status. * Update the status indicator for the current job with a new status.
* *
* @param int The status of the job (see constants in Resque_Job_Status) * @param int The status of the job (see constants in Resque_Job_Status)
*/ */
public function update($status) public function update($status)
{ {
if(!$this->isTracking()) { if (!$this->isTracking()) {
return; return;
} }
$statusPacket = array( $statusPacket = [
'status' => $status, 'status' => $status,
'updated' => time(), 'updated' => time(),
); ];
Resque::redis()->set((string)$this, json_encode($statusPacket)); Resque::redis()->set((string)$this, json_encode($statusPacket));
// Expire the status for completed jobs after 24 hours // Expire the status for completed jobs after 24 hours
if(in_array($status, self::$completeStatuses)) { if (in_array($status, self::$completeStatuses)) {
Resque::redis()->expire((string)$this, 86400); Resque::redis()->expire((string)$this, 86400);
} }
} }
/** /**
* Fetch the status for the job being monitored. * Fetch the status for the job being monitored.
* *
* @return mixed False if the status is not being monitored, otherwise the status as * @return mixed False if the status is not being monitored, otherwise the status as
* as an integer, based on the Resque_Job_Status constants. * as an integer, based on the Resque_Job_Status constants.
*/ */
public function get() public function get()
{ {
if(!$this->isTracking()) { if (!$this->isTracking()) {
return false; return false;
} }
$statusPacket = json_decode(Resque::redis()->get((string)$this), true); $statusPacket = json_decode(Resque::redis()->get((string)$this), true);
if(!$statusPacket) { if (!$statusPacket) {
return false; return false;
} }
return $statusPacket['status']; return $statusPacket['status'];
} }
/** /**
* Stop tracking the status of a job. * Stop tracking the status of a job.
*/ */
public function stop() public function stop()
{ {
Resque::redis()->del((string)$this); Resque::redis()->del((string)$this);
} }
/** /**
* Generate a string representation of this object. * Generate a string representation of this object.
* *
* @return string String representation of the current job status class. * @return string String representation of the current job status class.
*/ */
public function __toString() public function __toString()
{ {
return 'job:' . $this->id . ':status'; return 'job:' . $this->id . ':status';
} }
} }

View File

@ -2,8 +2,8 @@
interface Resque_JobInterface interface Resque_JobInterface
{ {
/** /**
* @return bool * @return bool
*/ */
public function perform(); public function perform();
} }

View File

@ -1,62 +1,65 @@
<?php <?php
/** /**
* Resque default logger PSR-3 compliant * Resque default logger PSR-3 compliant
* *
* @package Resque/Stat * @package Resque/Stat
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Log extends Psr\Log\AbstractLogger class Resque_Log extends Psr\Log\AbstractLogger
{ {
public $verbose; public $verbose;
public function __construct($verbose = false) { public function __construct($verbose = false)
$this->verbose = $verbose; {
} $this->verbose = $verbose;
}
/** /**
* Logs with an arbitrary level. * Logs with an arbitrary level.
* *
* @param mixed $level PSR-3 log level constant, or equivalent string * @param mixed $level PSR-3 log level constant, or equivalent string
* @param string $message Message to log, may contain a { placeholder } * @param string $message Message to log, may contain a { placeholder }
* @param array $context Variables to replace { placeholder } * @param array $context Variables to replace { placeholder }
* @return null * @return null
*/ */
public function log($level, $message, array $context = array()) public function log($level, $message, array $context = array())
{ {
if ($this->verbose) { if ($this->verbose) {
fwrite( fwrite(
STDOUT, STDOUT,
'[' . $level . '] [' . strftime('%T %Y-%m-%d') . '] ' . $this->interpolate($message, $context) . PHP_EOL '[' . $level . '] [' . strftime('%T %Y-%m-%d') . '] ' . $this->interpolate($message, $context) . PHP_EOL
); );
return; return;
} }
if (!($level === Psr\Log\LogLevel::INFO || $level === Psr\Log\LogLevel::DEBUG)) { if (!($level === Psr\Log\LogLevel::INFO || $level === Psr\Log\LogLevel::DEBUG)) {
fwrite( fwrite(
STDOUT, STDOUT,
'[' . $level . '] ' . $this->interpolate($message, $context) . PHP_EOL '[' . $level . '] ' . $this->interpolate($message, $context) . PHP_EOL
); );
} }
} }
/** /**
* Fill placeholders with the provided context * Fill placeholders with the provided context
* @author Jordi Boggiano j.boggiano@seld.be * @author Jordi Boggiano j.boggiano@seld.be
* *
* @param string $message Message to be logged * @param string $message Message to be logged
* @param array $context Array of variables to use in message * @param array $context Array of variables to use in message
* @return string * @return string
*/ */
public function interpolate($message, array $context = array()) public function interpolate($message, array $context = array())
{ {
// build a replacement array with braces around the context keys // build a replacement array with braces around the context keys
$replace = array(); $replace = array();
foreach ($context as $key => $val) { foreach ($context as $key => $val) {
$replace['{' . $key . '}'] = $val; $replace['{' . $key . '}'] = $val;
} }
// interpolate replacement values into the message and return // interpolate replacement values into the message and return
return strtr($message, $replace); return strtr($message, $replace);
} }
} }

View File

@ -1,270 +1,262 @@
<?php <?php
/** /**
* Wrap Credis to add namespace support and various helper methods. * Set up phpredis connection
* *
* @package Resque/Redis * @package Resque/Redis
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Redis class Resque_Redis
{ {
/** /**
* Redis namespace * Redis namespace
* @var string * @var string
*/ */
private static $defaultNamespace = 'resque:'; private static $defaultNamespace = 'resque:';
/** /**
* A default host to connect to * A default host to connect to
*/ */
const DEFAULT_HOST = 'localhost'; const DEFAULT_HOST = 'localhost';
/** /**
* The default Redis port * The default Redis port
*/ */
const DEFAULT_PORT = 6379; const DEFAULT_PORT = 6379;
/** /**
* The default Redis Database number * The default Redis Database number
*/ */
const DEFAULT_DATABASE = 0; const DEFAULT_DATABASE = 0;
/** /**
* @var array List of all commands in Redis that supply a key as their * @var array List of all commands in Redis that supply a key as their
* first argument. Used to prefix keys with the Resque namespace. * first argument. Used to prefix keys with the Resque namespace.
*/ */
private $keyCommands = array( private $keyCommands = [
'exists', 'exists',
'del', 'del',
'type', 'type',
'keys', 'keys',
'expire', 'expire',
'ttl', 'ttl',
'move', 'move',
'set', 'set',
'setex', 'setex',
'get', 'get',
'getset', 'getset',
'setnx', 'setnx',
'incr', 'incr',
'incrby', 'incrby',
'decr', 'decr',
'decrby', 'decrby',
'rpush', 'rpush',
'lpush', 'lpush',
'llen', 'llen',
'lrange', 'lrange',
'ltrim', 'ltrim',
'lindex', 'lindex',
'lset', 'lset',
'lrem', 'lrem',
'lpop', 'lpop',
'blpop', 'blpop',
'rpop', 'rpop',
'sadd', 'sadd',
'srem', 'srem',
'spop', 'spop',
'scard', 'scard',
'sismember', 'sismember',
'smembers', 'smembers',
'srandmember', 'srandmember',
'zadd', 'zadd',
'zrem', 'zrem',
'zrange', 'zrange',
'zrevrange', 'zrevrange',
'zrangebyscore', 'zrangebyscore',
'zcard', 'zcard',
'zscore', 'zscore',
'zremrangebyscore', 'zremrangebyscore',
'sort', 'sort',
'rename', 'rename',
'rpoplpush' 'rpoplpush'
); ];
// sinterstore // sinterstore
// sunion // sunion
// sunionstore // sunionstore
// sdiff // sdiff
// sdiffstore // sdiffstore
// sinter // sinter
// smove // smove
// mget // mget
// msetnx // msetnx
// mset // mset
// renamenx // renamenx
/** /**
* Set Redis namespace (prefix) default: resque * Set Redis namespace (prefix) default: resque
* @param string $namespace * @param string $namespace
*/ */
public static function prefix($namespace) public static function prefix($namespace)
{ {
if (substr($namespace, -1) !== ':' && $namespace != '') { if (substr($namespace, -1) !== ':' && $namespace != '') {
$namespace .= ':'; $namespace .= ':';
} }
self::$defaultNamespace = $namespace; self::$defaultNamespace = $namespace;
} }
/** /**
* @param string|array $server A DSN or array * @param string|array $server A DSN or array
* @param int $database A database number to select. However, if we find a valid database number in the DSN the * @param int $database A database number to select. However, if we find a valid database number in the DSN the
* DSN-supplied value will be used instead and this parameter is ignored. * DSN-supplied value will be used instead and this parameter is ignored.
* @param object $client Optional Credis_Cluster or Credis_Client instance instantiated by you * @param object $client Optional Credis_Cluster or Credis_Client instance instantiated by you
*/ * @throws Resque_RedisException
*/
public function __construct($server, $database = null, $client = null) public function __construct($server, $database = null, $client = null)
{ {
try { try {
if (is_array($server)) { if (is_object($client)) {
$this->driver = new Credis_Cluster($server); $this->redisConnection = $client;
} } else {
else if (is_object($client)) { list($host, $port, $dsnDatabase, $user, $password, $options) = self::parseDsn($server);
$this->driver = $client; // $user is not used, only $password
}
else {
list($host, $port, $dsnDatabase, $user, $password, $options) = self::parseDsn($server);
// $user is not used, only $password
// Look for known Credis_Client options $timeout = isset($options['timeout']) ? intval($options['timeout']) : null;
$timeout = isset($options['timeout']) ? intval($options['timeout']) : null;
$persistent = isset($options['persistent']) ? $options['persistent'] : '';
$maxRetries = isset($options['max_connect_retries']) ? $options['max_connect_retries'] : 0;
$this->driver = new Credis_Client($host, $port, $timeout, $persistent); $this->redisConnection = new \Redis();
$this->driver->setMaxConnectRetries($maxRetries);
if ($password){
$this->driver->auth($password);
}
// If we have found a database in our DSN, use it instead of the `$database` if (!$this->redisConnection->connect($host, $port, $timeout)) {
// value passed into the constructor. throw new RedisException("Connection Failed to Redis!");
if ($dsnDatabase !== false) { };
$database = $dsnDatabase;
}
}
if ($database !== null) { if ($password) {
$this->driver->select($database); $this->redisConnection->auth($password);
} }
}
catch(CredisException $e) {
throw new Resque_RedisException('Error communicating with Redis: ' . $e->getMessage(), 0, $e);
}
}
/** // If we have found a database in our DSN, use it instead of the `$database`
* Parse a DSN string, which can have one of the following formats: // value passed into the constructor.
* if ($dsnDatabase !== false) {
* - host:port $database = $dsnDatabase;
* - redis://user:pass@host:port/db?option1=val1&option2=val2 }
* - tcp://user:pass@host:port/db?option1=val1&option2=val2
* - unix:///path/to/redis.sock
*
* Note: the 'user' part of the DSN is not used.
*
* @param string $dsn A DSN string
* @return array An array of DSN compotnents, with 'false' values for any unknown components. e.g.
* [host, port, db, user, pass, options]
*/
public static function parseDsn($dsn)
{
if ($dsn == '') {
// Use a sensible default for an empty DNS string
$dsn = 'redis://' . self::DEFAULT_HOST;
}
if(substr($dsn, 0, 7) === 'unix://') {
return array(
$dsn,
null,
false,
null,
null,
null,
);
}
$parts = parse_url($dsn);
// Check the URI scheme if ($database) {
$validSchemes = array('redis', 'tcp'); $this->redisConnection->select($database);
if (isset($parts['scheme']) && ! in_array($parts['scheme'], $validSchemes)) { }
throw new \InvalidArgumentException("Invalid DSN. Supported schemes are " . implode(', ', $validSchemes)); }
} } catch (RedisException $e) {
throw new Resque_RedisException('Error communicating with Redis: ' . $e->getMessage(), 0, $e);
}
}
// Allow simple 'hostname' format, which `parse_url` treats as a path, not host. /**
if ( ! isset($parts['host']) && isset($parts['path'])) { * Parse a DSN string, which can have one of the following formats:
$parts['host'] = $parts['path']; *
unset($parts['path']); * - host:port
} * - redis://user:pass@host:port/db?option1=val1&option2=val2
* - tcp://user:pass@host:port/db?option1=val1&option2=val2
* - unix:///path/to/redis.sock
*
* Note: the 'user' part of the DSN is not used.
*
* @param string $dsn A DSN string
* @return array An array of DSN compotnents, with 'false' values for any unknown components. e.g.
* [host, port, db, user, pass, options]
*/
public static function parseDsn($dsn)
{
if ($dsn == '') {
// Use a sensible default for an empty DNS string
$dsn = 'redis://' . self::DEFAULT_HOST;
}
if (substr($dsn, 0, 7) === 'unix://') {
return [
$dsn,
null,
false,
null,
null,
null,
];
}
$parts = parse_url($dsn);
// Extract the port number as an integer // Check the URI scheme
$port = isset($parts['port']) ? intval($parts['port']) : self::DEFAULT_PORT; $validSchemes = array('redis', 'tcp');
if (isset($parts['scheme']) && !in_array($parts['scheme'], $validSchemes)) {
throw new \InvalidArgumentException("Invalid DSN. Supported schemes are " . implode(', ', $validSchemes));
}
// Get the database from the 'path' part of the URI // Allow simple 'hostname' format, which `parse_url` treats as a path, not host.
$database = false; if (!isset($parts['host']) && isset($parts['path'])) {
if (isset($parts['path'])) { $parts['host'] = $parts['path'];
// Strip non-digit chars from path unset($parts['path']);
$database = intval(preg_replace('/[^0-9]/', '', $parts['path'])); }
}
// Extract any 'user' and 'pass' values // Extract the port number as an integer
$user = isset($parts['user']) ? $parts['user'] : false; $port = isset($parts['port']) ? intval($parts['port']) : self::DEFAULT_PORT;
$pass = isset($parts['pass']) ? $parts['pass'] : false;
// Convert the query string into an associative array // Get the database from the 'path' part of the URI
$options = array(); $database = false;
if (isset($parts['query'])) { if (isset($parts['path'])) {
// Parse the query string into an array // Strip non-digit chars from path
parse_str($parts['query'], $options); $database = intval(preg_replace('/[^0-9]/', '', $parts['path']));
} }
return array( // Extract any 'user' and 'pass' values
$parts['host'], $user = isset($parts['user']) ? $parts['user'] : false;
$port, $pass = isset($parts['pass']) ? $parts['pass'] : false;
$database,
$user,
$pass,
$options,
);
}
/** // Convert the query string into an associative array
* Magic method to handle all function requests and prefix key based $options = array();
* operations with the {self::$defaultNamespace} key prefix. if (isset($parts['query'])) {
* // Parse the query string into an array
* @param string $name The name of the method called. parse_str($parts['query'], $options);
* @param array $args Array of supplied arguments to the method. }
* @return mixed Return value from Resident::call() based on the command.
*/
public function __call($name, $args)
{
if (in_array($name, $this->keyCommands)) {
if (is_array($args[0])) {
foreach ($args[0] AS $i => $v) {
$args[0][$i] = self::$defaultNamespace . $v;
}
}
else {
$args[0] = self::$defaultNamespace . $args[0];
}
}
try {
return $this->driver->__call($name, $args);
}
catch (CredisException $e) {
throw new Resque_RedisException('Error communicating with Redis: ' . $e->getMessage(), 0, $e);
}
}
public static function getPrefix() return array(
{ $parts['host'],
return self::$defaultNamespace; $port,
} $database,
$user,
$pass,
$options,
);
}
public static function removePrefix($string) /**
{ * Magic method to handle all function requests and prefix key based
$prefix=self::getPrefix(); * operations with the {self::$defaultNamespace} key prefix.
*
* @param string $name The name of the method called.
* @param array $args Array of supplied arguments to the method.
* @return mixed Return value from Resident::call() based on the command.
*/
public function __call($name, $args)
{
if (in_array($name, $this->keyCommands)) {
if (is_array($args[0])) {
foreach ($args[0] AS $i => $v) {
$args[0][$i] = self::$defaultNamespace . $v;
}
} else {
$args[0] = self::$defaultNamespace . $args[0];
}
}
}
if (substr($string, 0, strlen($prefix)) == $prefix) { public static function getPrefix()
$string = substr($string, strlen($prefix), strlen($string) ); {
} return self::$defaultNamespace;
return $string; }
}
public static function removePrefix($string)
{
$prefix = self::getPrefix();
if (substr($string, 0, strlen($prefix)) == $prefix) {
$string = substr($string, strlen($prefix), strlen($string));
}
return $string;
}
} }

View File

@ -1,12 +1,14 @@
<?php <?php
/** /**
* Redis related exceptions * Redis related exceptions
* *
* @package Resque * @package Resque
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_RedisException extends Resque_Exception class Resque_RedisException extends Resque_Exception
{ {
} }
?>

View File

@ -1,56 +1,58 @@
<?php <?php
/** /**
* Resque statistic management (jobs processed, failed, etc) * Resque statistic management (jobs processed, failed, etc)
* *
* @package Resque/Stat * @package Resque/Stat
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Stat class Resque_Stat
{ {
/** /**
* Get the value of the supplied statistic counter for the specified statistic. * Get the value of the supplied statistic counter for the specified statistic.
* *
* @param string $stat The name of the statistic to get the stats for. * @param string $stat The name of the statistic to get the stats for.
* @return mixed Value of the statistic. * @return mixed Value of the statistic.
*/ */
public static function get($stat) public static function get($stat)
{ {
return (int)Resque::redis()->get('stat:' . $stat); return (int)Resque::redis()->get('stat:' . $stat);
} }
/** /**
* Increment the value of the specified statistic by a certain amount (default is 1) * Increment the value of the specified statistic by a certain amount (default is 1)
* *
* @param string $stat The name of the statistic to increment. * @param string $stat The name of the statistic to increment.
* @param int $by The amount to increment the statistic by. * @param int $by The amount to increment the statistic by.
* @return boolean True if successful, false if not. * @return boolean True if successful, false if not.
*/ */
public static function incr($stat, $by = 1) public static function incr($stat, $by = 1)
{ {
return (bool)Resque::redis()->incrby('stat:' . $stat, $by); return (bool)Resque::redis()->incrby('stat:' . $stat, $by);
} }
/** /**
* Decrement the value of the specified statistic by a certain amount (default is 1) * Decrement the value of the specified statistic by a certain amount (default is 1)
* *
* @param string $stat The name of the statistic to decrement. * @param string $stat The name of the statistic to decrement.
* @param int $by The amount to decrement the statistic by. * @param int $by The amount to decrement the statistic by.
* @return boolean True if successful, false if not. * @return boolean True if successful, false if not.
*/ */
public static function decr($stat, $by = 1) public static function decr($stat, $by = 1)
{ {
return (bool)Resque::redis()->decrby('stat:' . $stat, $by); return (bool)Resque::redis()->decrby('stat:' . $stat, $by);
} }
/** /**
* Delete a statistic with the given name. * Delete a statistic with the given name.
* *
* @param string $stat The name of the statistic to delete. * @param string $stat The name of the statistic to delete.
* @return boolean True if successful, false if not. * @return boolean True if successful, false if not.
*/ */
public static function clear($stat) public static function clear($stat)
{ {
return (bool)Resque::redis()->del('stat:' . $stat); return (bool)Resque::redis()->del('stat:' . $stat);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,199 +1,201 @@
<?php <?php
/** /**
* Resque_Event tests. * Resque_Event tests.
* *
* @package Resque/Tests * @package Resque/Tests
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Tests_EventTest extends Resque_Tests_TestCase class Resque_Tests_EventTest extends Resque_Tests_TestCase
{ {
private $callbacksHit = array(); private $callbacksHit = array();
public function setUp() public function setUp()
{ {
Test_Job::$called = false; Test_Job::$called = false;
// Register a worker to test with // Register a worker to test with
$this->worker = new Resque_Worker('jobs'); $this->worker = new Resque_Worker('jobs');
$this->worker->setLogger(new Resque_Log()); $this->worker->setLogger(new Resque_Log());
$this->worker->registerWorker(); $this->worker->registerWorker();
} }
public function tearDown() public function tearDown()
{ {
Resque_Event::clearListeners(); Resque_Event::clearListeners();
$this->callbacksHit = array(); $this->callbacksHit = array();
} }
public function getEventTestJob() public function getEventTestJob()
{ {
$payload = array( $payload = array(
'class' => 'Test_Job', 'class' => 'Test_Job',
'args' => array( 'args' => array(
array('somevar'), array('somevar'),
), ),
); );
$job = new Resque_Job('jobs', $payload); $job = new Resque_Job('jobs', $payload);
$job->worker = $this->worker; $job->worker = $this->worker;
return $job; return $job;
} }
public function eventCallbackProvider() public function eventCallbackProvider()
{ {
return array( return array(
array('beforePerform', 'beforePerformEventCallback'), array('beforePerform', 'beforePerformEventCallback'),
array('afterPerform', 'afterPerformEventCallback'), array('afterPerform', 'afterPerformEventCallback'),
array('afterFork', 'afterForkEventCallback'), array('afterFork', 'afterForkEventCallback'),
); );
} }
/** /**
* @dataProvider eventCallbackProvider * @dataProvider eventCallbackProvider
*/ */
public function testEventCallbacksFire($event, $callback) public function testEventCallbacksFire($event, $callback)
{ {
Resque_Event::listen($event, array($this, $callback)); Resque_Event::listen($event, array($this, $callback));
$job = $this->getEventTestJob(); $job = $this->getEventTestJob();
$this->worker->perform($job); $this->worker->perform($job);
$this->worker->work(0); $this->worker->work(0);
$this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback .') was not called'); $this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback . ') was not called');
} }
public function testBeforeForkEventCallbackFires() public function testBeforeForkEventCallbackFires()
{ {
$event = 'beforeFork'; $event = 'beforeFork';
$callback = 'beforeForkEventCallback'; $callback = 'beforeForkEventCallback';
Resque_Event::listen($event, array($this, $callback)); Resque_Event::listen($event, array($this, $callback));
Resque::enqueue('jobs', 'Test_Job', array( Resque::enqueue('jobs', 'Test_Job', array(
'somevar' 'somevar'
)); ));
$job = $this->getEventTestJob(); $job = $this->getEventTestJob();
$this->worker->work(0); $this->worker->work(0);
$this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback .') was not called'); $this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback . ') was not called');
} }
public function testBeforeEnqueueEventCallbackFires() public function testBeforeEnqueueEventCallbackFires()
{ {
$event = 'beforeEnqueue'; $event = 'beforeEnqueue';
$callback = 'beforeEnqueueEventCallback'; $callback = 'beforeEnqueueEventCallback';
Resque_Event::listen($event, array($this, $callback)); Resque_Event::listen($event, array($this, $callback));
Resque::enqueue('jobs', 'Test_Job', array( Resque::enqueue('jobs', 'Test_Job', array(
'somevar' 'somevar'
)); ));
$this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback .') was not called'); $this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback . ') was not called');
} }
public function testBeforePerformEventCanStopWork() public function testBeforePerformEventCanStopWork()
{ {
$callback = 'beforePerformEventDontPerformCallback'; $callback = 'beforePerformEventDontPerformCallback';
Resque_Event::listen('beforePerform', array($this, $callback)); Resque_Event::listen('beforePerform', array($this, $callback));
$job = $this->getEventTestJob(); $job = $this->getEventTestJob();
$this->assertFalse($job->perform()); $this->assertFalse($job->perform());
$this->assertContains($callback, $this->callbacksHit, $callback . ' callback was not called'); $this->assertContains($callback, $this->callbacksHit, $callback . ' callback was not called');
$this->assertFalse(Test_Job::$called, 'Job was still performed though Resque_Job_DontPerform was thrown'); $this->assertFalse(Test_Job::$called, 'Job was still performed though Resque_Job_DontPerform was thrown');
} }
public function testBeforeEnqueueEventStopsJobCreation() public function testBeforeEnqueueEventStopsJobCreation()
{ {
$callback = 'beforeEnqueueEventDontCreateCallback'; $callback = 'beforeEnqueueEventDontCreateCallback';
Resque_Event::listen('beforeEnqueue', array($this, $callback)); Resque_Event::listen('beforeEnqueue', array($this, $callback));
Resque_Event::listen('afterEnqueue', array($this, 'afterEnqueueEventCallback')); Resque_Event::listen('afterEnqueue', array($this, 'afterEnqueueEventCallback'));
$result = Resque::enqueue('test_job', 'TestClass'); $result = Resque::enqueue('test_job', 'TestClass');
$this->assertContains($callback, $this->callbacksHit, $callback . ' callback was not called'); $this->assertContains($callback, $this->callbacksHit, $callback . ' callback was not called');
$this->assertNotContains('afterEnqueueEventCallback', $this->callbacksHit, 'afterEnqueue was still called, even though it should not have been'); $this->assertNotContains('afterEnqueueEventCallback', $this->callbacksHit, 'afterEnqueue was still called, even though it should not have been');
$this->assertFalse($result); $this->assertFalse($result);
} }
public function testAfterEnqueueEventCallbackFires() public function testAfterEnqueueEventCallbackFires()
{ {
$callback = 'afterEnqueueEventCallback'; $callback = 'afterEnqueueEventCallback';
$event = 'afterEnqueue'; $event = 'afterEnqueue';
Resque_Event::listen($event, array($this, $callback)); Resque_Event::listen($event, array($this, $callback));
Resque::enqueue('jobs', 'Test_Job', array( Resque::enqueue('jobs', 'Test_Job', array(
'somevar' 'somevar'
)); ));
$this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback .') was not called'); $this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback . ') was not called');
} }
public function testStopListeningRemovesListener() public function testStopListeningRemovesListener()
{ {
$callback = 'beforePerformEventCallback'; $callback = 'beforePerformEventCallback';
$event = 'beforePerform'; $event = 'beforePerform';
Resque_Event::listen($event, array($this, $callback)); Resque_Event::listen($event, array($this, $callback));
Resque_Event::stopListening($event, array($this, $callback)); Resque_Event::stopListening($event, array($this, $callback));
$job = $this->getEventTestJob(); $job = $this->getEventTestJob();
$this->worker->perform($job); $this->worker->perform($job);
$this->worker->work(0); $this->worker->work(0);
$this->assertNotContains($callback, $this->callbacksHit, $this->assertNotContains($callback, $this->callbacksHit,
$event . ' callback (' . $callback .') was called though Resque_Event::stopListening was called' $event . ' callback (' . $callback . ') was called though Resque_Event::stopListening was called'
); );
} }
public function beforePerformEventDontPerformCallback($instance) public function beforePerformEventDontPerformCallback($instance)
{ {
$this->callbacksHit[] = __FUNCTION__; $this->callbacksHit[] = __FUNCTION__;
throw new Resque_Job_DontPerform; throw new Resque_Job_DontPerform;
} }
public function beforeEnqueueEventDontCreateCallback($queue, $class, $args, $track = false) public function beforeEnqueueEventDontCreateCallback($queue, $class, $args, $track = false)
{ {
$this->callbacksHit[] = __FUNCTION__; $this->callbacksHit[] = __FUNCTION__;
throw new Resque_Job_DontCreate; throw new Resque_Job_DontCreate;
} }
public function assertValidEventCallback($function, $job) public function assertValidEventCallback($function, $job)
{ {
$this->callbacksHit[] = $function; $this->callbacksHit[] = $function;
if (!$job instanceof Resque_Job) { if (!$job instanceof Resque_Job) {
$this->fail('Callback job argument is not an instance of Resque_Job'); $this->fail('Callback job argument is not an instance of Resque_Job');
} }
$args = $job->getArguments(); $args = $job->getArguments();
$this->assertEquals($args[0], 'somevar'); $this->assertEquals($args[0], 'somevar');
} }
public function afterEnqueueEventCallback($class, $args) public function afterEnqueueEventCallback($class, $args)
{ {
$this->callbacksHit[] = __FUNCTION__; $this->callbacksHit[] = __FUNCTION__;
$this->assertEquals('Test_Job', $class); $this->assertEquals('Test_Job', $class);
$this->assertEquals(array( $this->assertEquals(array(
'somevar', 'somevar',
), $args); ), $args);
} }
public function beforeEnqueueEventCallback($job) public function beforeEnqueueEventCallback($job)
{ {
$this->callbacksHit[] = __FUNCTION__; $this->callbacksHit[] = __FUNCTION__;
} }
public function beforePerformEventCallback($job) public function beforePerformEventCallback($job)
{ {
$this->assertValidEventCallback(__FUNCTION__, $job); $this->assertValidEventCallback(__FUNCTION__, $job);
} }
public function afterPerformEventCallback($job) public function afterPerformEventCallback($job)
{ {
$this->assertValidEventCallback(__FUNCTION__, $job); $this->assertValidEventCallback(__FUNCTION__, $job);
} }
public function beforeForkEventCallback($job) public function beforeForkEventCallback($job)
{ {
$this->assertValidEventCallback(__FUNCTION__, $job); $this->assertValidEventCallback(__FUNCTION__, $job);
} }
public function afterForkEventCallback($job) public function afterForkEventCallback($job)
{ {
$this->assertValidEventCallback(__FUNCTION__, $job); $this->assertValidEventCallback(__FUNCTION__, $job);
} }
} }

View File

@ -1,11 +1,13 @@
<?php <?php
/** /**
* Resque_Job_Status tests. * Resque_Job_Status tests.
* *
* @package Resque/Tests * @package Resque/Tests
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Tests_JobStatusTest extends Resque_Tests_TestCase class Resque_Tests_JobStatusTest extends Resque_Tests_TestCase
{ {
/** /**
@ -13,94 +15,94 @@ class Resque_Tests_JobStatusTest extends Resque_Tests_TestCase
*/ */
protected $worker; protected $worker;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
// Register a worker to test with // Register a worker to test with
$this->worker = new Resque_Worker('jobs'); $this->worker = new Resque_Worker('jobs');
$this->worker->setLogger(new Resque_Log()); $this->worker->setLogger(new Resque_Log());
} }
public function testJobStatusCanBeTracked() public function testJobStatusCanBeTracked()
{ {
$token = Resque::enqueue('jobs', 'Test_Job', null, true); $token = Resque::enqueue('jobs', 'Test_Job', null, true);
$status = new Resque_Job_Status($token); $status = new Resque_Job_Status($token);
$this->assertTrue($status->isTracking()); $this->assertTrue($status->isTracking());
} }
public function testJobStatusIsReturnedViaJobInstance() public function testJobStatusIsReturnedViaJobInstance()
{ {
$token = Resque::enqueue('jobs', 'Test_Job', null, true); $token = Resque::enqueue('jobs', 'Test_Job', null, true);
$job = Resque_Job::reserve('jobs'); $job = Resque_Job::reserve('jobs');
$this->assertEquals(Resque_Job_Status::STATUS_WAITING, $job->getStatus()); $this->assertEquals(Resque_Job_Status::STATUS_WAITING, $job->getStatus());
} }
public function testQueuedJobReturnsQueuedStatus() public function testQueuedJobReturnsQueuedStatus()
{ {
$token = Resque::enqueue('jobs', 'Test_Job', null, true); $token = Resque::enqueue('jobs', 'Test_Job', null, true);
$status = new Resque_Job_Status($token); $status = new Resque_Job_Status($token);
$this->assertEquals(Resque_Job_Status::STATUS_WAITING, $status->get()); $this->assertEquals(Resque_Job_Status::STATUS_WAITING, $status->get());
} }
public function testRunningJobReturnsRunningStatus() public function testRunningJobReturnsRunningStatus()
{ {
$token = Resque::enqueue('jobs', 'Failing_Job', null, true); $token = Resque::enqueue('jobs', 'Failing_Job', null, true);
$job = $this->worker->reserve(); $job = $this->worker->reserve();
$this->worker->workingOn($job); $this->worker->workingOn($job);
$status = new Resque_Job_Status($token); $status = new Resque_Job_Status($token);
$this->assertEquals(Resque_Job_Status::STATUS_RUNNING, $status->get()); $this->assertEquals(Resque_Job_Status::STATUS_RUNNING, $status->get());
} }
public function testFailedJobReturnsFailedStatus() public function testFailedJobReturnsFailedStatus()
{ {
$token = Resque::enqueue('jobs', 'Failing_Job', null, true); $token = Resque::enqueue('jobs', 'Failing_Job', null, true);
$this->worker->work(0); $this->worker->work(0);
$status = new Resque_Job_Status($token); $status = new Resque_Job_Status($token);
$this->assertEquals(Resque_Job_Status::STATUS_FAILED, $status->get()); $this->assertEquals(Resque_Job_Status::STATUS_FAILED, $status->get());
} }
public function testCompletedJobReturnsCompletedStatus() public function testCompletedJobReturnsCompletedStatus()
{ {
$token = Resque::enqueue('jobs', 'Test_Job', null, true); $token = Resque::enqueue('jobs', 'Test_Job', null, true);
$this->worker->work(0); $this->worker->work(0);
$status = new Resque_Job_Status($token); $status = new Resque_Job_Status($token);
$this->assertEquals(Resque_Job_Status::STATUS_COMPLETE, $status->get()); $this->assertEquals(Resque_Job_Status::STATUS_COMPLETE, $status->get());
} }
public function testStatusIsNotTrackedWhenToldNotTo() public function testStatusIsNotTrackedWhenToldNotTo()
{ {
$token = Resque::enqueue('jobs', 'Test_Job', null, false); $token = Resque::enqueue('jobs', 'Test_Job', null, false);
$status = new Resque_Job_Status($token); $status = new Resque_Job_Status($token);
$this->assertFalse($status->isTracking()); $this->assertFalse($status->isTracking());
} }
public function testStatusTrackingCanBeStopped() public function testStatusTrackingCanBeStopped()
{ {
Resque_Job_Status::create('test'); Resque_Job_Status::create('test');
$status = new Resque_Job_Status('test'); $status = new Resque_Job_Status('test');
$this->assertEquals(Resque_Job_Status::STATUS_WAITING, $status->get()); $this->assertEquals(Resque_Job_Status::STATUS_WAITING, $status->get());
$status->stop(); $status->stop();
$this->assertFalse($status->get()); $this->assertFalse($status->get());
} }
public function testRecreatedJobWithTrackingStillTracksStatus() public function testRecreatedJobWithTrackingStillTracksStatus()
{ {
$originalToken = Resque::enqueue('jobs', 'Test_Job', null, true); $originalToken = Resque::enqueue('jobs', 'Test_Job', null, true);
$job = $this->worker->reserve(); $job = $this->worker->reserve();
// Mark this job as being worked on to ensure that the new status is still // Mark this job as being worked on to ensure that the new status is still
// waiting. // waiting.
$this->worker->workingOn($job); $this->worker->workingOn($job);
// Now recreate it // Now recreate it
$newToken = $job->recreate(); $newToken = $job->recreate();
// Make sure we've got a new job returned // Make sure we've got a new job returned
$this->assertNotEquals($originalToken, $newToken); $this->assertNotEquals($originalToken, $newToken);
// Now check the status of the new job // Now check the status of the new job
$newJob = Resque_Job::reserve('jobs'); $newJob = Resque_Job::reserve('jobs');
$this->assertEquals(Resque_Job_Status::STATUS_WAITING, $newJob->getStatus()); $this->assertEquals(Resque_Job_Status::STATUS_WAITING, $newJob->getStatus());
} }
} }

View File

@ -3,444 +3,446 @@
/** /**
* Resque_Job tests. * Resque_Job tests.
* *
* @package Resque/Tests * @package Resque/Tests
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Tests_JobTest extends Resque_Tests_TestCase class Resque_Tests_JobTest extends Resque_Tests_TestCase
{ {
protected $worker; protected $worker;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
// Register a worker to test with // Register a worker to test with
$this->worker = new Resque_Worker('jobs'); $this->worker = new Resque_Worker('jobs');
$this->worker->setLogger(new Resque_Log()); $this->worker->setLogger(new Resque_Log());
$this->worker->registerWorker(); $this->worker->registerWorker();
} }
public function testJobCanBeQueued() public function testJobCanBeQueued()
{ {
$this->assertTrue((bool)Resque::enqueue('jobs', 'Test_Job')); $this->assertTrue((bool)Resque::enqueue('jobs', 'Test_Job'));
} }
/** /**
* @expectedException Resque_RedisException * @expectedException Resque_RedisException
*/ */
public function testRedisErrorThrowsExceptionOnJobCreation() // public function testRedisErrorThrowsExceptionOnJobCreation()
{ // {
$mockCredis = $this->getMockBuilder('Credis_Client') // $mockCredis = $this->getMockBuilder('Credis_Client')
->setMethods(['connect', '__call']) // ->setMethods(['connect', '__call'])
->getMock(); // ->getMock();
$mockCredis->expects($this->any())->method('__call') // $mockCredis->expects($this->any())->method('__call')
->will($this->throwException(new CredisException('failure'))); // ->will($this->throwException(new CredisException('failure')));
//
// Resque::setBackend(function($database) use ($mockCredis) {
// return new Resque_Redis('localhost:6379', $database, $mockCredis);
// });
// Resque::enqueue('jobs', 'This is a test');
// }
Resque::setBackend(function($database) use ($mockCredis) { public function testQeueuedJobCanBeReserved()
return new Resque_Redis('localhost:6379', $database, $mockCredis); {
}); Resque::enqueue('jobs', 'Test_Job');
Resque::enqueue('jobs', 'This is a test');
}
public function testQeueuedJobCanBeReserved() $job = Resque_Job::reserve('jobs');
{ if ($job == false) {
Resque::enqueue('jobs', 'Test_Job'); $this->fail('Job could not be reserved.');
}
$this->assertEquals('jobs', $job->queue);
$this->assertEquals('Test_Job', $job->payload['class']);
}
$job = Resque_Job::reserve('jobs'); /**
if($job == false) { * @expectedException InvalidArgumentException
$this->fail('Job could not be reserved.'); */
} public function testObjectArgumentsCannotBePassedToJob()
$this->assertEquals('jobs', $job->queue); {
$this->assertEquals('Test_Job', $job->payload['class']); $args = new stdClass;
} $args->test = 'somevalue';
Resque::enqueue('jobs', 'Test_Job', $args);
}
/** public function testQueuedJobReturnsExactSamePassedInArguments()
* @expectedException InvalidArgumentException {
*/ $args = array(
public function testObjectArgumentsCannotBePassedToJob() 'int' => 123,
{ 'numArray' => array(
$args = new stdClass; 1,
$args->test = 'somevalue'; 2,
Resque::enqueue('jobs', 'Test_Job', $args); ),
} 'assocArray' => array(
'key1' => 'value1',
'key2' => 'value2'
),
);
Resque::enqueue('jobs', 'Test_Job', $args);
$job = Resque_Job::reserve('jobs');
public function testQueuedJobReturnsExactSamePassedInArguments() $this->assertEquals($args, $job->getArguments());
{ }
$args = array(
'int' => 123,
'numArray' => array(
1,
2,
),
'assocArray' => array(
'key1' => 'value1',
'key2' => 'value2'
),
);
Resque::enqueue('jobs', 'Test_Job', $args);
$job = Resque_Job::reserve('jobs');
$this->assertEquals($args, $job->getArguments()); public function testAfterJobIsReservedItIsRemoved()
} {
Resque::enqueue('jobs', 'Test_Job');
Resque_Job::reserve('jobs');
$this->assertFalse(Resque_Job::reserve('jobs'));
}
public function testAfterJobIsReservedItIsRemoved() public function testRecreatedJobMatchesExistingJob()
{ {
Resque::enqueue('jobs', 'Test_Job'); $args = array(
Resque_Job::reserve('jobs'); 'int' => 123,
$this->assertFalse(Resque_Job::reserve('jobs')); 'numArray' => array(
} 1,
2,
),
'assocArray' => array(
'key1' => 'value1',
'key2' => 'value2'
),
);
public function testRecreatedJobMatchesExistingJob() Resque::enqueue('jobs', 'Test_Job', $args);
{ $job = Resque_Job::reserve('jobs');
$args = array(
'int' => 123,
'numArray' => array(
1,
2,
),
'assocArray' => array(
'key1' => 'value1',
'key2' => 'value2'
),
);
Resque::enqueue('jobs', 'Test_Job', $args); // Now recreate it
$job = Resque_Job::reserve('jobs'); $job->recreate();
// Now recreate it $newJob = Resque_Job::reserve('jobs');
$job->recreate(); $this->assertEquals($job->payload['class'], $newJob->payload['class']);
$this->assertEquals($job->getArguments(), $newJob->getArguments());
$newJob = Resque_Job::reserve('jobs'); }
$this->assertEquals($job->payload['class'], $newJob->payload['class']);
$this->assertEquals($job->getArguments(), $newJob->getArguments());
}
public function testFailedJobExceptionsAreCaught() public function testFailedJobExceptionsAreCaught()
{ {
$payload = array( $payload = array(
'class' => 'Failing_Job', 'class' => 'Failing_Job',
'args' => null 'args' => null
); );
$job = new Resque_Job('jobs', $payload); $job = new Resque_Job('jobs', $payload);
$job->worker = $this->worker; $job->worker = $this->worker;
$this->worker->perform($job); $this->worker->perform($job);
$this->assertEquals(1, Resque_Stat::get('failed')); $this->assertEquals(1, Resque_Stat::get('failed'));
$this->assertEquals(1, Resque_Stat::get('failed:'.$this->worker)); $this->assertEquals(1, Resque_Stat::get('failed:' . $this->worker));
} }
/** /**
* @expectedException Resque_Exception * @expectedException Resque_Exception
*/ */
public function testJobWithoutPerformMethodThrowsException() public function testJobWithoutPerformMethodThrowsException()
{ {
Resque::enqueue('jobs', 'Test_Job_Without_Perform_Method'); Resque::enqueue('jobs', 'Test_Job_Without_Perform_Method');
$job = $this->worker->reserve(); $job = $this->worker->reserve();
$job->worker = $this->worker; $job->worker = $this->worker;
$job->perform(); $job->perform();
} }
/** /**
* @expectedException Resque_Exception * @expectedException Resque_Exception
*/ */
public function testInvalidJobThrowsException() public function testInvalidJobThrowsException()
{ {
Resque::enqueue('jobs', 'Invalid_Job'); Resque::enqueue('jobs', 'Invalid_Job');
$job = $this->worker->reserve(); $job = $this->worker->reserve();
$job->worker = $this->worker; $job->worker = $this->worker;
$job->perform(); $job->perform();
} }
public function testJobWithSetUpCallbackFiresSetUp() public function testJobWithSetUpCallbackFiresSetUp()
{ {
$payload = array( $payload = array(
'class' => 'Test_Job_With_SetUp', 'class' => 'Test_Job_With_SetUp',
'args' => array( 'args' => array(
'somevar', 'somevar',
'somevar2', 'somevar2',
), ),
); );
$job = new Resque_Job('jobs', $payload); $job = new Resque_Job('jobs', $payload);
$job->perform(); $job->perform();
$this->assertTrue(Test_Job_With_SetUp::$called); $this->assertTrue(Test_Job_With_SetUp::$called);
} }
public function testJobWithTearDownCallbackFiresTearDown() public function testJobWithTearDownCallbackFiresTearDown()
{ {
$payload = array( $payload = array(
'class' => 'Test_Job_With_TearDown', 'class' => 'Test_Job_With_TearDown',
'args' => array( 'args' => array(
'somevar', 'somevar',
'somevar2', 'somevar2',
), ),
); );
$job = new Resque_Job('jobs', $payload); $job = new Resque_Job('jobs', $payload);
$job->perform(); $job->perform();
$this->assertTrue(Test_Job_With_TearDown::$called); $this->assertTrue(Test_Job_With_TearDown::$called);
} }
public function testNamespaceNaming() { public function testNamespaceNaming()
$fixture = array( {
array('test' => 'more:than:one:with:', 'assertValue' => 'more:than:one:with:'), $fixture = array(
array('test' => 'more:than:one:without', 'assertValue' => 'more:than:one:without:'), array('test' => 'more:than:one:with:', 'assertValue' => 'more:than:one:with:'),
array('test' => 'resque', 'assertValue' => 'resque:'), array('test' => 'more:than:one:without', 'assertValue' => 'more:than:one:without:'),
array('test' => 'resque:', 'assertValue' => 'resque:'), array('test' => 'resque', 'assertValue' => 'resque:'),
); array('test' => 'resque:', 'assertValue' => 'resque:'),
);
foreach($fixture as $item) { foreach ($fixture as $item) {
Resque_Redis::prefix($item['test']); Resque_Redis::prefix($item['test']);
$this->assertEquals(Resque_Redis::getPrefix(), $item['assertValue']); $this->assertEquals(Resque_Redis::getPrefix(), $item['assertValue']);
} }
} }
public function testJobWithNamespace() public function testJobWithNamespace()
{ {
Resque_Redis::prefix('php'); Resque_Redis::prefix('php');
$queue = 'jobs'; $queue = 'jobs';
$payload = array('another_value'); $payload = array('another_value');
Resque::enqueue($queue, 'Test_Job_With_TearDown', $payload); Resque::enqueue($queue, 'Test_Job_With_TearDown', $payload);
$this->assertEquals(Resque::queues(), array('jobs')); $this->assertEquals(Resque::queues(), array('jobs'));
$this->assertEquals(Resque::size($queue), 1); $this->assertEquals(Resque::size($queue), 1);
Resque_Redis::prefix('resque'); Resque_Redis::prefix('resque');
$this->assertEquals(Resque::size($queue), 0); $this->assertEquals(Resque::size($queue), 0);
} }
public function testDequeueAll() public function testDequeueAll()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
$this->assertEquals(Resque::dequeue($queue), 2); $this->assertEquals(Resque::dequeue($queue), 2);
$this->assertEquals(Resque::size($queue), 0); $this->assertEquals(Resque::size($queue), 0);
} }
public function testDequeueMakeSureNotDeleteOthers() public function testDequeueMakeSureNotDeleteOthers()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
$other_queue = 'other_jobs'; $other_queue = 'other_jobs';
Resque::enqueue($other_queue, 'Test_Job_Dequeue'); Resque::enqueue($other_queue, 'Test_Job_Dequeue');
Resque::enqueue($other_queue, 'Test_Job_Dequeue'); Resque::enqueue($other_queue, 'Test_Job_Dequeue');
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
$this->assertEquals(Resque::size($other_queue), 2); $this->assertEquals(Resque::size($other_queue), 2);
$this->assertEquals(Resque::dequeue($queue), 2); $this->assertEquals(Resque::dequeue($queue), 2);
$this->assertEquals(Resque::size($queue), 0); $this->assertEquals(Resque::size($queue), 0);
$this->assertEquals(Resque::size($other_queue), 2); $this->assertEquals(Resque::size($other_queue), 2);
} }
public function testDequeueSpecificItem() public function testDequeueSpecificItem()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue1'); Resque::enqueue($queue, 'Test_Job_Dequeue1');
Resque::enqueue($queue, 'Test_Job_Dequeue2'); Resque::enqueue($queue, 'Test_Job_Dequeue2');
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
$test = array('Test_Job_Dequeue2'); $test = array('Test_Job_Dequeue2');
$this->assertEquals(Resque::dequeue($queue, $test), 1); $this->assertEquals(Resque::dequeue($queue, $test), 1);
$this->assertEquals(Resque::size($queue), 1); $this->assertEquals(Resque::size($queue), 1);
} }
public function testDequeueSpecificMultipleItems() public function testDequeueSpecificMultipleItems()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue1'); Resque::enqueue($queue, 'Test_Job_Dequeue1');
Resque::enqueue($queue, 'Test_Job_Dequeue2'); Resque::enqueue($queue, 'Test_Job_Dequeue2');
Resque::enqueue($queue, 'Test_Job_Dequeue3'); Resque::enqueue($queue, 'Test_Job_Dequeue3');
$this->assertEquals(Resque::size($queue), 3); $this->assertEquals(Resque::size($queue), 3);
$test = array('Test_Job_Dequeue2', 'Test_Job_Dequeue3'); $test = array('Test_Job_Dequeue2', 'Test_Job_Dequeue3');
$this->assertEquals(Resque::dequeue($queue, $test), 2); $this->assertEquals(Resque::dequeue($queue, $test), 2);
$this->assertEquals(Resque::size($queue), 1); $this->assertEquals(Resque::size($queue), 1);
} }
public function testDequeueNonExistingItem() public function testDequeueNonExistingItem()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue1'); Resque::enqueue($queue, 'Test_Job_Dequeue1');
Resque::enqueue($queue, 'Test_Job_Dequeue2'); Resque::enqueue($queue, 'Test_Job_Dequeue2');
Resque::enqueue($queue, 'Test_Job_Dequeue3'); Resque::enqueue($queue, 'Test_Job_Dequeue3');
$this->assertEquals(Resque::size($queue), 3); $this->assertEquals(Resque::size($queue), 3);
$test = array('Test_Job_Dequeue4'); $test = array('Test_Job_Dequeue4');
$this->assertEquals(Resque::dequeue($queue, $test), 0); $this->assertEquals(Resque::dequeue($queue, $test), 0);
$this->assertEquals(Resque::size($queue), 3); $this->assertEquals(Resque::size($queue), 3);
} }
public function testDequeueNonExistingItem2() public function testDequeueNonExistingItem2()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue1'); Resque::enqueue($queue, 'Test_Job_Dequeue1');
Resque::enqueue($queue, 'Test_Job_Dequeue2'); Resque::enqueue($queue, 'Test_Job_Dequeue2');
Resque::enqueue($queue, 'Test_Job_Dequeue3'); Resque::enqueue($queue, 'Test_Job_Dequeue3');
$this->assertEquals(Resque::size($queue), 3); $this->assertEquals(Resque::size($queue), 3);
$test = array('Test_Job_Dequeue4', 'Test_Job_Dequeue1'); $test = array('Test_Job_Dequeue4', 'Test_Job_Dequeue1');
$this->assertEquals(Resque::dequeue($queue, $test), 1); $this->assertEquals(Resque::dequeue($queue, $test), 1);
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
} }
public function testDequeueItemID() public function testDequeueItemID()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
$qid = Resque::enqueue($queue, 'Test_Job_Dequeue'); $qid = Resque::enqueue($queue, 'Test_Job_Dequeue');
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
$test = array('Test_Job_Dequeue' => $qid); $test = array('Test_Job_Dequeue' => $qid);
$this->assertEquals(Resque::dequeue($queue, $test), 1); $this->assertEquals(Resque::dequeue($queue, $test), 1);
$this->assertEquals(Resque::size($queue), 1); $this->assertEquals(Resque::size($queue), 1);
} }
public function testDequeueWrongItemID() public function testDequeueWrongItemID()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
$qid = Resque::enqueue($queue, 'Test_Job_Dequeue'); $qid = Resque::enqueue($queue, 'Test_Job_Dequeue');
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
#qid right but class name is wrong #qid right but class name is wrong
$test = array('Test_Job_Dequeue1' => $qid); $test = array('Test_Job_Dequeue1' => $qid);
$this->assertEquals(Resque::dequeue($queue, $test), 0); $this->assertEquals(Resque::dequeue($queue, $test), 0);
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
} }
public function testDequeueWrongItemID2() public function testDequeueWrongItemID2()
{ {
$queue = 'jobs'; $queue = 'jobs';
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
$qid = Resque::enqueue($queue, 'Test_Job_Dequeue'); $qid = Resque::enqueue($queue, 'Test_Job_Dequeue');
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
$test = array('Test_Job_Dequeue' => 'r4nD0mH4sh3dId'); $test = array('Test_Job_Dequeue' => 'r4nD0mH4sh3dId');
$this->assertEquals(Resque::dequeue($queue, $test), 0); $this->assertEquals(Resque::dequeue($queue, $test), 0);
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
} }
public function testDequeueItemWithArg() public function testDequeueItemWithArg()
{ {
$queue = 'jobs'; $queue = 'jobs';
$arg = array('foo' => 1, 'bar' => 2); $arg = array('foo' => 1, 'bar' => 2);
Resque::enqueue($queue, 'Test_Job_Dequeue9'); Resque::enqueue($queue, 'Test_Job_Dequeue9');
Resque::enqueue($queue, 'Test_Job_Dequeue9', $arg); Resque::enqueue($queue, 'Test_Job_Dequeue9', $arg);
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
$test = array('Test_Job_Dequeue9' => $arg); $test = array('Test_Job_Dequeue9' => $arg);
$this->assertEquals(Resque::dequeue($queue, $test), 1); $this->assertEquals(Resque::dequeue($queue, $test), 1);
#$this->assertEquals(Resque::size($queue), 1); #$this->assertEquals(Resque::size($queue), 1);
} }
public function testDequeueSeveralItemsWithArgs() public function testDequeueSeveralItemsWithArgs()
{ {
// GIVEN // GIVEN
$queue = 'jobs'; $queue = 'jobs';
$args = array('foo' => 1, 'bar' => 10); $args = array('foo' => 1, 'bar' => 10);
$removeArgs = array('foo' => 1, 'bar' => 2); $removeArgs = array('foo' => 1, 'bar' => 2);
Resque::enqueue($queue, 'Test_Job_Dequeue9', $args); Resque::enqueue($queue, 'Test_Job_Dequeue9', $args);
Resque::enqueue($queue, 'Test_Job_Dequeue9', $removeArgs); Resque::enqueue($queue, 'Test_Job_Dequeue9', $removeArgs);
Resque::enqueue($queue, 'Test_Job_Dequeue9', $removeArgs); Resque::enqueue($queue, 'Test_Job_Dequeue9', $removeArgs);
$this->assertEquals(Resque::size($queue), 3); $this->assertEquals(Resque::size($queue), 3);
// WHEN // WHEN
$test = array('Test_Job_Dequeue9' => $removeArgs); $test = array('Test_Job_Dequeue9' => $removeArgs);
$removedItems = Resque::dequeue($queue, $test); $removedItems = Resque::dequeue($queue, $test);
// THEN // THEN
$this->assertEquals($removedItems, 2); $this->assertEquals($removedItems, 2);
$this->assertEquals(Resque::size($queue), 1); $this->assertEquals(Resque::size($queue), 1);
$item = Resque::pop($queue); $item = Resque::pop($queue);
$this->assertInternalType('array', $item['args']); $this->assertInternalType('array', $item['args']);
$this->assertEquals(10, $item['args'][0]['bar'], 'Wrong items were dequeued from queue!'); $this->assertEquals(10, $item['args'][0]['bar'], 'Wrong items were dequeued from queue!');
} }
public function testDequeueItemWithUnorderedArg() public function testDequeueItemWithUnorderedArg()
{ {
$queue = 'jobs'; $queue = 'jobs';
$arg = array('foo' => 1, 'bar' => 2); $arg = array('foo' => 1, 'bar' => 2);
$arg2 = array('bar' => 2, 'foo' => 1); $arg2 = array('bar' => 2, 'foo' => 1);
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
Resque::enqueue($queue, 'Test_Job_Dequeue', $arg); Resque::enqueue($queue, 'Test_Job_Dequeue', $arg);
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
$test = array('Test_Job_Dequeue' => $arg2); $test = array('Test_Job_Dequeue' => $arg2);
$this->assertEquals(Resque::dequeue($queue, $test), 1); $this->assertEquals(Resque::dequeue($queue, $test), 1);
$this->assertEquals(Resque::size($queue), 1); $this->assertEquals(Resque::size($queue), 1);
} }
public function testDequeueItemWithiWrongArg() public function testDequeueItemWithiWrongArg()
{ {
$queue = 'jobs'; $queue = 'jobs';
$arg = array('foo' => 1, 'bar' => 2); $arg = array('foo' => 1, 'bar' => 2);
$arg2 = array('foo' => 2, 'bar' => 3); $arg2 = array('foo' => 2, 'bar' => 3);
Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue');
Resque::enqueue($queue, 'Test_Job_Dequeue', $arg); Resque::enqueue($queue, 'Test_Job_Dequeue', $arg);
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
$test = array('Test_Job_Dequeue' => $arg2); $test = array('Test_Job_Dequeue' => $arg2);
$this->assertEquals(Resque::dequeue($queue, $test), 0); $this->assertEquals(Resque::dequeue($queue, $test), 0);
$this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($queue), 2);
} }
public function testUseDefaultFactoryToGetJobInstance() public function testUseDefaultFactoryToGetJobInstance()
{ {
$payload = array( $payload = array(
'class' => 'Some_Job_Class', 'class' => 'Some_Job_Class',
'args' => null 'args' => null
); );
$job = new Resque_Job('jobs', $payload); $job = new Resque_Job('jobs', $payload);
$instance = $job->getInstance(); $instance = $job->getInstance();
$this->assertInstanceOf('Some_Job_Class', $instance); $this->assertInstanceOf('Some_Job_Class', $instance);
} }
public function testUseFactoryToGetJobInstance() public function testUseFactoryToGetJobInstance()
{ {
$payload = array( $payload = array(
'class' => 'Some_Job_Class', 'class' => 'Some_Job_Class',
'args' => array(array()) 'args' => array(array())
); );
$job = new Resque_Job('jobs', $payload); $job = new Resque_Job('jobs', $payload);
$factory = new Some_Stub_Factory(); $factory = new Some_Stub_Factory();
$job->setJobFactory($factory); $job->setJobFactory($factory);
$instance = $job->getInstance(); $instance = $job->getInstance();
$this->assertInstanceOf('Resque_JobInterface', $instance); $this->assertInstanceOf('Resque_JobInterface', $instance);
} }
public function testDoNotUseFactoryToGetInstance() public function testDoNotUseFactoryToGetInstance()
{ {
$payload = array( $payload = array(
'class' => 'Some_Job_Class', 'class' => 'Some_Job_Class',
'args' => array(array()) 'args' => array(array())
); );
$job = new Resque_Job('jobs', $payload); $job = new Resque_Job('jobs', $payload);
$factory = $this->getMock('Resque_Job_FactoryInterface'); $factory = $this->getMock('Resque_Job_FactoryInterface');
$testJob = $this->getMock('Resque_JobInterface'); $testJob = $this->getMock('Resque_JobInterface');
$factory->expects(self::never())->method('create')->will(self::returnValue($testJob)); $factory->expects(self::never())->method('create')->will(self::returnValue($testJob));
$instance = $job->getInstance(); $instance = $job->getInstance();
$this->assertInstanceOf('Resque_JobInterface', $instance); $this->assertInstanceOf('Resque_JobInterface', $instance);
} }
} }
class Some_Job_Class implements Resque_JobInterface class Some_Job_Class implements Resque_JobInterface
{ {
/** /**
* @return bool * @return bool
*/ */
public function perform() public function perform()
{ {
return true; return true;
} }
} }
class Some_Stub_Factory implements Resque_Job_FactoryInterface class Some_Stub_Factory implements Resque_Job_FactoryInterface
{ {
/** /**
* @param $className * @param $className
* @param array $args * @param array $args
* @param $queue * @param $queue
* @return Resque_JobInterface * @return Resque_JobInterface
*/ */
public function create($className, $args, $queue) public function create($className, $args, $queue)
{ {
return new Some_Job_Class(); return new Some_Job_Class();
} }
} }

View File

@ -1,31 +1,33 @@
<?php <?php
/** /**
* Resque_Log tests. * Resque_Log tests.
* *
* @package Resque/Tests * @package Resque/Tests
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Tests_LogTest extends Resque_Tests_TestCase class Resque_Tests_LogTest extends Resque_Tests_TestCase
{ {
public function testLogInterpolate() public function testLogInterpolate()
{ {
$logger = new Resque_Log(); $logger = new Resque_Log();
$actual = $logger->interpolate('string {replace}', array('replace' => 'value')); $actual = $logger->interpolate('string {replace}', array('replace' => 'value'));
$expected = 'string value'; $expected = 'string value';
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
public function testLogInterpolateMutiple() public function testLogInterpolateMutiple()
{ {
$logger = new Resque_Log(); $logger = new Resque_Log();
$actual = $logger->interpolate( $actual = $logger->interpolate(
'string {replace1} {replace2}', 'string {replace1} {replace2}',
array('replace1' => 'value1', 'replace2' => 'value2') array('replace1' => 'value1', 'replace2' => 'value2')
); );
$expected = 'string value1 value2'; $expected = 'string value1 value2';
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
} }

View File

@ -1,197 +1,199 @@
<?php <?php
/** /**
* Resque_Event tests. * Resque_Event tests.
* *
* @package Resque/Tests * @package Resque/Tests
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Tests_RedisTest extends Resque_Tests_TestCase class Resque_Tests_RedisTest extends Resque_Tests_TestCase
{ {
/** /**
* @expectedException Resque_RedisException * @expectedException Resque_RedisException
*/ */
public function testRedisExceptionsAreSurfaced() // public function testRedisExceptionsAreSurfaced()
{ // {
$mockCredis = $this->getMockBuilder('Credis_Client') // $mockCredis = $this->getMockBuilder('Credis_Client')
->setMethods(['connect', '__call']) // ->setMethods(['connect', '__call'])
->getMock(); // ->getMock();
$mockCredis->expects($this->any())->method('__call') // $mockCredis->expects($this->any())->method('__call')
->will($this->throwException(new CredisException('failure'))); // ->will($this->throwException(new CredisException('failure')));
//
// Resque::setBackend(function($database) use ($mockCredis) {
// return new Resque_Redis('localhost:6379', $database, $mockCredis);
// });
// Resque::redis()->ping();
// }
Resque::setBackend(function($database) use ($mockCredis) { /**
return new Resque_Redis('localhost:6379', $database, $mockCredis); * These DNS strings are considered valid.
}); *
Resque::redis()->ping(); * @return array
} */
public function validDsnStringProvider()
{
return [
// Input , Expected output
['', [
'localhost',
Resque_Redis::DEFAULT_PORT,
false,
false, false,
[],
]],
['localhost', [
'localhost',
Resque_Redis::DEFAULT_PORT,
false,
false, false,
[],
]],
['localhost:1234', [
'localhost',
1234,
false,
false, false,
[],
]],
['localhost:1234/2', [
'localhost',
1234,
2,
false, false,
[],
]],
['redis://foobar', [
'foobar',
Resque_Redis::DEFAULT_PORT,
false,
false, false,
[],
]],
['redis://foobar/', [
'foobar',
Resque_Redis::DEFAULT_PORT,
false,
false, false,
[],
]],
['redis://foobar:1234', [
'foobar',
1234,
false,
false, false,
[],
]],
['redis://foobar:1234/15', [
'foobar',
1234,
15,
false, false,
[],
]],
['redis://foobar:1234/0', [
'foobar',
1234,
0,
false, false,
[],
]],
['redis://user@foobar:1234', [
'foobar',
1234,
false,
'user', false,
[],
]],
['redis://user@foobar:1234/15', [
'foobar',
1234,
15,
'user', false,
[],
]],
['redis://user:pass@foobar:1234', [
'foobar',
1234,
false,
'user', 'pass',
[],
]],
['redis://user:pass@foobar:1234?x=y&a=b', [
'foobar',
1234,
false,
'user', 'pass',
['x' => 'y', 'a' => 'b'],
]],
['redis://:pass@foobar:1234?x=y&a=b', [
'foobar',
1234,
false,
false, 'pass',
['x' => 'y', 'a' => 'b'],
]],
['redis://user@foobar:1234?x=y&a=b', [
'foobar',
1234,
false,
'user', false,
['x' => 'y', 'a' => 'b'],
]],
['redis://foobar:1234?x=y&a=b', [
'foobar',
1234,
false,
false, false,
['x' => 'y', 'a' => 'b'],
]],
['redis://user@foobar:1234/12?x=y&a=b', [
'foobar',
1234,
12,
'user', false,
['x' => 'y', 'a' => 'b'],
]],
['tcp://user@foobar:1234/12?x=y&a=b', [
'foobar',
1234,
12,
'user', false,
['x' => 'y', 'a' => 'b'],
]],
];
}
/** /**
* These DNS strings are considered valid. * These DSN values should throw exceptions
* * @return array
* @return array */
*/ public function bogusDsnStringProvider()
public function validDsnStringProvider() {
{ return [
return array( ['http://foo.bar/'],
// Input , Expected output ['user:@foobar:1234?x=y&a=b'],
array('', array( ['foobar:1234?x=y&a=b'],
'localhost', ];
Resque_Redis::DEFAULT_PORT, }
false,
false, false,
array(),
)),
array('localhost', array(
'localhost',
Resque_Redis::DEFAULT_PORT,
false,
false, false,
array(),
)),
array('localhost:1234', array(
'localhost',
1234,
false,
false, false,
array(),
)),
array('localhost:1234/2', array(
'localhost',
1234,
2,
false, false,
array(),
)),
array('redis://foobar', array(
'foobar',
Resque_Redis::DEFAULT_PORT,
false,
false, false,
array(),
)),
array('redis://foobar/', array(
'foobar',
Resque_Redis::DEFAULT_PORT,
false,
false, false,
array(),
)),
array('redis://foobar:1234', array(
'foobar',
1234,
false,
false, false,
array(),
)),
array('redis://foobar:1234/15', array(
'foobar',
1234,
15,
false, false,
array(),
)),
array('redis://foobar:1234/0', array(
'foobar',
1234,
0,
false, false,
array(),
)),
array('redis://user@foobar:1234', array(
'foobar',
1234,
false,
'user', false,
array(),
)),
array('redis://user@foobar:1234/15', array(
'foobar',
1234,
15,
'user', false,
array(),
)),
array('redis://user:pass@foobar:1234', array(
'foobar',
1234,
false,
'user', 'pass',
array(),
)),
array('redis://user:pass@foobar:1234?x=y&a=b', array(
'foobar',
1234,
false,
'user', 'pass',
array('x' => 'y', 'a' => 'b'),
)),
array('redis://:pass@foobar:1234?x=y&a=b', array(
'foobar',
1234,
false,
false, 'pass',
array('x' => 'y', 'a' => 'b'),
)),
array('redis://user@foobar:1234?x=y&a=b', array(
'foobar',
1234,
false,
'user', false,
array('x' => 'y', 'a' => 'b'),
)),
array('redis://foobar:1234?x=y&a=b', array(
'foobar',
1234,
false,
false, false,
array('x' => 'y', 'a' => 'b'),
)),
array('redis://user@foobar:1234/12?x=y&a=b', array(
'foobar',
1234,
12,
'user', false,
array('x' => 'y', 'a' => 'b'),
)),
array('tcp://user@foobar:1234/12?x=y&a=b', array(
'foobar',
1234,
12,
'user', false,
array('x' => 'y', 'a' => 'b'),
)),
);
}
/** /**
* These DSN values should throw exceptions * @dataProvider validDsnStringProvider
* @return array */
*/ public function testParsingValidDsnString($dsn, $expected)
public function bogusDsnStringProvider() {
{ $result = Resque_Redis::parseDsn($dsn);
return array( $this->assertEquals($expected, $result);
array('http://foo.bar/'), }
array('user:@foobar:1234?x=y&a=b'),
array('foobar:1234?x=y&a=b'),
);
}
/** /**
* @dataProvider validDsnStringProvider * @dataProvider bogusDsnStringProvider
*/ * @expectedException InvalidArgumentException
public function testParsingValidDsnString($dsn, $expected) */
{ public function testParsingBogusDsnStringThrowsException($dsn)
$result = Resque_Redis::parseDsn($dsn); {
$this->assertEquals($expected, $result); // The next line should throw an InvalidArgumentException
} Resque_Redis::parseDsn($dsn);
}
/**
* @dataProvider bogusDsnStringProvider
* @expectedException InvalidArgumentException
*/
public function testParsingBogusDsnStringThrowsException($dsn)
{
// The next line should throw an InvalidArgumentException
$result = Resque_Redis::parseDsn($dsn);
}
} }

View File

@ -1,49 +1,51 @@
<?php <?php
/** /**
* Resque_Stat tests. * Resque_Stat tests.
* *
* @package Resque/Tests * @package Resque/Tests
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Tests_StatTest extends Resque_Tests_TestCase class Resque_Tests_StatTest extends Resque_Tests_TestCase
{ {
public function testStatCanBeIncremented() public function testStatCanBeIncremented()
{ {
Resque_Stat::incr('test_incr'); Resque_Stat::incr('test_incr');
Resque_Stat::incr('test_incr'); Resque_Stat::incr('test_incr');
$this->assertEquals(2, $this->redis->get('resque:stat:test_incr')); $this->assertEquals(2, $this->redis->get('resque:stat:test_incr'));
} }
public function testStatCanBeIncrementedByX() public function testStatCanBeIncrementedByX()
{ {
Resque_Stat::incr('test_incrX', 10); Resque_Stat::incr('test_incrX', 10);
Resque_Stat::incr('test_incrX', 11); Resque_Stat::incr('test_incrX', 11);
$this->assertEquals(21, $this->redis->get('resque:stat:test_incrX')); $this->assertEquals(21, $this->redis->get('resque:stat:test_incrX'));
} }
public function testStatCanBeDecremented() public function testStatCanBeDecremented()
{ {
Resque_Stat::incr('test_decr', 22); Resque_Stat::incr('test_decr', 22);
Resque_Stat::decr('test_decr'); Resque_Stat::decr('test_decr');
$this->assertEquals(21, $this->redis->get('resque:stat:test_decr')); $this->assertEquals(21, $this->redis->get('resque:stat:test_decr'));
} }
public function testStatCanBeDecrementedByX() public function testStatCanBeDecrementedByX()
{ {
Resque_Stat::incr('test_decrX', 22); Resque_Stat::incr('test_decrX', 22);
Resque_Stat::decr('test_decrX', 11); Resque_Stat::decr('test_decrX', 11);
$this->assertEquals(11, $this->redis->get('resque:stat:test_decrX')); $this->assertEquals(11, $this->redis->get('resque:stat:test_decrX'));
} }
public function testGetStatByName() public function testGetStatByName()
{ {
Resque_Stat::incr('test_get', 100); Resque_Stat::incr('test_get', 100);
$this->assertEquals(100, Resque_Stat::get('test_get')); $this->assertEquals(100, Resque_Stat::get('test_get'));
} }
public function testGetUnknownStatReturns0() public function testGetUnknownStatReturns0()
{ {
$this->assertEquals(0, Resque_Stat::get('test_get_unknown')); $this->assertEquals(0, Resque_Stat::get('test_get_unknown'));
} }
} }

View File

@ -1,30 +1,34 @@
<?php <?php
/** /**
* Resque test case class. Contains setup and teardown methods. * Resque test case class. Contains setup and teardown methods.
* *
* @package Resque/Tests * @package Resque/Tests
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Tests_TestCase extends PHPUnit_Framework_TestCase
class Resque_Tests_TestCase extends PHPUnit\Framework\TestCase
{ {
protected $resque; protected $resque;
protected $redis; protected $redis;
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
} }
public function setUp() public function setUp()
{ {
$config = file_get_contents(REDIS_CONF); // $config = file_get_contents(REDIS_CONF);
preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches); // preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches);
$this->redis = new Credis_Client('localhost', $matches[1]); $this->redis = new \Redis();
$this->redis->connect('localhost');
$this->redis->select(9);
Resque::setBackend('redis://localhost:' . $matches[1]); Resque::setBackend('localhost', 9);
// Flush redis // Flush redis
$this->redis->flushAll(); $this->redis->flushAll();
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Resque_Worker tests. * Resque_Worker tests.
* *
@ -6,6 +7,7 @@
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
class Resque_Tests_WorkerTest extends Resque_Tests_TestCase class Resque_Tests_WorkerTest extends Resque_Tests_TestCase
{ {
public function testWorkerRegistersInList() public function testWorkerRegistersInList()

View File

@ -2,9 +2,9 @@
/** /**
* Resque test bootstrap file - sets up a test environment. * Resque test bootstrap file - sets up a test environment.
* *
* @package Resque/Tests * @package Resque/Tests
* @author Chris Boulton <chris@bigcommerce.com> * @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php * @license http://www.opensource.org/licenses/mit-license.php
*/ */
$loader = require __DIR__ . '/../vendor/autoload.php'; $loader = require __DIR__ . '/../vendor/autoload.php';
@ -15,24 +15,24 @@ define('REDIS_CONF', TEST_MISC . '/redis.conf');
// Attempt to start our own redis instance for tesitng. // Attempt to start our own redis instance for tesitng.
exec('which redis-server', $output, $returnVar); exec('which redis-server', $output, $returnVar);
if($returnVar != 0) { if ($returnVar != 0) {
echo "Cannot find redis-server in path. Please make sure redis is installed.\n"; echo "Cannot find redis-server in path. Please make sure redis is installed.\n";
exit(1); exit(1);
} }
exec('cd ' . TEST_MISC . '; redis-server ' . REDIS_CONF, $output, $returnVar); exec('cd ' . TEST_MISC . '; redis-server ' . REDIS_CONF, $output, $returnVar);
usleep(500000); usleep(500000);
if($returnVar != 0) { if ($returnVar != 0) {
echo "Cannot start redis-server.\n"; echo "Cannot start redis-server.\n";
exit(1); exit(1);
} }
// Get redis port from conf // Get redis port from conf
$config = file_get_contents(REDIS_CONF); $config = file_get_contents(REDIS_CONF);
if(!preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches)) { if (!preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches)) {
echo "Could not determine redis port from redis.conf"; echo "Could not determine redis port from redis.conf";
exit(1); exit(1);
} }
Resque::setBackend('localhost:' . $matches[1]); Resque::setBackend('localhost:' . $matches[1]);
@ -43,57 +43,59 @@ function killRedis($pid)
if (getmypid() !== $pid) { if (getmypid() !== $pid) {
return; // don't kill from a forked worker return; // don't kill from a forked worker
} }
$config = file_get_contents(REDIS_CONF); $config = file_get_contents(REDIS_CONF);
if(!preg_match('#^\s*pidfile\s+([^\s]+)#m', $config, $matches)) { if (!preg_match('#^\s*pidfile\s+([^\s]+)#m', $config, $matches)) {
return; return;
} }
$pidFile = TEST_MISC . '/' . $matches[1]; $pidFile = TEST_MISC . '/' . $matches[1];
if (file_exists($pidFile)) { if (file_exists($pidFile)) {
$pid = trim(file_get_contents($pidFile)); $pid = trim(file_get_contents($pidFile));
posix_kill((int) $pid, 9); posix_kill((int)$pid, 9);
if(is_file($pidFile)) { if (is_file($pidFile)) {
unlink($pidFile); unlink($pidFile);
} }
} }
// Remove the redis database // Remove the redis database
if(!preg_match('#^\s*dir\s+([^\s]+)#m', $config, $matches)) { if (!preg_match('#^\s*dir\s+([^\s]+)#m', $config, $matches)) {
return; return;
} }
$dir = $matches[1]; $dir = $matches[1];
if(!preg_match('#^\s*dbfilename\s+([^\s]+)#m', $config, $matches)) { if (!preg_match('#^\s*dbfilename\s+([^\s]+)#m', $config, $matches)) {
return; return;
} }
$filename = TEST_MISC . '/' . $dir . '/' . $matches[1]; $filename = TEST_MISC . '/' . $dir . '/' . $matches[1];
if(is_file($filename)) { if (is_file($filename)) {
unlink($filename); unlink($filename);
} }
} }
register_shutdown_function('killRedis', getmypid()); register_shutdown_function('killRedis', getmypid());
if(function_exists('pcntl_signal')) { if (function_exists('pcntl_signal')) {
// Override INT and TERM signals, so they do a clean shutdown and also // Override INT and TERM signals, so they do a clean shutdown and also
// clean up redis-server as well. // clean up redis-server as well.
function sigint() function sigint()
{ {
exit; exit;
} }
pcntl_signal(SIGINT, 'sigint');
pcntl_signal(SIGTERM, 'sigint'); pcntl_signal(SIGINT, 'sigint');
pcntl_signal(SIGTERM, 'sigint');
} }
class Test_Job class Test_Job
{ {
public static $called = false; public static $called = false;
public function perform() public function perform()
{ {
self::$called = true; self::$called = true;
} }
} }
class Failing_Job_Exception extends Exception class Failing_Job_Exception extends Exception
@ -103,10 +105,10 @@ class Failing_Job_Exception extends Exception
class Failing_Job class Failing_Job
{ {
public function perform() public function perform()
{ {
throw new Failing_Job_Exception('Message!'); throw new Failing_Job_Exception('Message!');
} }
} }
class Test_Job_Without_Perform_Method class Test_Job_Without_Perform_Method
@ -116,33 +118,33 @@ class Test_Job_Without_Perform_Method
class Test_Job_With_SetUp class Test_Job_With_SetUp
{ {
public static $called = false; public static $called = false;
public $args = false; public $args = false;
public function setUp() public function setUp()
{ {
self::$called = true; self::$called = true;
} }
public function perform() public function perform()
{ {
} }
} }
class Test_Job_With_TearDown class Test_Job_With_TearDown
{ {
public static $called = false; public static $called = false;
public $args = false; public $args = false;
public function perform() public function perform()
{ {
} }
public function tearDown() public function tearDown()
{ {
self::$called = true; self::$called = true;
} }
} }