InstallerTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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\Test;
  12. use Composer\Installer;
  13. use Composer\Console\Application;
  14. use Composer\Config;
  15. use Composer\Json\JsonFile;
  16. use Composer\Repository\ArrayRepository;
  17. use Composer\Repository\RepositoryManager;
  18. use Composer\Repository\InstalledArrayRepository;
  19. use Composer\Package\RootPackageInterface;
  20. use Composer\Package\Link;
  21. use Composer\Package\Locker;
  22. use Composer\Test\Mock\FactoryMock;
  23. use Composer\Test\Mock\InstalledFilesystemRepositoryMock;
  24. use Composer\Test\Mock\InstallationManagerMock;
  25. use Symfony\Component\Console\Input\StringInput;
  26. use Symfony\Component\Console\Output\StreamOutput;
  27. use Composer\TestCase;
  28. class InstallerTest extends TestCase
  29. {
  30. protected $prevCwd;
  31. public function setUp()
  32. {
  33. $this->prevCwd = getcwd();
  34. chdir(__DIR__);
  35. }
  36. public function tearDown()
  37. {
  38. chdir($this->prevCwd);
  39. }
  40. /**
  41. * @dataProvider provideInstaller
  42. */
  43. public function testInstaller(RootPackageInterface $rootPackage, $repositories, array $options)
  44. {
  45. $io = $this->getMock('Composer\IO\IOInterface');
  46. $downloadManager = $this->getMock('Composer\Downloader\DownloadManager', array(), array($io));
  47. $config = $this->getMock('Composer\Config');
  48. $repositoryManager = new RepositoryManager($io, $config);
  49. $repositoryManager->setLocalRepository(new InstalledArrayRepository());
  50. if (!is_array($repositories)) {
  51. $repositories = array($repositories);
  52. }
  53. foreach ($repositories as $repository) {
  54. $repositoryManager->addRepository($repository);
  55. }
  56. $locker = $this->getMockBuilder('Composer\Package\Locker')->disableOriginalConstructor()->getMock();
  57. $installationManager = new InstallationManagerMock();
  58. $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock();
  59. $autoloadGenerator = $this->getMockBuilder('Composer\Autoload\AutoloadGenerator')->disableOriginalConstructor()->getMock();
  60. $installer = new Installer($io, $config, clone $rootPackage, $downloadManager, $repositoryManager, $locker, $installationManager, $eventDispatcher, $autoloadGenerator);
  61. $result = $installer->run();
  62. $this->assertSame(0, $result);
  63. $expectedInstalled = isset($options['install']) ? $options['install'] : array();
  64. $expectedUpdated = isset($options['update']) ? $options['update'] : array();
  65. $expectedUninstalled = isset($options['uninstall']) ? $options['uninstall'] : array();
  66. $installed = $installationManager->getInstalledPackages();
  67. $this->assertSame($expectedInstalled, $installed);
  68. $updated = $installationManager->getUpdatedPackages();
  69. $this->assertSame($expectedUpdated, $updated);
  70. $uninstalled = $installationManager->getUninstalledPackages();
  71. $this->assertSame($expectedUninstalled, $uninstalled);
  72. }
  73. public function provideInstaller()
  74. {
  75. $cases = array();
  76. // when A requires B and B requires A, and A is a non-published root package
  77. // the install of B should succeed
  78. $a = $this->getPackage('A', '1.0.0', 'Composer\Package\RootPackage');
  79. $a->setRequires(array(
  80. new Link('A', 'B', $this->getVersionConstraint('=', '1.0.0')),
  81. ));
  82. $b = $this->getPackage('B', '1.0.0');
  83. $b->setRequires(array(
  84. new Link('B', 'A', $this->getVersionConstraint('=', '1.0.0')),
  85. ));
  86. $cases[] = array(
  87. $a,
  88. new ArrayRepository(array($b)),
  89. array(
  90. 'install' => array($b)
  91. ),
  92. );
  93. // #480: when A requires B and B requires A, and A is a published root package
  94. // only B should be installed, as A is the root
  95. $a = $this->getPackage('A', '1.0.0', 'Composer\Package\RootPackage');
  96. $a->setRequires(array(
  97. new Link('A', 'B', $this->getVersionConstraint('=', '1.0.0')),
  98. ));
  99. $b = $this->getPackage('B', '1.0.0');
  100. $b->setRequires(array(
  101. new Link('B', 'A', $this->getVersionConstraint('=', '1.0.0')),
  102. ));
  103. $cases[] = array(
  104. $a,
  105. new ArrayRepository(array($a, $b)),
  106. array(
  107. 'install' => array($b)
  108. ),
  109. );
  110. return $cases;
  111. }
  112. /**
  113. * @dataProvider getIntegrationTests
  114. */
  115. public function testIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectOutput, $expect, $expectExitCode)
  116. {
  117. if ($condition) {
  118. eval('$res = '.$condition.';');
  119. if (!$res) {
  120. $this->markTestSkipped($condition);
  121. }
  122. }
  123. $output = null;
  124. $io = $this->getMock('Composer\IO\IOInterface');
  125. $callback = function ($text, $newline) use (&$output) {
  126. $output .= $text . ($newline ? "\n" : "");
  127. };
  128. $io->expects($this->any())
  129. ->method('write')
  130. ->will($this->returnCallback($callback));
  131. $io->expects($this->any())
  132. ->method('writeError')
  133. ->will($this->returnCallback($callback));
  134. $composer = FactoryMock::create($io, $composerConfig);
  135. $jsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock();
  136. $jsonMock->expects($this->any())
  137. ->method('read')
  138. ->will($this->returnValue($installed));
  139. $jsonMock->expects($this->any())
  140. ->method('exists')
  141. ->will($this->returnValue(true));
  142. $repositoryManager = $composer->getRepositoryManager();
  143. $repositoryManager->setLocalRepository(new InstalledFilesystemRepositoryMock($jsonMock));
  144. $lockJsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock();
  145. $lockJsonMock->expects($this->any())
  146. ->method('read')
  147. ->will($this->returnValue($lock));
  148. $lockJsonMock->expects($this->any())
  149. ->method('exists')
  150. ->will($this->returnValue(true));
  151. if ($expectLock) {
  152. $actualLock = array();
  153. $lockJsonMock->expects($this->atLeastOnce())
  154. ->method('write')
  155. ->will($this->returnCallback(function ($hash, $options) use (&$actualLock) {
  156. // need to do assertion outside of mock for nice phpunit output
  157. // so store value temporarily in reference for later assetion
  158. $actualLock = $hash;
  159. }));
  160. }
  161. $locker = new Locker($io, $lockJsonMock, $repositoryManager, $composer->getInstallationManager(), md5(json_encode($composerConfig)));
  162. $composer->setLocker($locker);
  163. $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock();
  164. $autoloadGenerator = $this->getMock('Composer\Autoload\AutoloadGenerator', array(), array($eventDispatcher));
  165. $composer->setAutoloadGenerator($autoloadGenerator);
  166. $composer->setEventDispatcher($eventDispatcher);
  167. $installer = Installer::create($io, $composer);
  168. $application = new Application;
  169. $application->get('install')->setCode(function ($input, $output) use ($installer) {
  170. $installer
  171. ->setDevMode(!$input->getOption('no-dev'))
  172. ->setDryRun($input->getOption('dry-run'))
  173. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'));
  174. return $installer->run();
  175. });
  176. $application->get('update')->setCode(function ($input, $output) use ($installer) {
  177. $installer
  178. ->setDevMode(!$input->getOption('no-dev'))
  179. ->setUpdate(true)
  180. ->setDryRun($input->getOption('dry-run'))
  181. ->setUpdateWhitelist($input->getArgument('packages'))
  182. ->setWhitelistDependencies($input->getOption('with-dependencies'))
  183. ->setPreferStable($input->getOption('prefer-stable'))
  184. ->setPreferLowest($input->getOption('prefer-lowest'))
  185. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'));
  186. return $installer->run();
  187. });
  188. if (!preg_match('{^(install|update)\b}', $run)) {
  189. throw new \UnexpectedValueException('The run command only supports install and update');
  190. }
  191. $application->setAutoExit(false);
  192. $appOutput = fopen('php://memory', 'w+');
  193. $result = $application->run(new StringInput($run), new StreamOutput($appOutput));
  194. fseek($appOutput, 0);
  195. $this->assertEquals($expectExitCode, $result, $output . stream_get_contents($appOutput));
  196. if ($expectLock) {
  197. unset($actualLock['hash']);
  198. unset($actualLock['_readme']);
  199. $this->assertEquals($expectLock, $actualLock);
  200. }
  201. $installationManager = $composer->getInstallationManager();
  202. $this->assertSame(rtrim($expect), implode("\n", $installationManager->getTrace()));
  203. if ($expectOutput) {
  204. $this->assertEquals(rtrim($expectOutput), rtrim($output));
  205. }
  206. }
  207. public function getIntegrationTests()
  208. {
  209. $fixturesDir = realpath(__DIR__.'/Fixtures/installer/');
  210. $tests = array();
  211. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  212. if (!preg_match('/\.test$/', $file)) {
  213. continue;
  214. }
  215. $testData = $this->readTestFile($file, $fixturesDir);
  216. $installed = array();
  217. $installedDev = array();
  218. $lock = array();
  219. $expectLock = array();
  220. $expectExitCode = 0;
  221. try {
  222. $message = $testData['TEST'];
  223. $condition = !empty($testData['CONDITION']) ? $testData['CONDITION'] : null;
  224. $composer = JsonFile::parseJson($testData['COMPOSER']);
  225. if (isset($composer['repositories'])) {
  226. foreach ($composer['repositories'] as &$repo) {
  227. if ($repo['type'] !== 'composer') {
  228. continue;
  229. }
  230. // Change paths like file://foobar to file:///path/to/fixtures
  231. if (preg_match('{^file://[^/]}', $repo['url'])) {
  232. $repo['url'] = 'file://' . strtr($fixturesDir, '\\', '/') . '/' . substr($repo['url'], 7);
  233. }
  234. unset($repo);
  235. }
  236. }
  237. if (!empty($testData['LOCK'])) {
  238. $lock = JsonFile::parseJson($testData['LOCK']);
  239. if (!isset($lock['hash'])) {
  240. $lock['hash'] = md5(json_encode($composer));
  241. }
  242. }
  243. if (!empty($testData['INSTALLED'])) {
  244. $installed = JsonFile::parseJson($testData['INSTALLED']);
  245. }
  246. $run = $testData['RUN'];
  247. if (!empty($testData['EXPECT-LOCK'])) {
  248. $expectLock = JsonFile::parseJson($testData['EXPECT-LOCK']);
  249. }
  250. $expectOutput = isset($testData['EXPECT-OUTPUT']) ? $testData['EXPECT-OUTPUT'] : null;
  251. $expect = $testData['EXPECT'];
  252. $expectExitCode = isset($testData['EXPECT-EXIT-CODE']) ? (int) $testData['EXPECT-EXIT-CODE'] : 0;
  253. } catch (\Exception $e) {
  254. die(sprintf('Test "%s" is not valid: '.$e->getMessage(), str_replace($fixturesDir.'/', '', $file)));
  255. }
  256. $tests[basename($file)] = array(str_replace($fixturesDir.'/', '', $file), $message, $condition, $composer, $lock, $installed, $run, $expectLock, $expectOutput, $expect, $expectExitCode);
  257. }
  258. return $tests;
  259. }
  260. protected function readTestFile(\SplFileInfo $file, $fixturesDir)
  261. {
  262. $tokens = preg_split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), null, PREG_SPLIT_DELIM_CAPTURE);
  263. $sectionInfo = array(
  264. 'TEST' => true,
  265. 'CONDITION' => false,
  266. 'COMPOSER' => true,
  267. 'LOCK' => false,
  268. 'INSTALLED' => false,
  269. 'RUN' => true,
  270. 'EXPECT-LOCK' => false,
  271. 'EXPECT-OUTPUT' => false,
  272. 'EXPECT-EXIT-CODE' => false,
  273. 'EXPECT' => true,
  274. );
  275. $section = null;
  276. foreach ($tokens as $i => $token) {
  277. if (null === $section && empty($token)) {
  278. continue; // skip leading blank
  279. }
  280. if (null === $section) {
  281. if (!isset($sectionInfo[$token])) {
  282. throw new \RuntimeException(sprintf(
  283. 'The test file "%s" must not contain a section named "%s".',
  284. str_replace($fixturesDir.'/', '', $file),
  285. $token
  286. ));
  287. }
  288. $section = $token;
  289. continue;
  290. }
  291. $sectionData = $token;
  292. $data[$section] = $sectionData;
  293. $section = $sectionData = null;
  294. }
  295. foreach ($sectionInfo as $section => $required) {
  296. if ($required && !isset($data[$section])) {
  297. throw new \RuntimeException(sprintf(
  298. 'The test file "%s" must have a section named "%s".',
  299. str_replace($fixturesDir.'/', '', $file),
  300. $section
  301. ));
  302. }
  303. }
  304. return $data;
  305. }
  306. }