TestCase.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer;
  12. use Composer\Semver\VersionParser;
  13. use Composer\Package\AliasPackage;
  14. use Composer\Semver\Constraint\Constraint;
  15. use Composer\Util\Filesystem;
  16. use Composer\Util\Silencer;
  17. use Symfony\Component\Process\ExecutableFinder;
  18. abstract class TestCase extends \PHPUnit_Framework_TestCase
  19. {
  20. private static $parser;
  21. public static function getUniqueTmpDirectory()
  22. {
  23. $attempts = 5;
  24. $root = sys_get_temp_dir();
  25. do {
  26. $unique = $root . DIRECTORY_SEPARATOR . uniqid('composer-test-' . rand(1000, 9000));
  27. if (!file_exists($unique) && Silencer::call('mkdir', $unique, 0777)) {
  28. return realpath($unique);
  29. }
  30. } while (--$attempts);
  31. throw new \RuntimeException('Failed to create a unique temporary directory.');
  32. }
  33. protected static function getVersionParser()
  34. {
  35. if (!self::$parser) {
  36. self::$parser = new VersionParser();
  37. }
  38. return self::$parser;
  39. }
  40. protected function getVersionConstraint($operator, $version)
  41. {
  42. $constraint = new Constraint(
  43. $operator,
  44. self::getVersionParser()->normalize($version)
  45. );
  46. $constraint->setPrettyString($operator.' '.$version);
  47. return $constraint;
  48. }
  49. protected function getPackage($name, $version, $class = 'Composer\Package\Package')
  50. {
  51. $normVersion = self::getVersionParser()->normalize($version);
  52. return new $class($name, $normVersion, $version);
  53. }
  54. protected function getAliasPackage($package, $version)
  55. {
  56. $normVersion = self::getVersionParser()->normalize($version);
  57. return new AliasPackage($package, $normVersion, $version);
  58. }
  59. protected static function ensureDirectoryExistsAndClear($directory)
  60. {
  61. $fs = new Filesystem();
  62. if (is_dir($directory)) {
  63. $fs->removeDirectory($directory);
  64. }
  65. mkdir($directory, 0777, true);
  66. }
  67. /**
  68. * Check whether or not the given name is an available executable.
  69. *
  70. * @param string $executableName The name of the binary to test.
  71. *
  72. * @throws PHPUnit_Framework_SkippedTestError
  73. */
  74. protected function skipIfNotExecutable($executableName)
  75. {
  76. $finder = new ExecutableFinder();
  77. if (!$finder->find($executableName))
  78. $this->markTestSkipped($executableName . ' is not found or not executable.');
  79. }
  80. }