File: GitTest.php

package info (click to toggle)
composer 2.9.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,528 kB
  • sloc: php: 83,030; makefile: 59; xml: 39
file content (306 lines) | stat: -rw-r--r-- 12,439 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
<?php declare(strict_types=1);

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Test\Util;

use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
use Composer\Util\Git;
use Composer\Test\Mock\ProcessExecutorMock;
use Composer\Test\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;

class GitTest extends TestCase
{
    /** @var Git */
    private $git;
    /** @var IOInterface&\PHPUnit\Framework\MockObject\MockObject */
    private $io;
    /** @var Config&\PHPUnit\Framework\MockObject\MockObject */
    private $config;
    /** @var ProcessExecutorMock */
    private $process;
    /** @var Filesystem&\PHPUnit\Framework\MockObject\MockObject */
    private $fs;

    protected function setUp(): void
    {
        $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
        $this->config = $this->getMockBuilder('Composer\Config')->disableOriginalConstructor()->getMock();
        $this->process = $this->getProcessExecutorMock();
        $this->fs = $this->getMockBuilder('Composer\Util\Filesystem')->disableOriginalConstructor()->getMock();
        $this->git = new Git($this->io, $this->config, $this->process, $this->fs);
    }

    #[DataProvider('publicGithubNoCredentialsProvider')]
    public function testRunCommandPublicGitHubRepositoryNotInitialClone(string $protocol, string $expectedUrl): void
    {
        $commandCallable = static function ($url) use ($expectedUrl): string {
            self::assertSame($expectedUrl, $url);

            return 'git command';
        };

        $this->mockConfig($protocol);

        $this->process->expects(['git command'], true);

        // @phpstan-ignore method.deprecated
        $this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true);
    }

    public static function publicGithubNoCredentialsProvider(): array
    {
        return [
            ['ssh', 'git@github.com:acme/repo'],
            ['https', 'https://github.com/acme/repo'],
        ];
    }

    public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithoutAuthentication(): void
    {
        self::expectException('RuntimeException');

        $commandCallable = static function ($url): string {
            self::assertSame('https://github.com/acme/repo', $url);

            return 'git command';
        };

        $this->mockConfig('https');

        $this->process->expects([
            ['cmd' => 'git command', 'return' => 1],
            ['cmd' => ['git', '--version'], 'return' => 0],
        ], true);

        // @phpstan-ignore method.deprecated
        $this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true);
    }

    #[DataProvider('privateGithubWithCredentialsProvider')]
    public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithAuthentication(string $gitUrl, string $protocol, string $gitHubToken, string $expectedUrl, int $expectedFailuresBeforeSuccess): void
    {
        $commandCallable = static function ($url) use ($expectedUrl): string {
            if ($url !== $expectedUrl) {
                return 'git command failing';
            }

            return 'git command ok';
        };

        $this->mockConfig($protocol);

        $expectedCalls = array_fill(0, $expectedFailuresBeforeSuccess, ['cmd' => 'git command failing', 'return' => 1]);
        $expectedCalls[] = ['cmd' => 'git command ok', 'return' => 0];

        $this->process->expects($expectedCalls, true);

        $this->io
            ->method('isInteractive')
            ->willReturn(false);

        $this->io
            ->expects($this->atLeastOnce())
            ->method('hasAuthentication')
            ->with($this->equalTo('github.com'))
            ->willReturn(true);

        $this->io
            ->expects($this->atLeastOnce())
            ->method('getAuthentication')
            ->with($this->equalTo('github.com'))
            ->willReturn(['username' => 'token', 'password' => $gitHubToken]);

        // @phpstan-ignore method.deprecated
        $this->git->runCommand($commandCallable, $gitUrl, null, true);
    }

    #[DataProvider('privateBitbucketWithCredentialsProvider')]
    public function testRunCommandPrivateBitbucketRepositoryNotInitialCloneNotInteractiveWithAuthentication(string $gitUrl, ?string $bitbucketToken, string $expectedUrl, int $expectedFailuresBeforeSuccess, int $bitbucket_git_auth_calls = 0): void
    {
        $commandCallable = static function ($url) use ($expectedUrl): string {
            if ($url !== $expectedUrl) {
                return 'git command failing';
            }

            return 'git command ok';
        };

        $this->config
            ->method('get')
            ->willReturnMap([
                ['gitlab-domains', 0, ['gitlab.com']],
                ['github-domains', 0, ['github.com']],
            ]);

        $expectedCalls = array_fill(0, $expectedFailuresBeforeSuccess, ['cmd' => 'git command failing', 'return' => 1]);
        if ($bitbucket_git_auth_calls > 0) {
            // When we are testing what happens without auth saved, and URLs
            // with https, there will also be an attempt to find the token in
            // the git config for the folder and repo, locally.
            $additional_calls = array_fill(0, $bitbucket_git_auth_calls, ['cmd' => ['git', 'config', 'bitbucket.accesstoken'], 'return' => 1]);
            foreach ($additional_calls as $call) {
                $expectedCalls[] = $call;
            }
        }
        $expectedCalls[] = ['cmd' => 'git command ok', 'return' => 0];

        $this->process->expects($expectedCalls, true);

        $this->io
            ->method('isInteractive')
            ->willReturn(false);

        if (null !== $bitbucketToken) {
            $this->io
                ->expects($this->atLeastOnce())
                ->method('hasAuthentication')
                ->with($this->equalTo('bitbucket.org'))
                ->willReturn(true);
            $this->io
                ->expects($this->atLeastOnce())
                ->method('getAuthentication')
                ->with($this->equalTo('bitbucket.org'))
                ->willReturn(['username' => 'token', 'password' => $bitbucketToken]);
        }
        // @phpstan-ignore method.deprecated
        $this->git->runCommand($commandCallable, $gitUrl, null, true);
    }

    /**
     * @dataProvider privateBitbucketWithOauthProvider
     *
     * @param string $gitUrl
     * @param string $expectedUrl
     * @param array{'username': string, 'password': string}[] $initial_config
     */
    #[DataProvider('privateBitbucketWithOauthProvider')]
    public function testRunCommandPrivateBitbucketRepositoryNotInitialCloneInteractiveWithOauth(string $gitUrl, string $expectedUrl, array $initial_config = []): void
    {
        $commandCallable = static function ($url) use ($expectedUrl): string {
            if ($url !== $expectedUrl) {
                return 'git command failing';
            }

            return 'git command ok';
        };

        $expectedCalls = [];
        $expectedCalls[] = ['cmd' => 'git command failing', 'return' => 1];
        if (count($initial_config) > 0) {
            $expectedCalls[] = ['cmd' => 'git command failing', 'return' => 1];
        } else {
            $expectedCalls[] = ['cmd' => ['git', 'config', 'bitbucket.accesstoken'], 'return' => 1];
        }
        $expectedCalls[] = ['cmd' => 'git command ok', 'return' => 0];
        $this->process->expects($expectedCalls, true);

        $this->config
            ->method('get')
            ->willReturnMap([
                ['gitlab-domains', 0, ['gitlab.com']],
                ['github-domains', 0, ['github.com']],
            ]);

        $this->io
            ->method('isInteractive')
            ->willReturn(true);

        $this->io
            ->method('askConfirmation')
            ->willReturnCallback(static function () {
                return true;
            });
        $this->io->method('askAndHideAnswer')
            ->willReturnCallback(static function ($question) {
                switch ($question) {
                    case 'Consumer Key (hidden): ':
                        return 'my-consumer-key';
                    case 'Consumer Secret (hidden): ':
                        return 'my-consumer-secret';
                }

                return '';
            });

        $this->io
            ->method('hasAuthentication')
            ->with($this->equalTo('bitbucket.org'))
            ->willReturnCallback(static function ($repositoryName) use (&$initial_config) {
                return isset($initial_config[$repositoryName]);
            });
        $this->io
            ->method('setAuthentication')
            ->willReturnCallback(static function (string $repositoryName, string $username, ?string $password = null) use (&$initial_config) {
                $initial_config[$repositoryName] = ['username' => $username, 'password' => $password];
            });
        $this->io
            ->method('getAuthentication')
            ->willReturnCallback(static function (string $repositoryName) use (&$initial_config) {
                if (isset($initial_config[$repositoryName])) {
                    return $initial_config[$repositoryName];
                }

                return ['username' => null, 'password' => null];
            });
        $downloader_mock = $this->getHttpDownloaderMock();
        $downloader_mock->expects([
            ['url' => 'https://bitbucket.org/site/oauth2/access_token', 'status' => 200, 'body' => '{"expires_in": 600, "access_token": "my-access-token"}'],
        ]);
        $this->git->setHttpDownloader($downloader_mock);
        // @phpstan-ignore method.deprecated
        $this->git->runCommand($commandCallable, $gitUrl, null, true);
    }

    public static function privateBitbucketWithOauthProvider(): array
    {
        return [
            ['git@bitbucket.org:acme/repo.git', 'https://x-token-auth:my-access-token@bitbucket.org/acme/repo.git'],
            ['https://bitbucket.org/acme/repo.git', 'https://x-token-auth:my-access-token@bitbucket.org/acme/repo.git'],
            ['https://bitbucket.org/acme/repo', 'https://x-token-auth:my-access-token@bitbucket.org/acme/repo.git'],
            ['git@bitbucket.org:acme/repo.git', 'https://x-token-auth:my-access-token@bitbucket.org/acme/repo.git', ['bitbucket.org' => ['username' => 'someuseralsoswappedfortoken', 'password' => 'little green men']]],
        ];
    }

    public static function privateBitbucketWithCredentialsProvider(): array
    {
        return [
            ['git@bitbucket.org:acme/repo.git', 'MY_BITBUCKET_TOKEN', 'https://token:MY_BITBUCKET_TOKEN@bitbucket.org/acme/repo.git', 1],
            ['https://bitbucket.org/acme/repo', 'MY_BITBUCKET_TOKEN', 'https://token:MY_BITBUCKET_TOKEN@bitbucket.org/acme/repo.git', 1],
            ['https://bitbucket.org/acme/repo.git', 'MY_BITBUCKET_TOKEN', 'https://token:MY_BITBUCKET_TOKEN@bitbucket.org/acme/repo.git', 1],
            ['git@bitbucket.org:acme/repo.git', null, 'git@bitbucket.org:acme/repo.git', 0],
            ['https://bitbucket.org/acme/repo', null, 'git@bitbucket.org:acme/repo.git', 1, 1],
            ['https://bitbucket.org/acme/repo.git', null, 'git@bitbucket.org:acme/repo.git', 1, 1],
            ['https://bitbucket.org/acme/repo.git', 'ATAT_BITBUCKET_API_TOKEN', 'https://x-bitbucket-api-token-auth:ATAT_BITBUCKET_API_TOKEN@bitbucket.org/acme/repo.git', 1],
        ];
    }

    public static function privateGithubWithCredentialsProvider(): array
    {
        return [
            ['git@github.com:acme/repo.git', 'ssh', 'MY_GITHUB_TOKEN', 'https://token:MY_GITHUB_TOKEN@github.com/acme/repo.git', 1],
            ['https://github.com/acme/repo', 'https', 'MY_GITHUB_TOKEN', 'https://token:MY_GITHUB_TOKEN@github.com/acme/repo.git', 2],
        ];
    }

    private function mockConfig(string $protocol): void
    {
        $this->config
            ->method('get')
            ->willReturnMap([
                ['github-domains', 0, ['github.com']],
                ['github-protocols', 0, [$protocol]],
            ]);
    }
}