InstallerTest.php 15 KB

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