InstallerTest.php 14 KB

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