CommandUnishTestCase.php

  1. 8.0.x tests/Unish/CommandUnishTestCase.php
  2. 7.x tests/Unish/CommandUnishTestCase.php
  3. master tests/Unish/CommandUnishTestCase.php

Namespace

Unish

Classes

File

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