InstallerTest.php 15 KB

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