InstallerTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. unset($actualLock['plugin-api-version']);
  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. }