InstallerTest.php 17 KB

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