InstallerTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 Composer\TestCase;
  27. class InstallerTest extends TestCase
  28. {
  29. protected $prevCwd;
  30. public function setUp()
  31. {
  32. $this->prevCwd = getcwd();
  33. chdir(__DIR__);
  34. }
  35. public function tearDown()
  36. {
  37. chdir($this->prevCwd);
  38. }
  39. /**
  40. * @dataProvider provideInstaller
  41. */
  42. public function testInstaller(RootPackageInterface $rootPackage, $repositories, array $options)
  43. {
  44. $io = $this->getMock('Composer\IO\IOInterface');
  45. $downloadManager = $this->getMock('Composer\Downloader\DownloadManager', array(), array($io));
  46. $config = $this->getMock('Composer\Config');
  47. $repositoryManager = new RepositoryManager($io, $config);
  48. $repositoryManager->setLocalRepository(new InstalledArrayRepository());
  49. if (!is_array($repositories)) {
  50. $repositories = array($repositories);
  51. }
  52. foreach ($repositories as $repository) {
  53. $repositoryManager->addRepository($repository);
  54. }
  55. $locker = $this->getMockBuilder('Composer\Package\Locker')->disableOriginalConstructor()->getMock();
  56. $installationManager = new InstallationManagerMock();
  57. $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock();
  58. $autoloadGenerator = $this->getMockBuilder('Composer\Autoload\AutoloadGenerator')->disableOriginalConstructor()->getMock();
  59. $installer = new Installer($io, $config, clone $rootPackage, $downloadManager, $repositoryManager, $locker, $installationManager, $eventDispatcher, $autoloadGenerator);
  60. $result = $installer->run();
  61. $this->assertSame(0, $result);
  62. $expectedInstalled = isset($options['install']) ? $options['install'] : array();
  63. $expectedUpdated = isset($options['update']) ? $options['update'] : array();
  64. $expectedUninstalled = isset($options['uninstall']) ? $options['uninstall'] : array();
  65. $installed = $installationManager->getInstalledPackages();
  66. $this->assertSame($expectedInstalled, $installed);
  67. $updated = $installationManager->getUpdatedPackages();
  68. $this->assertSame($expectedUpdated, $updated);
  69. $uninstalled = $installationManager->getUninstalledPackages();
  70. $this->assertSame($expectedUninstalled, $uninstalled);
  71. }
  72. public function provideInstaller()
  73. {
  74. $cases = array();
  75. // when A requires B and B requires A, and A is a non-published root package
  76. // the install of B should succeed
  77. $a = $this->getPackage('A', '1.0.0', 'Composer\Package\RootPackage');
  78. $a->setRequires(array(
  79. new Link('A', 'B', $this->getVersionConstraint('=', '1.0.0')),
  80. ));
  81. $b = $this->getPackage('B', '1.0.0');
  82. $b->setRequires(array(
  83. new Link('B', 'A', $this->getVersionConstraint('=', '1.0.0')),
  84. ));
  85. $cases[] = array(
  86. $a,
  87. new ArrayRepository(array($b)),
  88. array(
  89. 'install' => array($b),
  90. ),
  91. );
  92. // #480: when A requires B and B requires A, and A is a published root package
  93. // only B should be installed, as A is the root
  94. $a = $this->getPackage('A', '1.0.0', 'Composer\Package\RootPackage');
  95. $a->setRequires(array(
  96. new Link('A', 'B', $this->getVersionConstraint('=', '1.0.0')),
  97. ));
  98. $b = $this->getPackage('B', '1.0.0');
  99. $b->setRequires(array(
  100. new Link('B', 'A', $this->getVersionConstraint('=', '1.0.0')),
  101. ));
  102. $cases[] = array(
  103. $a,
  104. new ArrayRepository(array($a, $b)),
  105. array(
  106. 'install' => array($b),
  107. ),
  108. );
  109. return $cases;
  110. }
  111. /**
  112. * @dataProvider getIntegrationTests
  113. */
  114. public function testIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectOutput, $expect, $expectResult)
  115. {
  116. if ($condition) {
  117. eval('$res = '.$condition.';');
  118. if (!$res) {
  119. $this->markTestSkipped($condition);
  120. }
  121. }
  122. $output = null;
  123. $io = $this->getMock('Composer\IO\IOInterface');
  124. $callback = function ($text, $newline) use (&$output) {
  125. $output .= $text . ($newline ? "\n" : "");
  126. };
  127. $io->expects($this->any())
  128. ->method('write')
  129. ->will($this->returnCallback($callback));
  130. $io->expects($this->any())
  131. ->method('writeError')
  132. ->will($this->returnCallback($callback));
  133. // Prepare for exceptions
  134. if (!is_int($expectResult)) {
  135. $normalizedOutput = rtrim(str_replace("\n", PHP_EOL, $expect));
  136. $this->setExpectedException($expectResult, $normalizedOutput);
  137. }
  138. // Create Composer mock object according to configuration
  139. $composer = FactoryMock::create($io, $composerConfig);
  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. if (!is_int($expectResult)) {
  202. // Shouldn't check output and results if an exception was expected by this point
  203. return;
  204. }
  205. $this->assertEquals($expectResult, $result, $output . stream_get_contents($appOutput));
  206. if ($expectLock) {
  207. unset($actualLock['hash']);
  208. unset($actualLock['content-hash']);
  209. unset($actualLock['_readme']);
  210. $this->assertEquals($expectLock, $actualLock);
  211. }
  212. $installationManager = $composer->getInstallationManager();
  213. $this->assertSame(rtrim($expect), implode("\n", $installationManager->getTrace()));
  214. if ($expectOutput) {
  215. $this->assertEquals(rtrim($expectOutput), rtrim($output));
  216. }
  217. }
  218. public function getIntegrationTests()
  219. {
  220. $fixturesDir = realpath(__DIR__.'/Fixtures/installer/');
  221. $tests = array();
  222. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  223. if (!preg_match('/\.test$/', $file)) {
  224. continue;
  225. }
  226. $testData = $this->readTestFile($file, $fixturesDir);
  227. $installed = array();
  228. $installedDev = array();
  229. $lock = array();
  230. $expectLock = array();
  231. $expectResult = 0;
  232. try {
  233. $message = $testData['TEST'];
  234. $condition = !empty($testData['CONDITION']) ? $testData['CONDITION'] : null;
  235. $composer = JsonFile::parseJson($testData['COMPOSER']);
  236. if (isset($composer['repositories'])) {
  237. foreach ($composer['repositories'] as &$repo) {
  238. if ($repo['type'] !== 'composer') {
  239. continue;
  240. }
  241. // Change paths like file://foobar to file:///path/to/fixtures
  242. if (preg_match('{^file://[^/]}', $repo['url'])) {
  243. $repo['url'] = 'file://' . strtr($fixturesDir, '\\', '/') . '/' . substr($repo['url'], 7);
  244. }
  245. unset($repo);
  246. }
  247. }
  248. if (!empty($testData['LOCK'])) {
  249. $lock = JsonFile::parseJson($testData['LOCK']);
  250. if (!isset($lock['hash'])) {
  251. $lock['hash'] = md5(json_encode($composer));
  252. }
  253. }
  254. if (!empty($testData['INSTALLED'])) {
  255. $installed = JsonFile::parseJson($testData['INSTALLED']);
  256. }
  257. $run = $testData['RUN'];
  258. if (!empty($testData['EXPECT-LOCK'])) {
  259. $expectLock = JsonFile::parseJson($testData['EXPECT-LOCK']);
  260. }
  261. $expectOutput = isset($testData['EXPECT-OUTPUT']) ? $testData['EXPECT-OUTPUT'] : null;
  262. $expect = $testData['EXPECT'];
  263. if (!empty($testData['EXPECT-EXCEPTION'])) {
  264. $expectResult = $testData['EXPECT-EXCEPTION'];
  265. if (!empty($testData['EXPECT-EXIT-CODE'])) {
  266. throw new \LogicException('EXPECT-EXCEPTION and EXPECT-EXIT-CODE are mutually exclusive');
  267. }
  268. } elseif (!empty($testData['EXPECT-EXIT-CODE'])) {
  269. $expectResult = (int) $testData['EXPECT-EXIT-CODE'];
  270. } else {
  271. $expectResult = 0;
  272. }
  273. } catch (\Exception $e) {
  274. die(sprintf('Test "%s" is not valid: '.$e->getMessage(), str_replace($fixturesDir.'/', '', $file)));
  275. }
  276. $tests[basename($file)] = array(str_replace($fixturesDir.'/', '', $file), $message, $condition, $composer, $lock, $installed, $run, $expectLock, $expectOutput, $expect, $expectResult);
  277. }
  278. return $tests;
  279. }
  280. protected function readTestFile(\SplFileInfo $file, $fixturesDir)
  281. {
  282. $tokens = preg_split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), null, PREG_SPLIT_DELIM_CAPTURE);
  283. $sectionInfo = array(
  284. 'TEST' => true,
  285. 'CONDITION' => false,
  286. 'COMPOSER' => true,
  287. 'LOCK' => false,
  288. 'INSTALLED' => false,
  289. 'RUN' => true,
  290. 'EXPECT-LOCK' => false,
  291. 'EXPECT-OUTPUT' => false,
  292. 'EXPECT-EXIT-CODE' => false,
  293. 'EXPECT-EXCEPTION' => false,
  294. 'EXPECT' => true,
  295. );
  296. $section = null;
  297. foreach ($tokens as $i => $token) {
  298. if (null === $section && empty($token)) {
  299. continue; // skip leading blank
  300. }
  301. if (null === $section) {
  302. if (!isset($sectionInfo[$token])) {
  303. throw new \RuntimeException(sprintf(
  304. 'The test file "%s" must not contain a section named "%s".',
  305. str_replace($fixturesDir.'/', '', $file),
  306. $token
  307. ));
  308. }
  309. $section = $token;
  310. continue;
  311. }
  312. $sectionData = $token;
  313. $data[$section] = $sectionData;
  314. $section = $sectionData = null;
  315. }
  316. foreach ($sectionInfo as $section => $required) {
  317. if ($required && !isset($data[$section])) {
  318. throw new \RuntimeException(sprintf(
  319. 'The test file "%s" must have a section named "%s".',
  320. str_replace($fixturesDir.'/', '', $file),
  321. $section
  322. ));
  323. }
  324. }
  325. return $data;
  326. }
  327. }