InstallerTest.php 15 KB

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