InstallerTest.php 15 KB

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