InstallerTest.php 20 KB

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