InstallerTest.php 15 KB

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