InstallerTest.php 16 KB

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