InstallerTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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, $expectExitCode)
  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. $composer = FactoryMock::create($io, $composerConfig);
  127. $jsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock();
  128. $jsonMock->expects($this->any())
  129. ->method('read')
  130. ->will($this->returnValue($installed));
  131. $jsonMock->expects($this->any())
  132. ->method('exists')
  133. ->will($this->returnValue(true));
  134. $repositoryManager = $composer->getRepositoryManager();
  135. $repositoryManager->setLocalRepository(new InstalledFilesystemRepositoryMock($jsonMock));
  136. $lockJsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock();
  137. $lockJsonMock->expects($this->any())
  138. ->method('read')
  139. ->will($this->returnValue($lock));
  140. $lockJsonMock->expects($this->any())
  141. ->method('exists')
  142. ->will($this->returnValue(true));
  143. if ($expectLock) {
  144. $actualLock = array();
  145. $lockJsonMock->expects($this->atLeastOnce())
  146. ->method('write')
  147. ->will($this->returnCallback(function ($hash, $options) use (&$actualLock) {
  148. // need to do assertion outside of mock for nice phpunit output
  149. // so store value temporarily in reference for later assetion
  150. $actualLock = $hash;
  151. }));
  152. }
  153. $contents = json_encode($composerConfig);
  154. $locker = new Locker($io, $lockJsonMock, $repositoryManager, $composer->getInstallationManager(), $contents);
  155. $composer->setLocker($locker);
  156. $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock();
  157. $autoloadGenerator = $this->getMock('Composer\Autoload\AutoloadGenerator', array(), array($eventDispatcher));
  158. $composer->setAutoloadGenerator($autoloadGenerator);
  159. $composer->setEventDispatcher($eventDispatcher);
  160. $installer = Installer::create($io, $composer);
  161. $application = new Application;
  162. $application->get('install')->setCode(function ($input, $output) use ($installer) {
  163. $installer
  164. ->setDevMode(!$input->getOption('no-dev'))
  165. ->setDryRun($input->getOption('dry-run'))
  166. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'));
  167. return $installer->run();
  168. });
  169. $application->get('update')->setCode(function ($input, $output) use ($installer) {
  170. $installer
  171. ->setDevMode(!$input->getOption('no-dev'))
  172. ->setUpdate(true)
  173. ->setDryRun($input->getOption('dry-run'))
  174. ->setUpdateWhitelist($input->getArgument('packages'))
  175. ->setWhitelistDependencies($input->getOption('with-dependencies'))
  176. ->setPreferStable($input->getOption('prefer-stable'))
  177. ->setPreferLowest($input->getOption('prefer-lowest'))
  178. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'));
  179. return $installer->run();
  180. });
  181. if (!preg_match('{^(install|update)\b}', $run)) {
  182. throw new \UnexpectedValueException('The run command only supports install and update');
  183. }
  184. $application->setAutoExit(false);
  185. $appOutput = fopen('php://memory', 'w+');
  186. $result = $application->run(new StringInput($run), new StreamOutput($appOutput));
  187. fseek($appOutput, 0);
  188. $output = str_replace("\r", '', $io->getOutput());
  189. $this->assertEquals($expectExitCode, $result, $output . stream_get_contents($appOutput));
  190. if ($expectLock) {
  191. unset($actualLock['hash']);
  192. unset($actualLock['content-hash']);
  193. unset($actualLock['_readme']);
  194. $this->assertEquals($expectLock, $actualLock);
  195. }
  196. $installationManager = $composer->getInstallationManager();
  197. $this->assertSame(rtrim($expect), implode("\n", $installationManager->getTrace()));
  198. if ($expectOutput) {
  199. $this->assertEquals(rtrim($expectOutput), rtrim($output));
  200. }
  201. }
  202. public function getIntegrationTests()
  203. {
  204. $fixturesDir = realpath(__DIR__.'/Fixtures/installer/');
  205. $tests = array();
  206. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  207. if (!preg_match('/\.test$/', $file)) {
  208. continue;
  209. }
  210. $testData = $this->readTestFile($file, $fixturesDir);
  211. $installed = array();
  212. $installedDev = array();
  213. $lock = array();
  214. $expectLock = array();
  215. $expectExitCode = 0;
  216. try {
  217. $message = $testData['TEST'];
  218. $condition = !empty($testData['CONDITION']) ? $testData['CONDITION'] : null;
  219. $composer = JsonFile::parseJson($testData['COMPOSER']);
  220. if (isset($composer['repositories'])) {
  221. foreach ($composer['repositories'] as &$repo) {
  222. if ($repo['type'] !== 'composer') {
  223. continue;
  224. }
  225. // Change paths like file://foobar to file:///path/to/fixtures
  226. if (preg_match('{^file://[^/]}', $repo['url'])) {
  227. $repo['url'] = 'file://' . strtr($fixturesDir, '\\', '/') . '/' . substr($repo['url'], 7);
  228. }
  229. unset($repo);
  230. }
  231. }
  232. if (!empty($testData['LOCK'])) {
  233. $lock = JsonFile::parseJson($testData['LOCK']);
  234. if (!isset($lock['hash'])) {
  235. $lock['hash'] = md5(json_encode($composer));
  236. }
  237. }
  238. if (!empty($testData['INSTALLED'])) {
  239. $installed = JsonFile::parseJson($testData['INSTALLED']);
  240. }
  241. $run = $testData['RUN'];
  242. if (!empty($testData['EXPECT-LOCK'])) {
  243. $expectLock = JsonFile::parseJson($testData['EXPECT-LOCK']);
  244. }
  245. $expectOutput = isset($testData['EXPECT-OUTPUT']) ? $testData['EXPECT-OUTPUT'] : null;
  246. $expect = $testData['EXPECT'];
  247. $expectExitCode = isset($testData['EXPECT-EXIT-CODE']) ? (int) $testData['EXPECT-EXIT-CODE'] : 0;
  248. } catch (\Exception $e) {
  249. die(sprintf('Test "%s" is not valid: '.$e->getMessage(), str_replace($fixturesDir.'/', '', $file)));
  250. }
  251. $tests[basename($file)] = array(str_replace($fixturesDir.'/', '', $file), $message, $condition, $composer, $lock, $installed, $run, $expectLock, $expectOutput, $expect, $expectExitCode);
  252. }
  253. return $tests;
  254. }
  255. protected function readTestFile(\SplFileInfo $file, $fixturesDir)
  256. {
  257. $tokens = preg_split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), null, PREG_SPLIT_DELIM_CAPTURE);
  258. $sectionInfo = array(
  259. 'TEST' => true,
  260. 'CONDITION' => false,
  261. 'COMPOSER' => true,
  262. 'LOCK' => false,
  263. 'INSTALLED' => false,
  264. 'RUN' => true,
  265. 'EXPECT-LOCK' => false,
  266. 'EXPECT-OUTPUT' => false,
  267. 'EXPECT-EXIT-CODE' => false,
  268. 'EXPECT' => true,
  269. );
  270. $section = null;
  271. foreach ($tokens as $i => $token) {
  272. if (null === $section && empty($token)) {
  273. continue; // skip leading blank
  274. }
  275. if (null === $section) {
  276. if (!isset($sectionInfo[$token])) {
  277. throw new \RuntimeException(sprintf(
  278. 'The test file "%s" must not contain a section named "%s".',
  279. str_replace($fixturesDir.'/', '', $file),
  280. $token
  281. ));
  282. }
  283. $section = $token;
  284. continue;
  285. }
  286. $sectionData = $token;
  287. $data[$section] = $sectionData;
  288. $section = $sectionData = null;
  289. }
  290. foreach ($sectionInfo as $section => $required) {
  291. if ($required && !isset($data[$section])) {
  292. throw new \RuntimeException(sprintf(
  293. 'The test file "%s" must have a section named "%s".',
  294. str_replace($fixturesDir.'/', '', $file),
  295. $section
  296. ));
  297. }
  298. }
  299. return $data;
  300. }
  301. }