InstallerTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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, $httpDownloader, $eventDispatcher);
  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. } elseif ($expectLock === false) {
  169. $lockJsonMock->expects($this->never())
  170. ->method('write');
  171. }
  172. $contents = json_encode($composerConfig);
  173. $locker = new Locker($io, $lockJsonMock, $composer->getInstallationManager(), $contents);
  174. $composer->setLocker($locker);
  175. $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock();
  176. $autoloadGenerator = $this->getMockBuilder('Composer\Autoload\AutoloadGenerator')
  177. ->setConstructorArgs(array($eventDispatcher))
  178. ->getMock();
  179. $composer->setAutoloadGenerator($autoloadGenerator);
  180. $composer->setEventDispatcher($eventDispatcher);
  181. $installer = Installer::create($io, $composer);
  182. $application = new Application;
  183. $application->get('install')->setCode(function ($input, $output) use ($installer) {
  184. $installer
  185. ->setDevMode(!$input->getOption('no-dev'))
  186. ->setDryRun($input->getOption('dry-run'))
  187. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'));
  188. return $installer->run();
  189. });
  190. $application->get('update')->setCode(function ($input, $output) use ($installer) {
  191. $installer
  192. ->setDevMode(!$input->getOption('no-dev'))
  193. ->setUpdate(true)
  194. ->setDryRun($input->getOption('dry-run'))
  195. ->setUpdateWhitelist($input->getArgument('packages'))
  196. ->setWhitelistTransitiveDependencies($input->getOption('with-dependencies'))
  197. ->setWhitelistAllDependencies($input->getOption('with-all-dependencies'))
  198. ->setPreferStable($input->getOption('prefer-stable'))
  199. ->setPreferLowest($input->getOption('prefer-lowest'))
  200. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'));
  201. return $installer->run();
  202. });
  203. if (!preg_match('{^(install|update)\b}', $run)) {
  204. throw new \UnexpectedValueException('The run command only supports install and update');
  205. }
  206. $application->setAutoExit(false);
  207. $appOutput = fopen('php://memory', 'w+');
  208. $input = new StringInput($run);
  209. $input->setInteractive(false);
  210. $result = $application->run($input, new StreamOutput($appOutput));
  211. fseek($appOutput, 0);
  212. // Shouldn't check output and results if an exception was expected by this point
  213. if (!is_int($expectResult)) {
  214. return;
  215. }
  216. $output = str_replace("\r", '', $io->getOutput());
  217. $this->assertEquals($expectResult, $result, $output . stream_get_contents($appOutput));
  218. if ($expectLock) {
  219. unset($actualLock['hash']);
  220. unset($actualLock['content-hash']);
  221. unset($actualLock['_readme']);
  222. $this->assertEquals($expectLock, $actualLock);
  223. }
  224. $installationManager = $composer->getInstallationManager();
  225. $this->assertSame(rtrim($expect), implode("\n", $installationManager->getTrace()));
  226. if ($expectOutput) {
  227. $this->assertStringMatchesFormat(rtrim($expectOutput), rtrim($output));
  228. }
  229. }
  230. public function getIntegrationTests()
  231. {
  232. $fixturesDir = realpath(__DIR__.'/Fixtures/installer/');
  233. $tests = array();
  234. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  235. if (!preg_match('/\.test$/', $file)) {
  236. continue;
  237. }
  238. try {
  239. $testData = $this->readTestFile($file, $fixturesDir);
  240. $installed = array();
  241. $installedDev = array();
  242. $lock = array();
  243. $expectLock = array();
  244. $expectResult = 0;
  245. $message = $testData['TEST'];
  246. $condition = !empty($testData['CONDITION']) ? $testData['CONDITION'] : null;
  247. $composer = JsonFile::parseJson($testData['COMPOSER']);
  248. if (isset($composer['repositories'])) {
  249. foreach ($composer['repositories'] as &$repo) {
  250. if ($repo['type'] !== 'composer') {
  251. continue;
  252. }
  253. // Change paths like file://foobar to file:///path/to/fixtures
  254. if (preg_match('{^file://[^/]}', $repo['url'])) {
  255. $repo['url'] = 'file://' . strtr($fixturesDir, '\\', '/') . '/' . substr($repo['url'], 7);
  256. }
  257. unset($repo);
  258. }
  259. }
  260. if (!empty($testData['LOCK'])) {
  261. $lock = JsonFile::parseJson($testData['LOCK']);
  262. if (!isset($lock['hash'])) {
  263. $lock['hash'] = md5(json_encode($composer));
  264. }
  265. }
  266. if (!empty($testData['INSTALLED'])) {
  267. $installed = JsonFile::parseJson($testData['INSTALLED']);
  268. }
  269. $run = $testData['RUN'];
  270. if (!empty($testData['EXPECT-LOCK'])) {
  271. if ($testData['EXPECT-LOCK'] === 'false') {
  272. $expectLock = false;
  273. } else {
  274. $expectLock = JsonFile::parseJson($testData['EXPECT-LOCK']);
  275. }
  276. }
  277. $expectOutput = isset($testData['EXPECT-OUTPUT']) ? $testData['EXPECT-OUTPUT'] : null;
  278. $expect = $testData['EXPECT'];
  279. if (!empty($testData['EXPECT-EXCEPTION'])) {
  280. $expectResult = $testData['EXPECT-EXCEPTION'];
  281. if (!empty($testData['EXPECT-EXIT-CODE'])) {
  282. throw new \LogicException('EXPECT-EXCEPTION and EXPECT-EXIT-CODE are mutually exclusive');
  283. }
  284. } elseif (!empty($testData['EXPECT-EXIT-CODE'])) {
  285. $expectResult = (int) $testData['EXPECT-EXIT-CODE'];
  286. } else {
  287. $expectResult = 0;
  288. }
  289. } catch (\Exception $e) {
  290. die(sprintf('Test "%s" is not valid: '.$e->getMessage(), str_replace($fixturesDir.'/', '', $file)));
  291. }
  292. $tests[basename($file)] = array(str_replace($fixturesDir.'/', '', $file), $message, $condition, $composer, $lock, $installed, $run, $expectLock, $expectOutput, $expect, $expectResult);
  293. }
  294. return $tests;
  295. }
  296. protected function readTestFile(\SplFileInfo $file, $fixturesDir)
  297. {
  298. $tokens = preg_split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), null, PREG_SPLIT_DELIM_CAPTURE);
  299. $sectionInfo = array(
  300. 'TEST' => true,
  301. 'CONDITION' => false,
  302. 'COMPOSER' => true,
  303. 'LOCK' => false,
  304. 'INSTALLED' => false,
  305. 'RUN' => true,
  306. 'EXPECT-LOCK' => false,
  307. 'EXPECT-OUTPUT' => false,
  308. 'EXPECT-EXIT-CODE' => false,
  309. 'EXPECT-EXCEPTION' => false,
  310. 'EXPECT' => true,
  311. );
  312. $section = null;
  313. foreach ($tokens as $i => $token) {
  314. if (null === $section && empty($token)) {
  315. continue; // skip leading blank
  316. }
  317. if (null === $section) {
  318. if (!isset($sectionInfo[$token])) {
  319. throw new \RuntimeException(sprintf(
  320. 'The test file "%s" must not contain a section named "%s".',
  321. str_replace($fixturesDir.'/', '', $file),
  322. $token
  323. ));
  324. }
  325. $section = $token;
  326. continue;
  327. }
  328. $sectionData = $token;
  329. $data[$section] = $sectionData;
  330. $section = $sectionData = null;
  331. }
  332. foreach ($sectionInfo as $section => $required) {
  333. if ($required && !isset($data[$section])) {
  334. throw new \RuntimeException(sprintf(
  335. 'The test file "%s" must have a section named "%s".',
  336. str_replace($fixturesDir.'/', '', $file),
  337. $section
  338. ));
  339. }
  340. }
  341. return $data;
  342. }
  343. }