forked from drush-ops/drush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommandUnishTestCase.php
439 lines (400 loc) · 13.1 KB
/
CommandUnishTestCase.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<?php
namespace Unish;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Webmozart\PathUtil\Path;
abstract class CommandUnishTestCase extends UnishTestCase {
// Unix exit codes.
const EXIT_SUCCESS = 0;
const EXIT_ERROR = 1;
const UNISH_EXITCODE_USER_ABORT = 75; // Same as DRUSH_EXITCODE_USER_ABORT
/**
* Code coverage data collected during a single test.
*
* @var array
*/
protected $coverage_data = array();
/**
* Process of last executed command.
*
* @var Process
*/
private $process;
/**
* Default timeout for commands.
*
* @var int
*/
private $defaultTimeout = 60;
/**
* Timeout for command.
*
* Reset to $defaultTimeout after executing a command.
*
* @var int
*/
protected $timeout = 60;
/**
* Default idle timeout for commands.
*
* @var int
*/
private $defaultIdleTimeout = 15;
/**
* Idle timeouts for commands.
*
* Reset to $defaultIdleTimeout after executing a command.
*
* @var int
*/
protected $idleTimeout = 15;
/**
* Accessor for the last output, trimmed.
*
* @return string
* Trimmed output as text.
*
* @access public
*/
function getOutput() {
return trim($this->getOutputRaw());
}
/**
* Accessor for the last output, non-trimmed.
*
* @return string
* Raw output as text.
*
* @access public
*/
function getOutputRaw() {
return $this->process ? $this->process->getOutput() : '';
}
/**
* Accessor for the last output, rtrimmed and split on newlines.
*
* @return array
* Output as array of lines.
*
* @access public
*/
function getOutputAsList() {
return array_map('rtrim', explode("\n", $this->getOutput()));
}
/**
* Accessor for the last stderr output, trimmed.
*
* @return string
* Trimmed stderr as text.
*
* @access public
*/
function getErrorOutput() {
return trim($this->getErrorOutputRaw());
}
/**
* Accessor for the last stderr output, non-trimmed.
*
* @return string
* Raw stderr as text.
*
* @access public
*/
function getErrorOutputRaw() {
return $this->process ? $this->process->getErrorOutput() : '';
}
/**
* Accessor for the last stderr output, rtrimmed and split on newlines.
*
* @return array
* Stderr as array of lines.
*
* @access public
*/
function getErrorOutputAsList() {
return array_map('rtrim', explode("\n", $this->getErrorOutput()));
}
/**
* Accessor for the last output, decoded from json.
*
* @param string $key
* Optionally return only a top level element from the json object.
*
* @return object
* Decoded object.
*/
function getOutputFromJSON($key = NULL) {
$json = json_decode($this->getOutput());
if (isset($key)) {
$json = $json->{$key}; // http://stackoverflow.com/questions/2925044/hyphens-in-keys-of-object
}
return $json;
}
/**
* Actually runs the command.
*
* @param string $command
* The actual command line to run.
* @param integer $expected_return
* The return code to expect
* @param sting cd
* The directory to run the command in.
* @param array $env
* @todo: Not fully implemented yet. Inheriting environment is hard - http://stackoverflow.com/questions/3780866/why-is-my-env-empty.
* @see drush_env().
* Extra environment variables.
* @param string $input
* A string representing the STDIN that is piped to the command.
* @return integer
* Exit code. Usually self::EXIT_ERROR or self::EXIT_SUCCESS.
*/
function execute($command, $expected_return = self::EXIT_SUCCESS, $cd = NULL, $env = NULL, $input = NULL) {
$return = 1;
$this->tick();
// Apply the environment variables we need for our test to the head of the
// command (excludes Windows). Process does have an $env argument, but it replaces the entire
// environment with the one given. This *could* be used for ensuring the
// test ran with a clean environment, but it also makes tests fail hard on
// Travis, for unknown reasons.
// @see https://github.com/drush-ops/drush/pull/646
$prefix = '';
if($env && !$this->is_windows()) {
foreach ($env as $env_name => $env_value) {
$prefix .= $env_name . '=' . self::escapeshellarg($env_value) . ' ';
}
}
$this->log("Executing: $command", 'verbose');
try {
// Process uses a default timeout of 60 seconds, set it to 0 (none).
$this->process = new Process($command, $cd, NULL, $input, 0);
if (!getenv('UNISH_NO_TIMEOUTS')) {
$this->process->setTimeout($this->timeout)
->setIdleTimeout($this->idleTimeout);
}
$return = $this->process->run();
if ($expected_return !== $return) {
$message = 'Unexpected exit code ' . $return . ' (expected ' . $expected_return . ") for command:\n" . $command;
throw new UnishProcessFailedError($message, $this->process);
}
// Reset timeouts to default.
$this->timeout = $this->defaultTimeout;
$this->idleTimeout = $this->defaultIdleTimeout;
return $return;
}
catch (ProcessTimedOutException $e) {
if ($e->isGeneralTimeout()) {
$message = 'Command runtime exceeded ' . $this->timeout . " seconds:\n" . $command;
}
else {
$message = 'Command had no output for ' . $this->idleTimeout . " seconds:\n" . $command;
}
throw new UnishProcessFailedError($message, $this->process);
}
}
/**
* Invoke drush in via execute().
*
* @param command
* A defined drush command such as 'cron', 'status' or any of the available ones such as 'drush pm'.
* @param args
* Command arguments.
* @param $options
* An associative array containing options.
* @param $site_specification
* A site alias or site specification. Include the '@' at start of a site alias.
* @param $cd
* A directory to change into before executing.
* @param $expected_return
* The expected exit code. Usually self::EXIT_ERROR or self::EXIT_SUCCESS.
* @param $suffix
* Any code to append to the command. For example, redirection like 2>&1.
* @param array $env
* Environment variables to pass along to the subprocess. @todo - not used.
* @return integer
* An exit code.
*/
function drush($command, array $args = array(), array $options = array(), $site_specification = NULL, $cd = NULL, $expected_return = self::EXIT_SUCCESS, $suffix = NULL, $env = array()) {
// cd is added for the benefit of siteSshTest which tests a strict command.
$global_option_list = array('simulate', 'root', 'uri', 'include', 'config', 'alias-path', 'ssh-options', 'backend', 'cd');
$hide_stderr = FALSE;
$cmd[] = self::getDrush();
// Insert global options.
foreach ($options as $key => $value) {
if (in_array($key, $global_option_list)) {
unset($options[$key]);
if ($key == 'backend') {
$hide_stderr = TRUE;
$value = NULL;
}
if (!isset($value)) {
$cmd[] = "--$key";
}
else {
$cmd[] = "--$key=" . self::escapeshellarg($value);
}
}
}
if ($level = $this->log_level()) {
$cmd[] = '--' . $level;
}
$cmd[] = "--no-ansi";
// Insert code coverage argument before command, in order for it to be
// parsed as a global option. This matters for commands like ssh and rsync
// where options after the command are passed along to external commands.
$result = $this->getTestResultObject();
if ($result->getCollectCodeCoverageInformation()) {
$coverage_file = tempnam(UNISH_TMP, 'drush_coverage');
if ($coverage_file) {
$cmd[] = "--drush-coverage=" . $coverage_file;
}
}
// Insert site specification and drush command.
$cmd[] = empty($site_specification) ? NULL : self::escapeshellarg($site_specification);
$cmd[] = $command;
// Insert drush command arguments.
foreach ($args as $arg) {
$cmd[] = self::escapeshellarg($arg);
}
// insert drush command options
foreach ($options as $key => $value) {
if (!isset($value)) {
$cmd[] = "--$key";
}
else {
$cmd[] = "--$key=" . self::escapeshellarg($value);
}
}
$cmd[] = $suffix;
if ($hide_stderr) {
$cmd[] = '2>' . $this->bit_bucket();
}
$exec = array_filter($cmd, 'strlen'); // Remove NULLs
// Set sendmail_path to 'true' to disable any outgoing emails
// that tests might cause Drupal to send.
$php_options = (array_key_exists('PHP_OPTIONS', $env)) ? $env['PHP_OPTIONS'] . " " : "";
// @todo The PHP Options below are not yet honored by execute(). See .travis.yml for an alternative way.
$env['PHP_OPTIONS'] = "${php_options}-d sendmail_path='true'";
$cmd = implode(' ', $exec);
$this->log("> Run $cmd", 'debug');
$return = $this->execute($cmd, $expected_return, $cd, $env);
// Save code coverage information.
if (!empty($coverage_file)) {
$data = unserialize(file_get_contents($coverage_file));
unlink($coverage_file);
// Save for appending after the test finishes.
$this->coverage_data[] = $data;
}
return $return;
}
/**
* Override the run method, so we can add in our code coverage data after the
* test has run.
*
* We have to collect all coverage data, merge them and append them as one, to
* avoid having phpUnit duplicating the test function as many times as drush
* has been invoked.
*
* Runs the test case and collects the results in a TestResult object.
* If no TestResult object is passed a new one will be created.
*
* @param \PHPUnit_Framework_TestResult $result
* @return \PHPUnit_Framework_TestResult
* @throws \PHPUnit_Framework_Exception
*/
public function run(\PHPUnit_Framework_TestResult $result = NULL) {
$result = parent::run($result);
$data = array();
foreach ($this->coverage_data as $merge_data) {
foreach ($merge_data as $file => $lines) {
if (!isset($data[$file])) {
$data[$file] = $lines;
}
else {
foreach ($lines as $num => $executed) {
if (!isset($data[$file][$num])) {
$data[$file][$num] = $executed;
}
else {
$data[$file][$num] = ($executed == 1 ? $executed : $data[$file][$num]);
}
}
}
}
}
// Reset coverage data.
$this->coverage_data = array();
if (!empty($data)) {
$result->getCodeCoverage()->append($data, $this);
}
return $result;
}
/**
* A slightly less functional copy of drush_backend_parse_output().
*/
function parse_backend_output($string) {
$regex = sprintf(self::getBackendOutputDelimiter(), '(.*)');
preg_match("/$regex/s", $string, $match);
if (isset($match[1])) {
// we have our JSON encoded string
$output = $match[1];
// remove the match we just made and any non printing characters
$string = trim(str_replace(sprintf(self::getBackendOutputDelimiter(), $match[1]), '', $string));
}
if (!empty($output)) {
$data = json_decode($output, TRUE);
if (is_array($data)) {
return $data;
}
}
return $string;
}
/**
* Ensure that an expected log message appears in the Drush log.
*
* $this->drush('command', array(), array('backend' => NULL));
* $parsed = $this->parse_backend_output($this->getOutput());
* $this->assertLogHasMessage($parsed['log'], "Expected message", 'debug')
*
* @param $log Parsed log entries from backend invoke
* @param $message The expected message that must be contained in
* some log entry's 'message' field. Substrings will match.
* @param $logType The type of log message to look for; all other
* types are ignored. If FALSE (the default), then all log types
* will be searched.
*/
function assertLogHasMessage($log, $message, $logType = FALSE) {
foreach ($log as $entry) {
if (!$logType || ($entry['type'] == $logType)) {
$logMessage = $this->getLogMessage($entry);
if (strpos($logMessage, $message) !== FALSE) {
return TRUE;
}
}
}
$this->fail("Could not find expected message in log: " . $message);
}
protected function getLogMessage($entry) {
return $this->interpolate($entry['message'], $entry);
}
protected function interpolate($message, array $context)
{
// build a replacement array with braces around the context keys
$replace = array();
foreach ($context as $key => $val) {
if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
$replace[sprintf('{%s}', $key)] = $val;
}
}
// interpolate replacement values into the message and return
return strtr($message, $replace);
}
function drush_major_version() {
static $major;
if (!isset($major)) {
$this->drush('version', array(), array('field' => 'drush-version'));
$version = trim($this->getOutput());
list($major) = explode('.', $version);
}
return (int)$major;
}
}