Completed
Pull Request — master (#35)
by
unknown
03:32
created
tests/Fixture/QueuedTasksFixture.php 1 patch
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -9,46 +9,46 @@
 block discarded – undo
9 9
 class QueuedTasksFixture extends TestFixture
10 10
 {
11 11
 
12
-    /**
13
-     * Fields
14
-     *
15
-     * @var array
16
-     */
17
-    // @codingStandardsIgnoreStart
18
-    public $fields = [
19
-        'id' => ['type' => 'integer', 'length' => 10, 'unsigned' => true, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
20
-        'task' => ['type' => 'string', 'length' => 255, 'null' => false, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
21
-        'data' => ['type' => 'text', 'length' => 16777215, 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null],
22
-        'not_before' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
23
-        'fetched' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
24
-        'completed' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
25
-        'failed_count' => ['type' => 'integer', 'length' => 10, 'unsigned' => true, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null, 'autoIncrement' => null],
26
-        'failure_message' => ['type' => 'text', 'length' => null, 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null],
27
-        'worker_key' => ['type' => 'string', 'fixed' => true, 'length' => 40, 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null],
28
-        'created' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
29
-        '_indexes' => [
30
-            'completed' => ['type' => 'index', 'columns' => ['completed'], 'length' => []],
31
-            'worker_key' => ['type' => 'index', 'columns' => ['worker_key'], 'length' => []],
32
-            'task' => ['type' => 'index', 'columns' => ['task'], 'length' => []],
33
-        ],
34
-        '_constraints' => [
35
-            'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
36
-        ],
37
-        '_options' => [
38
-            'engine' => 'InnoDB',
39
-            'collation' => 'utf8_general_ci'
40
-        ],
41
-    ];
42
-    // @codingStandardsIgnoreEnd
12
+	/**
13
+	 * Fields
14
+	 *
15
+	 * @var array
16
+	 */
17
+	// @codingStandardsIgnoreStart
18
+	public $fields = [
19
+		'id' => ['type' => 'integer', 'length' => 10, 'unsigned' => true, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
20
+		'task' => ['type' => 'string', 'length' => 255, 'null' => false, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
21
+		'data' => ['type' => 'text', 'length' => 16777215, 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null],
22
+		'not_before' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
23
+		'fetched' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
24
+		'completed' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
25
+		'failed_count' => ['type' => 'integer', 'length' => 10, 'unsigned' => true, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null, 'autoIncrement' => null],
26
+		'failure_message' => ['type' => 'text', 'length' => null, 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null],
27
+		'worker_key' => ['type' => 'string', 'fixed' => true, 'length' => 40, 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null],
28
+		'created' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
29
+		'_indexes' => [
30
+			'completed' => ['type' => 'index', 'columns' => ['completed'], 'length' => []],
31
+			'worker_key' => ['type' => 'index', 'columns' => ['worker_key'], 'length' => []],
32
+			'task' => ['type' => 'index', 'columns' => ['task'], 'length' => []],
33
+		],
34
+		'_constraints' => [
35
+			'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
36
+		],
37
+		'_options' => [
38
+			'engine' => 'InnoDB',
39
+			'collation' => 'utf8_general_ci'
40
+		],
41
+	];
42
+	// @codingStandardsIgnoreEnd
43 43
 
44
-    /**
45
-     * Init method
46
-     *
47
-     * @return void
48
-     */
49
-    public function init()
50
-    {
51
-        $this->records = [];
52
-        parent::init();
53
-    }
44
+	/**
45
+	 * Init method
46
+	 *
47
+	 * @return void
48
+	 */
49
+	public function init()
50
+	{
51
+		$this->records = [];
52
+		parent::init();
53
+	}
54 54
 }
Please login to merge, or discard this patch.
src/Shell/QueueShell.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@
 block discarded – undo
18 18
 use RuntimeException;
19 19
 use Throwable;
20 20
 
21
-declare(ticks = 1);
21
+declare(ticks=1);
22 22
 
23 23
 /**
24 24
  * Main shell to init and run queue workers.
Please login to merge, or discard this patch.
Indentation   +505 added lines, -505 removed lines patch added patch discarded remove patch
@@ -31,521 +31,521 @@
 block discarded – undo
31 31
 class QueueShell extends Shell
32 32
 {
33 33
 
34
-    /**
35
-     *
36
-     * @var string
37
-     */
38
-    public $modelClass = 'Queue.QueuedTasks';
39
-
40
-    /**
41
-     *
42
-     * @var array|null
43
-     */
44
-    protected $_taskConf;
45
-
46
-    /**
47
-     *
48
-     * @var int
49
-     */
50
-    protected $_time = 0;
51
-
52
-    /**
53
-     *
54
-     * @var bool
55
-     */
56
-    protected $_exit = false;
57
-
58
-    /**
59
-     * Overwrite shell initialize to dynamically load all Queue Related Tasks.
60
-     *
61
-     * @return void
62
-     */
63
-    public function initialize()
64
-    {
65
-        $taskFinder = new TaskFinder();
66
-        $this->tasks = $taskFinder->allAppAndPluginTasks();
67
-
68
-        parent::initialize();
69
-    }
70
-
71
-    /**
72
-     *
73
-     * @return void
74
-     */
75
-    public function startup()
76
-    {
77
-        if ($this->param('quiet')) {
78
-            $this->interactive = false;
79
-        }
80
-
81
-        parent::startup();
82
-    }
83
-
84
-    /**
85
-     *
86
-     * @return string
87
-     */
88
-    public function getDescription()
89
-    {
90
-        $tasks = [];
91
-        foreach ($this->taskNames as $loadedTask) {
92
-            $tasks[] = "\t" . '* ' . $this->_taskName($loadedTask);
93
-        }
94
-        $tasks = implode(PHP_EOL, $tasks);
95
-
96
-        $text = <<<TEXT
34
+	/**
35
+	 *
36
+	 * @var string
37
+	 */
38
+	public $modelClass = 'Queue.QueuedTasks';
39
+
40
+	/**
41
+	 *
42
+	 * @var array|null
43
+	 */
44
+	protected $_taskConf;
45
+
46
+	/**
47
+	 *
48
+	 * @var int
49
+	 */
50
+	protected $_time = 0;
51
+
52
+	/**
53
+	 *
54
+	 * @var bool
55
+	 */
56
+	protected $_exit = false;
57
+
58
+	/**
59
+	 * Overwrite shell initialize to dynamically load all Queue Related Tasks.
60
+	 *
61
+	 * @return void
62
+	 */
63
+	public function initialize()
64
+	{
65
+		$taskFinder = new TaskFinder();
66
+		$this->tasks = $taskFinder->allAppAndPluginTasks();
67
+
68
+		parent::initialize();
69
+	}
70
+
71
+	/**
72
+	 *
73
+	 * @return void
74
+	 */
75
+	public function startup()
76
+	{
77
+		if ($this->param('quiet')) {
78
+			$this->interactive = false;
79
+		}
80
+
81
+		parent::startup();
82
+	}
83
+
84
+	/**
85
+	 *
86
+	 * @return string
87
+	 */
88
+	public function getDescription()
89
+	{
90
+		$tasks = [];
91
+		foreach ($this->taskNames as $loadedTask) {
92
+			$tasks[] = "\t" . '* ' . $this->_taskName($loadedTask);
93
+		}
94
+		$tasks = implode(PHP_EOL, $tasks);
95
+
96
+		$text = <<<TEXT
97 97
 Simple and minimalistic job queue (or deferred-task) system.
98 98
 
99 99
 Available Tasks:
100 100
 $tasks
101 101
 TEXT;
102 102
 
103
-        return $text;
104
-    }
105
-
106
-    /**
107
-     * Look for a Queue Task of hte passed name and try to call add() on it.
108
-     * A QueueTask may provide an add function to enable the user to create new jobs via commandline.
109
-     *
110
-     * @return void
111
-     */
112
-    public function add()
113
-    {
114
-        if (count($this->args) < 1) {
115
-            $this->out('Please call like this:');
116
-            $this->out('       bin/cake queue add <taskname>');
117
-            $this->_displayAvailableTasks();
118
-
119
-            return;
120
-        }
121
-
122
-        $name = Inflector::camelize($this->args[0]);
123
-        if (in_array('Queue' . $name, $this->taskNames, true)) {
124
-            /** @var \Queue\Shell\Task\QueueTask|\Queue\Shell\Task\AddInterface $task */
125
-            $task = $this->{'Queue' . $name};
126
-            if (!($task instanceof AddInterface)) {
127
-                $this->abort('This task does not support adding via CLI call');
128
-            }
129
-            $task->add();
130
-        } else {
131
-            $this->out('Error: Task not found: ' . $name);
132
-            $this->_displayAvailableTasks();
133
-        }
134
-    }
135
-
136
-    /**
137
-     * Output the task without Queue or Task
138
-     * example: QueueImageTask becomes Image on display
139
-     *
140
-     * @param string $task Task name
141
-     * @return string Cleaned task name
142
-     */
143
-    protected function _taskName($task)
144
-    {
145
-        if (strpos($task, 'Queue') === 0) {
146
-            return substr($task, 5);
147
-        }
148
-
149
-        return $task;
150
-    }
151
-
152
-    /**
153
-     * Run a QueueWorker loop.
154
-     * Runs a Queue Worker process which will try to find unassigned jobs in the queue
155
-     * which it may run and try to fetch and execute them.
156
-     *
157
-     * @return int|null
158
-     */
159
-    public function runworker()
160
-    {
161
-        // Enable Garbage Collector (PHP >= 5.3)
162
-        if (function_exists('gc_enable')) {
163
-            gc_enable();
164
-        }
165
-        if (function_exists('pcntl_signal')) {
166
-            pcntl_signal(SIGTERM, [
167
-                &$this,
168
-                '_exit'
169
-            ]);
170
-            pcntl_signal(SIGINT, [
171
-                &$this,
172
-                '_exit'
173
-            ]);
174
-            pcntl_signal(SIGTSTP, [
175
-                &$this,
176
-                '_exit'
177
-            ]);
178
-            pcntl_signal(SIGQUIT, [
179
-                &$this,
180
-                '_exit'
181
-            ]);
182
-        }
183
-        $this->_exit = false;
184
-
185
-        $startTime = time();
186
-        $types = $this->_stringToArray($this->param('type'));
187
-
188
-        while (!$this->_exit) {
189
-            $this->out(__d('queue', 'Looking for a job.'), 1, Shell::VERBOSE);
190
-
191
-            $QueuedTask = $this->QueuedTasks->requestJob($this->_getTaskConf(), $types);
192
-
193
-            if ($QueuedTask) {
194
-                $this->runJob($QueuedTask);
195
-            } elseif (Configure::read('Queue.exitWhenNothingToDo')) {
196
-                $this->out(__d('queue', 'nothing to do, exiting.'));
197
-                $this->_exit = true;
198
-            } else {
199
-                $this->out(__d('queue', 'nothing to do, sleeping.'));
200
-                sleep(Config::sleepTime());
201
-            }
202
-
203
-            // check if we are over the maximum runtime and end processing if so.
204
-            if (Configure::readOrFail('Queue.workerMaxRuntime') && (time() - $startTime) >= Configure::readOrFail('Queue.workerMaxRuntime')) {
205
-                $this->_exit = true;
206
-                $this->out(__d('queue', 'Reached runtime of ' . (time() - $startTime) . ' Seconds (Max ' . Configure::readOrFail('Queue.workerMaxRuntime') . '), terminating.'));
207
-            }
208
-            if ($this->_exit || mt_rand(0, 100) > (100 - (int)Config::gcprob())) {
209
-                $this->out(__d('queue', 'Performing old job cleanup.'));
210
-                $this->QueuedTasks->cleanOldJobs();
211
-            }
212
-            $this->hr();
213
-        }
214
-
215
-        if ($this->param('verbose')) {
216
-            $this->_log('endworker');
217
-        }
218
-    }
219
-
220
-    /**
221
-     *
222
-     * @param \Queue\Model\Entity\QueuedTask $QueuedTask Queued task
223
-     * @return void
224
-     */
225
-    protected function runJob(QueuedTask $QueuedTask)
226
-    {
227
-        $this->out('Running Job of type "' . $QueuedTask->task . '"');
228
-        $this->_log('job ' . $QueuedTask->task . ', id ' . $QueuedTask->id, null, false);
229
-        $taskName = 'Queue' . $QueuedTask->task;
230
-
231
-        try {
232
-            $this->_time = time();
233
-
234
-            $data = unserialize($QueuedTask->data);
235
-            /** @var \Queue\Shell\Task\QueueTask $task */
236
-            $task = $this->{$taskName};
237
-            if (!$task instanceof QueueTaskInterface) {
238
-                throw new RuntimeException('Task must implement ' . QueueTaskInterface::class);
239
-            }
240
-
241
-            $return = $task->run((array)$data, $QueuedTask->id);
242
-            if ($return !== null) {
243
-                trigger_error('run() should be void and throw exception in error case now.', E_USER_DEPRECATED);
244
-            }
245
-            $failureMessage = $taskName . ' failed';
246
-        } catch (Throwable $e) {
247
-            $return = false;
248
-
249
-            $failureMessage = get_class($e) . ': ' . $e->getMessage();
250
-            if (!($e instanceof QueueException)) {
251
-                $failureMessage .= "\n" . $e->getTraceAsString();
252
-            }
253
-
254
-            $this->_logError($taskName . ' (job ' . $QueuedTask->id . ')' . "\n" . $failureMessage);
255
-        } catch (Exception $e) {
256
-            $return = false;
257
-
258
-            $failureMessage = get_class($e) . ': ' . $e->getMessage();
259
-            $this->_logError($taskName . "\n" . $failureMessage);
260
-        }
261
-
262
-        if ($return === false) {
263
-            $this->QueuedTasks->markJobFailed($QueuedTask, $failureMessage);
264
-            $failedStatus = $this->QueuedTasks->getFailedStatus($QueuedTask, $this->_getTaskConf());
265
-            $this->_log('job ' . $QueuedTask->task . ', id ' . $QueuedTask->id . ' failed and ' . $failedStatus);
266
-            $this->out('Job did not finish, ' . $failedStatus . ' after try ' . $QueuedTask->failed . '.');
267
-
268
-            return;
269
-        }
270
-
271
-        $this->QueuedTasks->markJobDone($QueuedTask);
272
-        $this->out('Job Finished.');
273
-    }
274
-
275
-    /**
276
-     * Manually trigger a Finished job cleanup.
277
-     *
278
-     * @return void
279
-     */
280
-    public function clean()
281
-    {
282
-        if (!Configure::read('Queue.cleanupTimeout')) {
283
-            $this->abort('You disabled cleanuptimout in config. Aborting.');
284
-        }
285
-
286
-        $this->out('Deleting old jobs, that have finished before ' . date('Y-m-d H:i:s', time() - (int)Configure::read('Queue.cleanupTimeout')));
287
-        $this->QueuedTasks->cleanOldJobs();
288
-    }
289
-
290
-    /**
291
-     * Display current settings
292
-     *
293
-     * @return void
294
-     */
295
-    public function settings()
296
-    {
297
-        $this->out('Current Settings:');
298
-        $conf = (array)Configure::read('Queue');
299
-        foreach ($conf as $key => $val) {
300
-            if ($val === false) {
301
-                $val = 'no';
302
-            }
303
-            if ($val === true) {
304
-                $val = 'yes';
305
-            }
306
-            $this->out('* ' . $key . ': ' . print_r($val, true));
307
-        }
308
-
309
-        $this->out();
310
-    }
311
-
312
-    /**
313
-     * Display some statistics about Finished Jobs.
314
-     *
315
-     * @return void
316
-     */
317
-    public function stats()
318
-    {
319
-        $this->out('Jobs currently in the queue:');
320
-
321
-        $types = $this->QueuedTasks->getTypes()->toArray();
322
-        foreach ($types as $type) {
323
-            $this->out('      ' . str_pad($type, 20, ' ', STR_PAD_RIGHT) . ': ' . $this->QueuedTasks->getLength($type));
324
-        }
325
-        $this->hr();
326
-        $this->out('Total unfinished jobs: ' . $this->QueuedTasks->getLength());
327
-        $this->hr();
328
-        $this->out('Finished job statistics:');
329
-        $data = $this->QueuedTasks->getStats();
330
-        foreach ($data as $item) {
331
-            $this->out(' ' . $item['task'] . ': ');
332
-            $this->out('   Finished Jobs in Database: ' . $item['num']);
333
-            $this->out('   Average Job existence    : ' . str_pad(Number::precision($item['alltime']), 8, ' ', STR_PAD_LEFT) . 's');
334
-            $this->out('   Average Execution delay  : ' . str_pad(Number::precision($item['fetchdelay']), 8, ' ', STR_PAD_LEFT) . 's');
335
-            $this->out('   Average Execution time   : ' . str_pad(Number::precision($item['runtime']), 8, ' ', STR_PAD_LEFT) . 's');
336
-        }
337
-    }
338
-
339
-    /**
340
-     * Get option parser method to parse commandline options
341
-     *
342
-     * @return \Cake\Console\ConsoleOptionParser
343
-     */
344
-    public function getOptionParser()
345
-    {
346
-        $subcommandParser = [
347
-            'options' => [
348
-                /*
103
+		return $text;
104
+	}
105
+
106
+	/**
107
+	 * Look for a Queue Task of hte passed name and try to call add() on it.
108
+	 * A QueueTask may provide an add function to enable the user to create new jobs via commandline.
109
+	 *
110
+	 * @return void
111
+	 */
112
+	public function add()
113
+	{
114
+		if (count($this->args) < 1) {
115
+			$this->out('Please call like this:');
116
+			$this->out('       bin/cake queue add <taskname>');
117
+			$this->_displayAvailableTasks();
118
+
119
+			return;
120
+		}
121
+
122
+		$name = Inflector::camelize($this->args[0]);
123
+		if (in_array('Queue' . $name, $this->taskNames, true)) {
124
+			/** @var \Queue\Shell\Task\QueueTask|\Queue\Shell\Task\AddInterface $task */
125
+			$task = $this->{'Queue' . $name};
126
+			if (!($task instanceof AddInterface)) {
127
+				$this->abort('This task does not support adding via CLI call');
128
+			}
129
+			$task->add();
130
+		} else {
131
+			$this->out('Error: Task not found: ' . $name);
132
+			$this->_displayAvailableTasks();
133
+		}
134
+	}
135
+
136
+	/**
137
+	 * Output the task without Queue or Task
138
+	 * example: QueueImageTask becomes Image on display
139
+	 *
140
+	 * @param string $task Task name
141
+	 * @return string Cleaned task name
142
+	 */
143
+	protected function _taskName($task)
144
+	{
145
+		if (strpos($task, 'Queue') === 0) {
146
+			return substr($task, 5);
147
+		}
148
+
149
+		return $task;
150
+	}
151
+
152
+	/**
153
+	 * Run a QueueWorker loop.
154
+	 * Runs a Queue Worker process which will try to find unassigned jobs in the queue
155
+	 * which it may run and try to fetch and execute them.
156
+	 *
157
+	 * @return int|null
158
+	 */
159
+	public function runworker()
160
+	{
161
+		// Enable Garbage Collector (PHP >= 5.3)
162
+		if (function_exists('gc_enable')) {
163
+			gc_enable();
164
+		}
165
+		if (function_exists('pcntl_signal')) {
166
+			pcntl_signal(SIGTERM, [
167
+				&$this,
168
+				'_exit'
169
+			]);
170
+			pcntl_signal(SIGINT, [
171
+				&$this,
172
+				'_exit'
173
+			]);
174
+			pcntl_signal(SIGTSTP, [
175
+				&$this,
176
+				'_exit'
177
+			]);
178
+			pcntl_signal(SIGQUIT, [
179
+				&$this,
180
+				'_exit'
181
+			]);
182
+		}
183
+		$this->_exit = false;
184
+
185
+		$startTime = time();
186
+		$types = $this->_stringToArray($this->param('type'));
187
+
188
+		while (!$this->_exit) {
189
+			$this->out(__d('queue', 'Looking for a job.'), 1, Shell::VERBOSE);
190
+
191
+			$QueuedTask = $this->QueuedTasks->requestJob($this->_getTaskConf(), $types);
192
+
193
+			if ($QueuedTask) {
194
+				$this->runJob($QueuedTask);
195
+			} elseif (Configure::read('Queue.exitWhenNothingToDo')) {
196
+				$this->out(__d('queue', 'nothing to do, exiting.'));
197
+				$this->_exit = true;
198
+			} else {
199
+				$this->out(__d('queue', 'nothing to do, sleeping.'));
200
+				sleep(Config::sleepTime());
201
+			}
202
+
203
+			// check if we are over the maximum runtime and end processing if so.
204
+			if (Configure::readOrFail('Queue.workerMaxRuntime') && (time() - $startTime) >= Configure::readOrFail('Queue.workerMaxRuntime')) {
205
+				$this->_exit = true;
206
+				$this->out(__d('queue', 'Reached runtime of ' . (time() - $startTime) . ' Seconds (Max ' . Configure::readOrFail('Queue.workerMaxRuntime') . '), terminating.'));
207
+			}
208
+			if ($this->_exit || mt_rand(0, 100) > (100 - (int)Config::gcprob())) {
209
+				$this->out(__d('queue', 'Performing old job cleanup.'));
210
+				$this->QueuedTasks->cleanOldJobs();
211
+			}
212
+			$this->hr();
213
+		}
214
+
215
+		if ($this->param('verbose')) {
216
+			$this->_log('endworker');
217
+		}
218
+	}
219
+
220
+	/**
221
+	 *
222
+	 * @param \Queue\Model\Entity\QueuedTask $QueuedTask Queued task
223
+	 * @return void
224
+	 */
225
+	protected function runJob(QueuedTask $QueuedTask)
226
+	{
227
+		$this->out('Running Job of type "' . $QueuedTask->task . '"');
228
+		$this->_log('job ' . $QueuedTask->task . ', id ' . $QueuedTask->id, null, false);
229
+		$taskName = 'Queue' . $QueuedTask->task;
230
+
231
+		try {
232
+			$this->_time = time();
233
+
234
+			$data = unserialize($QueuedTask->data);
235
+			/** @var \Queue\Shell\Task\QueueTask $task */
236
+			$task = $this->{$taskName};
237
+			if (!$task instanceof QueueTaskInterface) {
238
+				throw new RuntimeException('Task must implement ' . QueueTaskInterface::class);
239
+			}
240
+
241
+			$return = $task->run((array)$data, $QueuedTask->id);
242
+			if ($return !== null) {
243
+				trigger_error('run() should be void and throw exception in error case now.', E_USER_DEPRECATED);
244
+			}
245
+			$failureMessage = $taskName . ' failed';
246
+		} catch (Throwable $e) {
247
+			$return = false;
248
+
249
+			$failureMessage = get_class($e) . ': ' . $e->getMessage();
250
+			if (!($e instanceof QueueException)) {
251
+				$failureMessage .= "\n" . $e->getTraceAsString();
252
+			}
253
+
254
+			$this->_logError($taskName . ' (job ' . $QueuedTask->id . ')' . "\n" . $failureMessage);
255
+		} catch (Exception $e) {
256
+			$return = false;
257
+
258
+			$failureMessage = get_class($e) . ': ' . $e->getMessage();
259
+			$this->_logError($taskName . "\n" . $failureMessage);
260
+		}
261
+
262
+		if ($return === false) {
263
+			$this->QueuedTasks->markJobFailed($QueuedTask, $failureMessage);
264
+			$failedStatus = $this->QueuedTasks->getFailedStatus($QueuedTask, $this->_getTaskConf());
265
+			$this->_log('job ' . $QueuedTask->task . ', id ' . $QueuedTask->id . ' failed and ' . $failedStatus);
266
+			$this->out('Job did not finish, ' . $failedStatus . ' after try ' . $QueuedTask->failed . '.');
267
+
268
+			return;
269
+		}
270
+
271
+		$this->QueuedTasks->markJobDone($QueuedTask);
272
+		$this->out('Job Finished.');
273
+	}
274
+
275
+	/**
276
+	 * Manually trigger a Finished job cleanup.
277
+	 *
278
+	 * @return void
279
+	 */
280
+	public function clean()
281
+	{
282
+		if (!Configure::read('Queue.cleanupTimeout')) {
283
+			$this->abort('You disabled cleanuptimout in config. Aborting.');
284
+		}
285
+
286
+		$this->out('Deleting old jobs, that have finished before ' . date('Y-m-d H:i:s', time() - (int)Configure::read('Queue.cleanupTimeout')));
287
+		$this->QueuedTasks->cleanOldJobs();
288
+	}
289
+
290
+	/**
291
+	 * Display current settings
292
+	 *
293
+	 * @return void
294
+	 */
295
+	public function settings()
296
+	{
297
+		$this->out('Current Settings:');
298
+		$conf = (array)Configure::read('Queue');
299
+		foreach ($conf as $key => $val) {
300
+			if ($val === false) {
301
+				$val = 'no';
302
+			}
303
+			if ($val === true) {
304
+				$val = 'yes';
305
+			}
306
+			$this->out('* ' . $key . ': ' . print_r($val, true));
307
+		}
308
+
309
+		$this->out();
310
+	}
311
+
312
+	/**
313
+	 * Display some statistics about Finished Jobs.
314
+	 *
315
+	 * @return void
316
+	 */
317
+	public function stats()
318
+	{
319
+		$this->out('Jobs currently in the queue:');
320
+
321
+		$types = $this->QueuedTasks->getTypes()->toArray();
322
+		foreach ($types as $type) {
323
+			$this->out('      ' . str_pad($type, 20, ' ', STR_PAD_RIGHT) . ': ' . $this->QueuedTasks->getLength($type));
324
+		}
325
+		$this->hr();
326
+		$this->out('Total unfinished jobs: ' . $this->QueuedTasks->getLength());
327
+		$this->hr();
328
+		$this->out('Finished job statistics:');
329
+		$data = $this->QueuedTasks->getStats();
330
+		foreach ($data as $item) {
331
+			$this->out(' ' . $item['task'] . ': ');
332
+			$this->out('   Finished Jobs in Database: ' . $item['num']);
333
+			$this->out('   Average Job existence    : ' . str_pad(Number::precision($item['alltime']), 8, ' ', STR_PAD_LEFT) . 's');
334
+			$this->out('   Average Execution delay  : ' . str_pad(Number::precision($item['fetchdelay']), 8, ' ', STR_PAD_LEFT) . 's');
335
+			$this->out('   Average Execution time   : ' . str_pad(Number::precision($item['runtime']), 8, ' ', STR_PAD_LEFT) . 's');
336
+		}
337
+	}
338
+
339
+	/**
340
+	 * Get option parser method to parse commandline options
341
+	 *
342
+	 * @return \Cake\Console\ConsoleOptionParser
343
+	 */
344
+	public function getOptionParser()
345
+	{
346
+		$subcommandParser = [
347
+			'options' => [
348
+				/*
349 349
                  * 'dry-run'=> array(
350 350
                  * 'short' => 'd',
351 351
                  * 'help' => 'Dry run the update, no jobs will actually be added.',
352 352
                  * 'boolean' => true
353 353
                  * ),
354 354
                  */
355
-            ]
356
-        ];
357
-        $subcommandParserFull = $subcommandParser;
358
-        $subcommandParserFull['options']['type'] = [
359
-            'short' => 't',
360
-            'help' => 'Type (comma separated list possible)',
361
-            'default' => null
362
-        ];
363
-
364
-        return parent::getOptionParser()->setDescription($this->getDescription())
365
-            ->addSubcommand('clean', [
366
-                'help' => 'Remove old jobs (cleanup)',
367
-                'parser' => $subcommandParser
368
-            ])
369
-            ->addSubcommand('add', [
370
-                'help' => 'Add Job',
371
-                'parser' => $subcommandParser
372
-            ])
373
-            ->addSubcommand('stats', [
374
-                'help' => 'Stats',
375
-                'parser' => $subcommandParserFull
376
-            ])
377
-            ->addSubcommand('settings', [
378
-                'help' => 'Settings',
379
-                'parser' => $subcommandParserFull
380
-            ])
381
-            ->addSubcommand('runworker', [
382
-                'help' => 'Run Worker',
383
-                'parser' => $subcommandParserFull
384
-            ]);
385
-    }
386
-
387
-    /**
388
-     * Timestamped log.
389
-     *
390
-     * @param string $message Log type
391
-     * @param string|null $pid PID of the process
392
-     * @param bool $addDetails Details
393
-     * @return void
394
-     */
395
-    protected function _log($message, $pid = null, $addDetails = true)
396
-    {
397
-        if (!Configure::read('Queue.log')) {
398
-            return;
399
-        }
400
-
401
-        if ($addDetails) {
402
-            $timeNeeded = $this->_timeNeeded();
403
-            $memoryUsage = $this->_memoryUsage();
404
-            $message .= ' [' . $timeNeeded . ', ' . $memoryUsage . ']';
405
-        }
406
-
407
-        if ($pid) {
408
-            $message .= ' (pid ' . $pid . ')';
409
-        }
410
-        Log::write('info', $message, [
411
-            'scope' => 'queue'
412
-        ]);
413
-    }
414
-
415
-    /**
416
-     *
417
-     * @param string $message Message
418
-     * @param string|null $pid PID of the process
419
-     * @return void
420
-     */
421
-    protected function _logError($message, $pid = null)
422
-    {
423
-        $timeNeeded = $this->_timeNeeded();
424
-        $memoryUsage = $this->_memoryUsage();
425
-        $message .= ' [' . $timeNeeded . ', ' . $memoryUsage . ']';
426
-
427
-        if ($pid) {
428
-            $message .= ' (pid ' . $pid . ')';
429
-        }
430
-
431
-        Log::write('error', $message);
432
-    }
433
-
434
-    /**
435
-     * Returns a List of available QueueTasks and their individual configurations.
436
-     *
437
-     * @return array
438
-     */
439
-    protected function _getTaskConf()
440
-    {
441
-        if (!is_array($this->_taskConf)) {
442
-            $this->_taskConf = [];
443
-            foreach ($this->tasks as $task) {
444
-                list ($pluginName, $taskName) = pluginSplit($task);
445
-
446
-                $this->_taskConf[$taskName]['name'] = substr($taskName, 5);
447
-                $this->_taskConf[$taskName]['plugin'] = $pluginName;
448
-                if (property_exists($this->{$taskName}, 'timeout')) {
449
-                    $this->_taskConf[$taskName]['timeout'] = $this->{$taskName}->timeout;
450
-                } else {
451
-                    $this->_taskConf[$taskName]['timeout'] = Config::defaultWorkerTimeout();
452
-                }
453
-                if (property_exists($this->{$taskName}, 'retries')) {
454
-                    $this->_taskConf[$taskName]['retries'] = $this->{$taskName}->retries;
455
-                } else {
456
-                    $this->_taskConf[$taskName]['retries'] = Config::defaultWorkerRetries();
457
-                }
458
-                if (property_exists($this->{$taskName}, 'cleanupTimeout')) {
459
-                    $this->_taskConf[$taskName]['cleanupTimeout'] = $this->{$taskName}->cleanupTimeout;
460
-                } else {
461
-                    $this->_taskConf[$taskName]['cleanupTimeout'] = Config::cleanupTimeout();
462
-                }
463
-            }
464
-        }
465
-
466
-        return $this->_taskConf;
467
-    }
468
-
469
-    /**
470
-     * Signal handling to queue worker for clean shutdown
471
-     *
472
-     * @param int $signal The signal
473
-     * @return void
474
-     */
475
-    protected function _exit($signal)
476
-    {
477
-        $this->out(__d('queue', 'Caught %d signal, exiting.', $signal));
478
-        $this->_exit = true;
479
-    }
480
-
481
-    /**
482
-     *
483
-     * @return void
484
-     */
485
-    protected function _displayAvailableTasks()
486
-    {
487
-        $this->out('Available Tasks:');
488
-        foreach ($this->taskNames as $loadedTask) {
489
-            $this->out("\t" . '* ' . $this->_taskName($loadedTask));
490
-        }
491
-    }
492
-
493
-    /**
494
-     *
495
-     * @return string Memory usage in MB.
496
-     */
497
-    protected function _memoryUsage()
498
-    {
499
-        $limit = ini_get('memory_limit');
500
-
501
-        $used = number_format(memory_get_peak_usage(true) / (1024 * 1024), 0) . 'MB';
502
-        if ($limit !== '-1') {
503
-            $used .= '/' . $limit;
504
-        }
505
-
506
-        return $used;
507
-    }
508
-
509
-    /**
510
-     *
511
-     * @return string
512
-     */
513
-    protected function _timeNeeded()
514
-    {
515
-        $diff = $this->_time() - $this->_time($this->_time);
516
-        $seconds = max($diff, 1);
517
-
518
-        return $seconds . 's';
519
-    }
520
-
521
-    /**
522
-     *
523
-     * @param int|null $providedTime Provided time
524
-     *
525
-     * @return int
526
-     */
527
-    protected function _time($providedTime = null)
528
-    {
529
-        if ($providedTime !== null) {
530
-            return $providedTime;
531
-        }
532
-
533
-        return time();
534
-    }
535
-
536
-    /**
537
-     *
538
-     * @param string|null $param String to convert
539
-     * @return array
540
-     */
541
-    protected function _stringToArray($param)
542
-    {
543
-        if (!$param) {
544
-            return [];
545
-        }
546
-
547
-        $array = Text::tokenize($param);
548
-
549
-        return array_filter($array);
550
-    }
355
+			]
356
+		];
357
+		$subcommandParserFull = $subcommandParser;
358
+		$subcommandParserFull['options']['type'] = [
359
+			'short' => 't',
360
+			'help' => 'Type (comma separated list possible)',
361
+			'default' => null
362
+		];
363
+
364
+		return parent::getOptionParser()->setDescription($this->getDescription())
365
+			->addSubcommand('clean', [
366
+				'help' => 'Remove old jobs (cleanup)',
367
+				'parser' => $subcommandParser
368
+			])
369
+			->addSubcommand('add', [
370
+				'help' => 'Add Job',
371
+				'parser' => $subcommandParser
372
+			])
373
+			->addSubcommand('stats', [
374
+				'help' => 'Stats',
375
+				'parser' => $subcommandParserFull
376
+			])
377
+			->addSubcommand('settings', [
378
+				'help' => 'Settings',
379
+				'parser' => $subcommandParserFull
380
+			])
381
+			->addSubcommand('runworker', [
382
+				'help' => 'Run Worker',
383
+				'parser' => $subcommandParserFull
384
+			]);
385
+	}
386
+
387
+	/**
388
+	 * Timestamped log.
389
+	 *
390
+	 * @param string $message Log type
391
+	 * @param string|null $pid PID of the process
392
+	 * @param bool $addDetails Details
393
+	 * @return void
394
+	 */
395
+	protected function _log($message, $pid = null, $addDetails = true)
396
+	{
397
+		if (!Configure::read('Queue.log')) {
398
+			return;
399
+		}
400
+
401
+		if ($addDetails) {
402
+			$timeNeeded = $this->_timeNeeded();
403
+			$memoryUsage = $this->_memoryUsage();
404
+			$message .= ' [' . $timeNeeded . ', ' . $memoryUsage . ']';
405
+		}
406
+
407
+		if ($pid) {
408
+			$message .= ' (pid ' . $pid . ')';
409
+		}
410
+		Log::write('info', $message, [
411
+			'scope' => 'queue'
412
+		]);
413
+	}
414
+
415
+	/**
416
+	 *
417
+	 * @param string $message Message
418
+	 * @param string|null $pid PID of the process
419
+	 * @return void
420
+	 */
421
+	protected function _logError($message, $pid = null)
422
+	{
423
+		$timeNeeded = $this->_timeNeeded();
424
+		$memoryUsage = $this->_memoryUsage();
425
+		$message .= ' [' . $timeNeeded . ', ' . $memoryUsage . ']';
426
+
427
+		if ($pid) {
428
+			$message .= ' (pid ' . $pid . ')';
429
+		}
430
+
431
+		Log::write('error', $message);
432
+	}
433
+
434
+	/**
435
+	 * Returns a List of available QueueTasks and their individual configurations.
436
+	 *
437
+	 * @return array
438
+	 */
439
+	protected function _getTaskConf()
440
+	{
441
+		if (!is_array($this->_taskConf)) {
442
+			$this->_taskConf = [];
443
+			foreach ($this->tasks as $task) {
444
+				list ($pluginName, $taskName) = pluginSplit($task);
445
+
446
+				$this->_taskConf[$taskName]['name'] = substr($taskName, 5);
447
+				$this->_taskConf[$taskName]['plugin'] = $pluginName;
448
+				if (property_exists($this->{$taskName}, 'timeout')) {
449
+					$this->_taskConf[$taskName]['timeout'] = $this->{$taskName}->timeout;
450
+				} else {
451
+					$this->_taskConf[$taskName]['timeout'] = Config::defaultWorkerTimeout();
452
+				}
453
+				if (property_exists($this->{$taskName}, 'retries')) {
454
+					$this->_taskConf[$taskName]['retries'] = $this->{$taskName}->retries;
455
+				} else {
456
+					$this->_taskConf[$taskName]['retries'] = Config::defaultWorkerRetries();
457
+				}
458
+				if (property_exists($this->{$taskName}, 'cleanupTimeout')) {
459
+					$this->_taskConf[$taskName]['cleanupTimeout'] = $this->{$taskName}->cleanupTimeout;
460
+				} else {
461
+					$this->_taskConf[$taskName]['cleanupTimeout'] = Config::cleanupTimeout();
462
+				}
463
+			}
464
+		}
465
+
466
+		return $this->_taskConf;
467
+	}
468
+
469
+	/**
470
+	 * Signal handling to queue worker for clean shutdown
471
+	 *
472
+	 * @param int $signal The signal
473
+	 * @return void
474
+	 */
475
+	protected function _exit($signal)
476
+	{
477
+		$this->out(__d('queue', 'Caught %d signal, exiting.', $signal));
478
+		$this->_exit = true;
479
+	}
480
+
481
+	/**
482
+	 *
483
+	 * @return void
484
+	 */
485
+	protected function _displayAvailableTasks()
486
+	{
487
+		$this->out('Available Tasks:');
488
+		foreach ($this->taskNames as $loadedTask) {
489
+			$this->out("\t" . '* ' . $this->_taskName($loadedTask));
490
+		}
491
+	}
492
+
493
+	/**
494
+	 *
495
+	 * @return string Memory usage in MB.
496
+	 */
497
+	protected function _memoryUsage()
498
+	{
499
+		$limit = ini_get('memory_limit');
500
+
501
+		$used = number_format(memory_get_peak_usage(true) / (1024 * 1024), 0) . 'MB';
502
+		if ($limit !== '-1') {
503
+			$used .= '/' . $limit;
504
+		}
505
+
506
+		return $used;
507
+	}
508
+
509
+	/**
510
+	 *
511
+	 * @return string
512
+	 */
513
+	protected function _timeNeeded()
514
+	{
515
+		$diff = $this->_time() - $this->_time($this->_time);
516
+		$seconds = max($diff, 1);
517
+
518
+		return $seconds . 's';
519
+	}
520
+
521
+	/**
522
+	 *
523
+	 * @param int|null $providedTime Provided time
524
+	 *
525
+	 * @return int
526
+	 */
527
+	protected function _time($providedTime = null)
528
+	{
529
+		if ($providedTime !== null) {
530
+			return $providedTime;
531
+		}
532
+
533
+		return time();
534
+	}
535
+
536
+	/**
537
+	 *
538
+	 * @param string|null $param String to convert
539
+	 * @return array
540
+	 */
541
+	protected function _stringToArray($param)
542
+	{
543
+		if (!$param) {
544
+			return [];
545
+		}
546
+
547
+		$array = Text::tokenize($param);
548
+
549
+		return array_filter($array);
550
+	}
551 551
 }
Please login to merge, or discard this patch.
tests/TestCase/Queue/TaskFinderTest.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -7,50 +7,50 @@
 block discarded – undo
7 7
 class TaskFinderTest extends TestCase
8 8
 {
9 9
 
10
-    /**
11
-     *
12
-     * @var \Queue\Shell\QueueShell|\PHPUnit_Framework_MockObject_MockObject
13
-     */
14
-    public $QueueShell;
15
-
16
-    /**
17
-     *
18
-     * @var \Queue\Queue\TaskFinder
19
-     */
20
-    protected $taskFinder;
21
-
22
-    /**
23
-     * Fixtures to load
24
-     *
25
-     * @var array
26
-     */
27
-    public $fixtures = [
28
-        'plugin.Queue.QueuedTasks',
29
-    ];
30
-
31
-    /**
32
-     * Setup Defaults
33
-     *
34
-     * @return void
35
-     */
36
-    public function setUp()
37
-    {
38
-        parent::setUp();
39
-    }
40
-
41
-    /**
42
-     *
43
-     * @return void
44
-     */
45
-    public function testAllAppAndPluginTasks()
46
-    {
47
-        $this->taskFinder = new TaskFinder();
48
-
49
-        $result = $this->taskFinder->allAppAndPluginTasks();
50
-        $this->assertCount(1, $result);
51
-        $this->assertArraySubset([
52
-            'Queue.QueueExample'
53
-        ], $result);
54
-        $this->assertTrue(!in_array('Foo.QueueFoo', $result));
55
-    }
10
+	/**
11
+	 *
12
+	 * @var \Queue\Shell\QueueShell|\PHPUnit_Framework_MockObject_MockObject
13
+	 */
14
+	public $QueueShell;
15
+
16
+	/**
17
+	 *
18
+	 * @var \Queue\Queue\TaskFinder
19
+	 */
20
+	protected $taskFinder;
21
+
22
+	/**
23
+	 * Fixtures to load
24
+	 *
25
+	 * @var array
26
+	 */
27
+	public $fixtures = [
28
+		'plugin.Queue.QueuedTasks',
29
+	];
30
+
31
+	/**
32
+	 * Setup Defaults
33
+	 *
34
+	 * @return void
35
+	 */
36
+	public function setUp()
37
+	{
38
+		parent::setUp();
39
+	}
40
+
41
+	/**
42
+	 *
43
+	 * @return void
44
+	 */
45
+	public function testAllAppAndPluginTasks()
46
+	{
47
+		$this->taskFinder = new TaskFinder();
48
+
49
+		$result = $this->taskFinder->allAppAndPluginTasks();
50
+		$this->assertCount(1, $result);
51
+		$this->assertArraySubset([
52
+			'Queue.QueueExample'
53
+		], $result);
54
+		$this->assertTrue(!in_array('Foo.QueueFoo', $result));
55
+	}
56 56
 }
Please login to merge, or discard this patch.
tests/TestCase/Model/Table/QueuedTasksTableTest.php 1 patch
Indentation   +260 added lines, -260 removed lines patch added patch discarded remove patch
@@ -19,292 +19,292 @@
 block discarded – undo
19 19
 class QueuedTasksTableTest extends TestCase
20 20
 {
21 21
 
22
-    /**
23
-     *
24
-     * @var \Queue\Model\Table\QueuedTasksTable
25
-     */
26
-    protected $QueuedTasks;
22
+	/**
23
+	 *
24
+	 * @var \Queue\Model\Table\QueuedTasksTable
25
+	 */
26
+	protected $QueuedTasks;
27 27
 
28
-    /**
29
-     * Fixtures
30
-     *
31
-     * @var array
32
-     */
33
-    public $fixtures = [
34
-        'plugin.Queue.QueuedTasks'
35
-    ];
28
+	/**
29
+	 * Fixtures
30
+	 *
31
+	 * @var array
32
+	 */
33
+	public $fixtures = [
34
+		'plugin.Queue.QueuedTasks'
35
+	];
36 36
 
37
-    /**
38
-     * setUp method
39
-     *
40
-     * @return void
41
-     */
42
-    public function setUp()
43
-    {
44
-        parent::setUp();
45
-        $config = TableRegistry::getTableLocator()->exists('QueuedTasks') ? [] : [
46
-            'className' => QueuedTasksTable::class
47
-        ];
48
-        $this->QueuedTasks = TableRegistry::getTableLocator()->get('QueuedTasks', $config);
49
-    }
37
+	/**
38
+	 * setUp method
39
+	 *
40
+	 * @return void
41
+	 */
42
+	public function setUp()
43
+	{
44
+		parent::setUp();
45
+		$config = TableRegistry::getTableLocator()->exists('QueuedTasks') ? [] : [
46
+			'className' => QueuedTasksTable::class
47
+		];
48
+		$this->QueuedTasks = TableRegistry::getTableLocator()->get('QueuedTasks', $config);
49
+	}
50 50
 
51
-    /**
52
-     * Basic Instance test
53
-     *
54
-     * @return void
55
-     */
56
-    public function testQueueInstance()
57
-    {
58
-        $this->assertInstanceOf(QueuedTasksTable::class, $this->QueuedTasks);
59
-    }
51
+	/**
52
+	 * Basic Instance test
53
+	 *
54
+	 * @return void
55
+	 */
56
+	public function testQueueInstance()
57
+	{
58
+		$this->assertInstanceOf(QueuedTasksTable::class, $this->QueuedTasks);
59
+	}
60 60
 
61
-    /**
62
-     * Test the basic create and length evaluation functions.
63
-     *
64
-     * @return void
65
-     */
66
-    public function testCreateAndCount()
67
-    {
68
-        // at first, the queue should contain 0 items.
69
-        $this->assertSame(0, $this->QueuedTasks->getLength());
61
+	/**
62
+	 * Test the basic create and length evaluation functions.
63
+	 *
64
+	 * @return void
65
+	 */
66
+	public function testCreateAndCount()
67
+	{
68
+		// at first, the queue should contain 0 items.
69
+		$this->assertSame(0, $this->QueuedTasks->getLength());
70 70
 
71
-        // create a job
72
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('test1', [
73
-            'some' => 'random',
74
-            'test' => 'data'
75
-        ]));
71
+		// create a job
72
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('test1', [
73
+			'some' => 'random',
74
+			'test' => 'data'
75
+		]));
76 76
 
77
-        // test if queue Length is 1 now.
78
-        $this->assertSame(1, $this->QueuedTasks->getLength());
77
+		// test if queue Length is 1 now.
78
+		$this->assertSame(1, $this->QueuedTasks->getLength());
79 79
 
80
-        // create some more jobs
81
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('test2', [
82
-            'some' => 'random',
83
-            'test' => 'data2'
84
-        ]));
85
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('test2', [
86
-            'some' => 'random',
87
-            'test' => 'data3'
88
-        ]));
89
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('test3', [
90
-            'some' => 'random',
91
-            'test' => 'data4'
92
-        ]));
80
+		// create some more jobs
81
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('test2', [
82
+			'some' => 'random',
83
+			'test' => 'data2'
84
+		]));
85
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('test2', [
86
+			'some' => 'random',
87
+			'test' => 'data3'
88
+		]));
89
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('test3', [
90
+			'some' => 'random',
91
+			'test' => 'data4'
92
+		]));
93 93
 
94
-        // overall queueLength shpould now be 4
95
-        $this->assertSame(4, $this->QueuedTasks->getLength());
94
+		// overall queueLength shpould now be 4
95
+		$this->assertSame(4, $this->QueuedTasks->getLength());
96 96
 
97
-        // there should be 1 task of type 'test1', one of type 'test3' and 2 of type 'test2'
98
-        $this->assertSame(1, $this->QueuedTasks->getLength('test1'));
99
-        $this->assertSame(2, $this->QueuedTasks->getLength('test2'));
100
-        $this->assertSame(1, $this->QueuedTasks->getLength('test3'));
101
-    }
97
+		// there should be 1 task of type 'test1', one of type 'test3' and 2 of type 'test2'
98
+		$this->assertSame(1, $this->QueuedTasks->getLength('test1'));
99
+		$this->assertSame(2, $this->QueuedTasks->getLength('test2'));
100
+		$this->assertSame(1, $this->QueuedTasks->getLength('test3'));
101
+	}
102 102
 
103
-    /**
104
-     * Test the basic create and fetch functions.
105
-     *
106
-     * @return void
107
-     */
108
-    public function testCreateAndFetch()
109
-    {
110
-        $this->_needsConnection();
103
+	/**
104
+	 * Test the basic create and fetch functions.
105
+	 *
106
+	 * @return void
107
+	 */
108
+	public function testCreateAndFetch()
109
+	{
110
+		$this->_needsConnection();
111 111
 
112
-        // $capabilities is a list of tasks the worker can run.
113
-        $capabilities = [
114
-            'task1' => [
115
-                'name' => 'task1',
116
-                'timeout' => 100,
117
-                'retries' => 2
118
-            ]
119
-        ];
120
-        $testData = [
121
-            'x1' => 'y1',
122
-            'x2' => 'y2',
123
-            'x3' => 'y3',
124
-            'x4' => 'y4'
125
-        ];
112
+		// $capabilities is a list of tasks the worker can run.
113
+		$capabilities = [
114
+			'task1' => [
115
+				'name' => 'task1',
116
+				'timeout' => 100,
117
+				'retries' => 2
118
+			]
119
+		];
120
+		$testData = [
121
+			'x1' => 'y1',
122
+			'x2' => 'y2',
123
+			'x3' => 'y3',
124
+			'x4' => 'y4'
125
+		];
126 126
 
127
-        // start off empty.
128
-        $this->assertSame([], $this->QueuedTasks->find()
129
-            ->toArray());
130
-        // at first, the queue should contain 0 items.
131
-        $this->assertSame(0, $this->QueuedTasks->getLength());
132
-        // there are no jobs, so we cant fetch any.
133
-        $this->assertNull($this->QueuedTasks->requestJob($capabilities));
134
-        // insert one job.
135
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('task1', $testData));
127
+		// start off empty.
128
+		$this->assertSame([], $this->QueuedTasks->find()
129
+			->toArray());
130
+		// at first, the queue should contain 0 items.
131
+		$this->assertSame(0, $this->QueuedTasks->getLength());
132
+		// there are no jobs, so we cant fetch any.
133
+		$this->assertNull($this->QueuedTasks->requestJob($capabilities));
134
+		// insert one job.
135
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('task1', $testData));
136 136
 
137
-        // fetch and check the first job.
138
-        $job = $this->QueuedTasks->requestJob($capabilities);
139
-        $this->assertSame(1, $job->id);
140
-        $this->assertSame('task1', $job->task);
141
-        $this->assertSame(0, $job->failed_count);
142
-        $this->assertNull($job->completed);
143
-        $this->assertSame($testData, unserialize($job->data));
137
+		// fetch and check the first job.
138
+		$job = $this->QueuedTasks->requestJob($capabilities);
139
+		$this->assertSame(1, $job->id);
140
+		$this->assertSame('task1', $job->task);
141
+		$this->assertSame(0, $job->failed_count);
142
+		$this->assertNull($job->completed);
143
+		$this->assertSame($testData, unserialize($job->data));
144 144
 
145
-        // after this job has been fetched, it may not be reassigned.
146
-        $result = $this->QueuedTasks->requestJob($capabilities);
147
-        $this->assertNull($result);
145
+		// after this job has been fetched, it may not be reassigned.
146
+		$result = $this->QueuedTasks->requestJob($capabilities);
147
+		$this->assertNull($result);
148 148
 
149
-        // queue length is still 1 since the first job did not finish.
150
-        $this->assertSame(1, $this->QueuedTasks->getLength());
149
+		// queue length is still 1 since the first job did not finish.
150
+		$this->assertSame(1, $this->QueuedTasks->getLength());
151 151
 
152
-        // Now mark Task1 as done
153
-        $this->assertTrue($this->QueuedTasks->markJobDone($job));
152
+		// Now mark Task1 as done
153
+		$this->assertTrue($this->QueuedTasks->markJobDone($job));
154 154
 
155
-        // Should be 0 again.
156
-        $this->assertSame(0, $this->QueuedTasks->getLength());
157
-    }
155
+		// Should be 0 again.
156
+		$this->assertSame(0, $this->QueuedTasks->getLength());
157
+	}
158 158
 
159
-    /**
160
-     * Test the delivery of jobs in sequence, skipping fetched but not completed tasks.
161
-     *
162
-     * @return void
163
-     */
164
-    public function testSequence()
165
-    {
166
-        $this->_needsConnection();
159
+	/**
160
+	 * Test the delivery of jobs in sequence, skipping fetched but not completed tasks.
161
+	 *
162
+	 * @return void
163
+	 */
164
+	public function testSequence()
165
+	{
166
+		$this->_needsConnection();
167 167
 
168
-        // $capabilities is a list of tasks the worker can run.
169
-        $capabilities = [
170
-            'task1' => [
171
-                'name' => 'task1',
172
-                'timeout' => 100,
173
-                'retries' => 2
174
-            ]
175
-        ];
176
-        // at first, the queue should contain 0 items.
177
-        $this->assertSame(0, $this->QueuedTasks->getLength());
178
-        // create some more jobs
179
-        foreach (range(0, 9) as $num) {
180
-            $this->assertTrue((bool)$this->QueuedTasks->createJob('task1', [
181
-                'tasknum' => $num
182
-            ]));
183
-        }
184
-        // 10 jobs in the queue.
185
-        $this->assertSame(10, $this->QueuedTasks->getLength());
168
+		// $capabilities is a list of tasks the worker can run.
169
+		$capabilities = [
170
+			'task1' => [
171
+				'name' => 'task1',
172
+				'timeout' => 100,
173
+				'retries' => 2
174
+			]
175
+		];
176
+		// at first, the queue should contain 0 items.
177
+		$this->assertSame(0, $this->QueuedTasks->getLength());
178
+		// create some more jobs
179
+		foreach (range(0, 9) as $num) {
180
+			$this->assertTrue((bool)$this->QueuedTasks->createJob('task1', [
181
+				'tasknum' => $num
182
+			]));
183
+		}
184
+		// 10 jobs in the queue.
185
+		$this->assertSame(10, $this->QueuedTasks->getLength());
186 186
 
187
-        // jobs should be fetched in the original sequence.
188
-        $array = [];
189
-        foreach (range(0, 4) as $num) {
190
-            $array[$num] = $this->QueuedTasks->requestJob($capabilities);
191
-            $jobData = unserialize($array[$num]['data']);
192
-            $this->assertSame($num, $jobData['tasknum']);
193
-        }
194
-        // now mark them as done
195
-        foreach (range(0, 4) as $num) {
196
-            $this->assertTrue($this->QueuedTasks->markJobDone($array[$num]));
197
-            $this->assertSame(9 - $num, $this->QueuedTasks->getLength());
198
-        }
187
+		// jobs should be fetched in the original sequence.
188
+		$array = [];
189
+		foreach (range(0, 4) as $num) {
190
+			$array[$num] = $this->QueuedTasks->requestJob($capabilities);
191
+			$jobData = unserialize($array[$num]['data']);
192
+			$this->assertSame($num, $jobData['tasknum']);
193
+		}
194
+		// now mark them as done
195
+		foreach (range(0, 4) as $num) {
196
+			$this->assertTrue($this->QueuedTasks->markJobDone($array[$num]));
197
+			$this->assertSame(9 - $num, $this->QueuedTasks->getLength());
198
+		}
199 199
 
200
-        // jobs should be fetched in the original sequence.
201
-        foreach (range(5, 9) as $num) {
202
-            $job = $this->QueuedTasks->requestJob($capabilities);
203
-            $jobData = unserialize($job->data);
204
-            $this->assertSame($num, $jobData['tasknum']);
205
-            $this->assertTrue($this->QueuedTasks->markJobDone($job));
206
-            $this->assertSame(9 - $num, $this->QueuedTasks->getLength());
207
-        }
208
-    }
200
+		// jobs should be fetched in the original sequence.
201
+		foreach (range(5, 9) as $num) {
202
+			$job = $this->QueuedTasks->requestJob($capabilities);
203
+			$jobData = unserialize($job->data);
204
+			$this->assertSame($num, $jobData['tasknum']);
205
+			$this->assertTrue($this->QueuedTasks->markJobDone($job));
206
+			$this->assertSame(9 - $num, $this->QueuedTasks->getLength());
207
+		}
208
+	}
209 209
 
210
-    /**
211
-     * Test creating Jobs to run close to a specified time, and strtotime parsing.
212
-     * Using toUnixString() function to convert Time object to timestamp, instead of strtotime
213
-     *
214
-     * @return null
215
-     */
216
-    public function testNotBefore()
217
-    {
218
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('task1', null, '+ 1 Min'));
219
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('task1', null, '+ 1 Day'));
220
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('task1', null, '2009-07-01 12:00:00'));
221
-        $data = $this->QueuedTasks->find('all')->toArray();
222
-        $this->assertWithinRange((new Time('+ 1 Min'))->toUnixString(), $data[0]['not_before']->toUnixString(), 60);
223
-        $this->assertWithinRange((new Time('+ 1 Day'))->toUnixString(), $data[1]['not_before']->toUnixString(), 60);
224
-        $this->assertWithinRange((new Time('2009-07-01 12:00:00'))->toUnixString(), $data[2]['not_before']->toUnixString(), 60);
225
-    }
210
+	/**
211
+	 * Test creating Jobs to run close to a specified time, and strtotime parsing.
212
+	 * Using toUnixString() function to convert Time object to timestamp, instead of strtotime
213
+	 *
214
+	 * @return null
215
+	 */
216
+	public function testNotBefore()
217
+	{
218
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('task1', null, '+ 1 Min'));
219
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('task1', null, '+ 1 Day'));
220
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('task1', null, '2009-07-01 12:00:00'));
221
+		$data = $this->QueuedTasks->find('all')->toArray();
222
+		$this->assertWithinRange((new Time('+ 1 Min'))->toUnixString(), $data[0]['not_before']->toUnixString(), 60);
223
+		$this->assertWithinRange((new Time('+ 1 Day'))->toUnixString(), $data[1]['not_before']->toUnixString(), 60);
224
+		$this->assertWithinRange((new Time('2009-07-01 12:00:00'))->toUnixString(), $data[2]['not_before']->toUnixString(), 60);
225
+	}
226 226
 
227
-    /**
228
-     * Test Job reordering depending on 'notBefore' field.
229
-     * Jobs with an expired not_before field should be executed before any other job without specific timing info.
230
-     *
231
-     * @return void
232
-     */
233
-    public function testNotBeforeOrder()
234
-    {
235
-        $this->_needsConnection();
227
+	/**
228
+	 * Test Job reordering depending on 'notBefore' field.
229
+	 * Jobs with an expired not_before field should be executed before any other job without specific timing info.
230
+	 *
231
+	 * @return void
232
+	 */
233
+	public function testNotBeforeOrder()
234
+	{
235
+		$this->_needsConnection();
236 236
 
237
-        $capabilities = [
238
-            'task1' => [
239
-                'name' => 'task1',
240
-                'timeout' => 100,
241
-                'retries' => 2
242
-            ],
243
-            'dummytask' => [
244
-                'name' => 'dummytask',
245
-                'timeout' => 100,
246
-                'retries' => 2
247
-            ]
248
-        ];
249
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('dummytask'));
250
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('dummytask'));
251
-        // create a task with it's execution target some seconds in the past, so it should jump to the top of the testCreateAndFetchlist.
252
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('task1', [
253
-            'three'
254
-        ], '- 3 Seconds'));
255
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('task1', [
256
-            'two'
257
-        ], '- 5 Seconds'));
258
-        $this->assertTrue((bool)$this->QueuedTasks->createJob('task1', [
259
-            'one'
260
-        ], '- 7 Seconds'));
237
+		$capabilities = [
238
+			'task1' => [
239
+				'name' => 'task1',
240
+				'timeout' => 100,
241
+				'retries' => 2
242
+			],
243
+			'dummytask' => [
244
+				'name' => 'dummytask',
245
+				'timeout' => 100,
246
+				'retries' => 2
247
+			]
248
+		];
249
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('dummytask'));
250
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('dummytask'));
251
+		// create a task with it's execution target some seconds in the past, so it should jump to the top of the testCreateAndFetchlist.
252
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('task1', [
253
+			'three'
254
+		], '- 3 Seconds'));
255
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('task1', [
256
+			'two'
257
+		], '- 5 Seconds'));
258
+		$this->assertTrue((bool)$this->QueuedTasks->createJob('task1', [
259
+			'one'
260
+		], '- 7 Seconds'));
261 261
 
262
-        // when using requestJob, the jobs we just created should be delivered in this order, NOT the order in which they where created.
263
-        $expected = [
264
-            [
265
-                'name' => 'task1',
266
-                'data' => [
267
-                    'one'
268
-                ]
269
-            ],
270
-            [
271
-                'name' => 'task1',
272
-                'data' => [
273
-                    'two'
274
-                ]
275
-            ],
276
-            [
277
-                'name' => 'task1',
278
-                'data' => [
279
-                    'three'
280
-                ]
281
-            ],
282
-            [
283
-                'name' => 'dummytask',
284
-                'data' => null
285
-            ],
286
-            [
287
-                'name' => 'dummytask',
288
-                'data' => null
289
-            ]
290
-        ];
262
+		// when using requestJob, the jobs we just created should be delivered in this order, NOT the order in which they where created.
263
+		$expected = [
264
+			[
265
+				'name' => 'task1',
266
+				'data' => [
267
+					'one'
268
+				]
269
+			],
270
+			[
271
+				'name' => 'task1',
272
+				'data' => [
273
+					'two'
274
+				]
275
+			],
276
+			[
277
+				'name' => 'task1',
278
+				'data' => [
279
+					'three'
280
+				]
281
+			],
282
+			[
283
+				'name' => 'dummytask',
284
+				'data' => null
285
+			],
286
+			[
287
+				'name' => 'dummytask',
288
+				'data' => null
289
+			]
290
+		];
291 291
 
292
-        foreach ($expected as $item) {
293
-            $tmp = $this->QueuedTasks->requestJob($capabilities);
292
+		foreach ($expected as $item) {
293
+			$tmp = $this->QueuedTasks->requestJob($capabilities);
294 294
 
295
-            $this->assertSame($item['name'], $tmp['task']);
296
-            $this->assertEquals($item['data'], unserialize($tmp['data']));
297
-        }
298
-    }
295
+			$this->assertSame($item['name'], $tmp['task']);
296
+			$this->assertEquals($item['data'], unserialize($tmp['data']));
297
+		}
298
+	}
299 299
 
300
-    /**
301
-     * Helper method for skipping tests that need a real connection.
302
-     *
303
-     * @return void
304
-     */
305
-    protected function _needsConnection()
306
-    {
307
-        $config = ConnectionManager::getConfig('test');
308
-        $this->skipIf(strpos($config['driver'], 'Mysql') === false, 'Only Mysql is working yet for this.');
309
-    }
300
+	/**
301
+	 * Helper method for skipping tests that need a real connection.
302
+	 *
303
+	 * @return void
304
+	 */
305
+	protected function _needsConnection()
306
+	{
307
+		$config = ConnectionManager::getConfig('test');
308
+		$this->skipIf(strpos($config['driver'], 'Mysql') === false, 'Only Mysql is working yet for this.');
309
+	}
310 310
 }
Please login to merge, or discard this patch.
tests/TestCase/Shell/QueueShellTest.php 1 patch
Indentation   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -11,187 +11,187 @@
 block discarded – undo
11 11
 
12 12
 class QueueShellTest extends TestCase
13 13
 {
14
-    use ToolsTestTrait;
15
-
16
-    /**
17
-     *
18
-     * @var \Queue\Shell\QueueShell|\PHPUnit_Framework_MockObject_MockObject
19
-     */
20
-    public $QueueShell;
21
-
22
-    /**
23
-     *
24
-     * @var \Tools\TestSuite\ConsoleOutput
25
-     */
26
-    public $out;
27
-
28
-    /**
29
-     *
30
-     * @var \Tools\TestSuite\ConsoleOutput
31
-     */
32
-    public $err;
33
-
34
-    /**
35
-     * Fixtures to load
36
-     *
37
-     * @var array
38
-     */
39
-    public $fixtures = [
40
-        'plugin.Queue.QueuedTasks'
41
-    ];
42
-
43
-    /**
44
-     * Setup Defaults
45
-     *
46
-     * @return void
47
-     */
48
-    public function setUp()
49
-    {
50
-        parent::setUp();
51
-
52
-        $this->out = new ConsoleOutput();
53
-        $this->err = new ConsoleOutput();
54
-        $io = new ConsoleIo($this->out, $this->err);
55
-
56
-        $this->QueueShell = $this->getMockBuilder(QueueShell::class)
57
-            ->setMethods([
58
-                'in',
59
-                'err',
60
-                '_stop'
61
-            ])
62
-            ->setConstructorArgs([
63
-                $io
64
-            ])
65
-            ->getMock();
66
-        $this->QueueShell->initialize();
67
-
68
-        Configure::write('Queue', [
69
-            'sleepTime' => 2,
70
-            'defaultWorkerTimeout' => 3,
71
-            'workerMaxRuntime' => 5,
72
-            'cleanupTimeout' => 10,
73
-            'exitWhenNothingToDo' => false,
74
-            'log' => false
75
-        ]);
76
-    }
77
-
78
-    /**
79
-     *
80
-     * @return void
81
-     */
82
-    public function testObject()
83
-    {
84
-        $this->assertTrue(is_object($this->QueueShell));
85
-        $this->assertInstanceOf(QueueShell::class, $this->QueueShell);
86
-    }
87
-
88
-    /**
89
-     *
90
-     * @return void
91
-     */
92
-    public function testStats()
93
-    {
94
-        $this->_needsConnection();
95
-
96
-        $this->QueueShell->stats();
97
-        $this->assertContains('Total unfinished jobs: 0', $this->out->output());
98
-    }
99
-
100
-    /**
101
-     *
102
-     * @return void
103
-     */
104
-    public function testSettings()
105
-    {
106
-        $this->QueueShell->settings();
107
-        $this->assertContains('* cleanupTimeout: 10', $this->out->output());
108
-    }
109
-
110
-    /**
111
-     *
112
-     * @return void
113
-     */
114
-    public function testAddInexistent()
115
-    {
116
-        $this->QueueShell->args[] = 'FooBar';
117
-        $this->QueueShell->add();
118
-        $this->assertContains('Error: Task not found: FooBar', $this->out->output());
119
-    }
120
-
121
-    /**
122
-     *
123
-     * @return void
124
-     */
125
-    public function testAdd()
126
-    {
127
-        $this->QueueShell->args[] = 'Example';
128
-        $this->QueueShell->add();
129
-
130
-        $this->assertContains('OK, job created, now run the worker', $this->out->output(), print_r($this->out->output(), true));
131
-    }
132
-
133
-    /**
134
-     *
135
-     * @return void
136
-     */
137
-    public function testTimeNeeded()
138
-    {
139
-        $this->QueueShell = $this->getMockBuilder(QueueShell::class)
140
-            ->setMethods([
141
-                '_time'
142
-            ])
143
-            ->getMock();
144
-
145
-        $first = time();
146
-        $second = $first - HOUR + MINUTE;
147
-        $this->QueueShell->expects($this->at(0))
148
-            ->method('_time')
149
-            ->will($this->returnValue($first));
150
-        $this->QueueShell->expects($this->at(1))
151
-            ->method('_time')
152
-            ->will($this->returnValue($second));
153
-        $this->QueueShell->expects($this->exactly(2))
154
-            ->method('_time')
155
-            ->withAnyParameters();
156
-
157
-        $result = $this->invokeMethod($this->QueueShell, '_timeNeeded');
158
-        $this->assertSame('3540s', $result);
159
-    }
160
-
161
-    /**
162
-     *
163
-     * @return void
164
-     */
165
-    public function testMemoryUsage()
166
-    {
167
-        $result = $this->invokeMethod($this->QueueShell, '_memoryUsage');
168
-        $this->assertRegExp('/^\d+MB/', $result, 'Should be e.g. `17MB` or `17MB/1GB` etc.');
169
-    }
170
-
171
-    /**
172
-     *
173
-     * @return void
174
-     */
175
-    public function testStringToArray()
176
-    {
177
-        $string = 'Foo,Bar,';
178
-        $result = $this->invokeMethod($this->QueueShell, '_stringToArray', [$string]);
179
-
180
-        $expected = [
181
-            'Foo',
182
-            'Bar'
183
-        ];
184
-        $this->assertSame($expected, $result);
185
-    }
186
-
187
-    /**
188
-     * Helper method for skipping tests that need a real connection.
189
-     *
190
-     * @return void
191
-     */
192
-    protected function _needsConnection()
193
-    {
194
-        $config = ConnectionManager::getConfig('test');
195
-        $this->skipIf(strpos($config['driver'], 'Mysql') === false, 'Only Mysql is working yet for this.');
196
-    }
14
+	use ToolsTestTrait;
15
+
16
+	/**
17
+	 *
18
+	 * @var \Queue\Shell\QueueShell|\PHPUnit_Framework_MockObject_MockObject
19
+	 */
20
+	public $QueueShell;
21
+
22
+	/**
23
+	 *
24
+	 * @var \Tools\TestSuite\ConsoleOutput
25
+	 */
26
+	public $out;
27
+
28
+	/**
29
+	 *
30
+	 * @var \Tools\TestSuite\ConsoleOutput
31
+	 */
32
+	public $err;
33
+
34
+	/**
35
+	 * Fixtures to load
36
+	 *
37
+	 * @var array
38
+	 */
39
+	public $fixtures = [
40
+		'plugin.Queue.QueuedTasks'
41
+	];
42
+
43
+	/**
44
+	 * Setup Defaults
45
+	 *
46
+	 * @return void
47
+	 */
48
+	public function setUp()
49
+	{
50
+		parent::setUp();
51
+
52
+		$this->out = new ConsoleOutput();
53
+		$this->err = new ConsoleOutput();
54
+		$io = new ConsoleIo($this->out, $this->err);
55
+
56
+		$this->QueueShell = $this->getMockBuilder(QueueShell::class)
57
+			->setMethods([
58
+				'in',
59
+				'err',
60
+				'_stop'
61
+			])
62
+			->setConstructorArgs([
63
+				$io
64
+			])
65
+			->getMock();
66
+		$this->QueueShell->initialize();
67
+
68
+		Configure::write('Queue', [
69
+			'sleepTime' => 2,
70
+			'defaultWorkerTimeout' => 3,
71
+			'workerMaxRuntime' => 5,
72
+			'cleanupTimeout' => 10,
73
+			'exitWhenNothingToDo' => false,
74
+			'log' => false
75
+		]);
76
+	}
77
+
78
+	/**
79
+	 *
80
+	 * @return void
81
+	 */
82
+	public function testObject()
83
+	{
84
+		$this->assertTrue(is_object($this->QueueShell));
85
+		$this->assertInstanceOf(QueueShell::class, $this->QueueShell);
86
+	}
87
+
88
+	/**
89
+	 *
90
+	 * @return void
91
+	 */
92
+	public function testStats()
93
+	{
94
+		$this->_needsConnection();
95
+
96
+		$this->QueueShell->stats();
97
+		$this->assertContains('Total unfinished jobs: 0', $this->out->output());
98
+	}
99
+
100
+	/**
101
+	 *
102
+	 * @return void
103
+	 */
104
+	public function testSettings()
105
+	{
106
+		$this->QueueShell->settings();
107
+		$this->assertContains('* cleanupTimeout: 10', $this->out->output());
108
+	}
109
+
110
+	/**
111
+	 *
112
+	 * @return void
113
+	 */
114
+	public function testAddInexistent()
115
+	{
116
+		$this->QueueShell->args[] = 'FooBar';
117
+		$this->QueueShell->add();
118
+		$this->assertContains('Error: Task not found: FooBar', $this->out->output());
119
+	}
120
+
121
+	/**
122
+	 *
123
+	 * @return void
124
+	 */
125
+	public function testAdd()
126
+	{
127
+		$this->QueueShell->args[] = 'Example';
128
+		$this->QueueShell->add();
129
+
130
+		$this->assertContains('OK, job created, now run the worker', $this->out->output(), print_r($this->out->output(), true));
131
+	}
132
+
133
+	/**
134
+	 *
135
+	 * @return void
136
+	 */
137
+	public function testTimeNeeded()
138
+	{
139
+		$this->QueueShell = $this->getMockBuilder(QueueShell::class)
140
+			->setMethods([
141
+				'_time'
142
+			])
143
+			->getMock();
144
+
145
+		$first = time();
146
+		$second = $first - HOUR + MINUTE;
147
+		$this->QueueShell->expects($this->at(0))
148
+			->method('_time')
149
+			->will($this->returnValue($first));
150
+		$this->QueueShell->expects($this->at(1))
151
+			->method('_time')
152
+			->will($this->returnValue($second));
153
+		$this->QueueShell->expects($this->exactly(2))
154
+			->method('_time')
155
+			->withAnyParameters();
156
+
157
+		$result = $this->invokeMethod($this->QueueShell, '_timeNeeded');
158
+		$this->assertSame('3540s', $result);
159
+	}
160
+
161
+	/**
162
+	 *
163
+	 * @return void
164
+	 */
165
+	public function testMemoryUsage()
166
+	{
167
+		$result = $this->invokeMethod($this->QueueShell, '_memoryUsage');
168
+		$this->assertRegExp('/^\d+MB/', $result, 'Should be e.g. `17MB` or `17MB/1GB` etc.');
169
+	}
170
+
171
+	/**
172
+	 *
173
+	 * @return void
174
+	 */
175
+	public function testStringToArray()
176
+	{
177
+		$string = 'Foo,Bar,';
178
+		$result = $this->invokeMethod($this->QueueShell, '_stringToArray', [$string]);
179
+
180
+		$expected = [
181
+			'Foo',
182
+			'Bar'
183
+		];
184
+		$this->assertSame($expected, $result);
185
+	}
186
+
187
+	/**
188
+	 * Helper method for skipping tests that need a real connection.
189
+	 *
190
+	 * @return void
191
+	 */
192
+	protected function _needsConnection()
193
+	{
194
+		$config = ConnectionManager::getConfig('test');
195
+		$this->skipIf(strpos($config['driver'], 'Mysql') === false, 'Only Mysql is working yet for this.');
196
+	}
197 197
 }
Please login to merge, or discard this patch.