File: HttpDownloaderMock.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 (139 lines) | stat: -rw-r--r-- 5,597 bytes parent folder | download | duplicates (2)
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
<?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\Mock;

use Composer\Config;
use Composer\IO\BufferIO;
use Composer\IO\IOInterface;
use Composer\Util\HttpDownloader;
use Composer\Util\Http\Response;
use Composer\Downloader\TransportException;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\AssertionFailedError;

class HttpDownloaderMock extends HttpDownloader
{
    /**
     * @var array<array{url: non-empty-string, options: array<mixed>|null, status: int, body: string, headers: list<string>}>|null
     */
    private $expectations = null;
    /**
     * @var bool
     */
    private $strict = false;
    /**
     * @var array{status: int, body: string, headers: list<string>}
     */
    private $defaultHandler = ['status' => 200, 'body' => '', 'headers' => []];
    /**
     * @var string[]
     */
    private $log = [];

    public function __construct(?IOInterface $io = null, ?Config $config = null)
    {
        if ($io === null) {
            $io = new BufferIO();
        }
        if ($config === null) {
            $config = new Config(false);
        }
        parent::__construct($io, $config);
    }

    /**
     * @param array<array{url: non-empty-string, options?: array<mixed>, status?: int, body?: string, headers?: list<string>}> $expectations
     * @param bool                                                                                                    $strict         set to true if you want to provide *all* expected http requests, and not just a subset you are interested in testing
     * @param array{status?: int, body?: string, headers?: list<string>}                                             $defaultHandler default URL handler for undefined requests if not in strict mode
     */
    public function expects(array $expectations, bool $strict = false, array $defaultHandler = ['status' => 200, 'body' => '', 'headers' => []]): void
    {
        $default = ['url' => '', 'options' => null, 'status' => 200, 'body' => '', 'headers' => ['']];
        $this->expectations = array_map(static function (array $expect) use ($default): array {
            if (count($diff = array_diff_key(array_merge($default, $expect), $default)) > 0) {
                throw new \UnexpectedValueException('Unexpected keys in process execution step: '.implode(', ', array_keys($diff)));
            }

            return array_merge($default, $expect);
        }, $expectations);
        $this->strict = $strict;

        $this->defaultHandler = array_merge($this->defaultHandler, $defaultHandler);
    }

    public function assertComplete(): void
    {
        // this was not configured to expect anything, so no need to react here
        if (!is_array($this->expectations)) {
            return;
        }

        if (count($this->expectations) > 0) {
            $expectations = array_map(static function ($expect): string {
                return $expect['url'];
            }, $this->expectations);
            throw new AssertionFailedError(
                'There are still '.count($this->expectations).' expected HTTP requests which have not been consumed:'.PHP_EOL.
                implode(PHP_EOL, $expectations).PHP_EOL.PHP_EOL.
                'Received calls:'.PHP_EOL.implode(PHP_EOL, $this->log)
            );
        }

        // dummy assertion to ensure the test is not marked as having no assertions
        Assert::assertTrue(true); // @phpstan-ignore staticMethod.alreadyNarrowedType
    }

    public function get($fileUrl, $options = []): Response
    {
        if ('' === $fileUrl) {
            throw new \LogicException('url cannot be an empty string');
        }

        $this->log[] = $fileUrl;

        if (is_array($this->expectations) && count($this->expectations) > 0 && $fileUrl === $this->expectations[0]['url'] && ($this->expectations[0]['options'] === null || $options === $this->expectations[0]['options'])) {
            $expect = array_shift($this->expectations);

            return $this->respond($fileUrl, $expect['status'], $expect['headers'], $expect['body']);
        }

        if (!$this->strict) {
            return $this->respond($fileUrl, $this->defaultHandler['status'], $this->defaultHandler['headers'], $this->defaultHandler['body']);
        }

        throw new AssertionFailedError(
            'Received unexpected request for "'.$fileUrl.'" with options "'.json_encode($options).'"'.PHP_EOL.
            (is_array($this->expectations) && count($this->expectations) > 0
                ? 'Expected "'.$this->expectations[0]['url'].($this->expectations[0]['options'] !== null ? '" with options "'.json_encode($this->expectations[0]['options']) : '').'" at this point.'
                : 'Expected no more calls at this point.').PHP_EOL.
            'Received calls:'.PHP_EOL.implode(PHP_EOL, array_slice($this->log, 0, -1))
        );
    }

    /**
     * @param list<string> $headers
     * @param non-empty-string $url
     */
    private function respond(string $url, int $status, array $headers, string $body): Response
    {
        if ($status < 400) {
            return new Response(['url' => $url], $status, $headers, $body);
        }

        $e = new TransportException('The "'.$url.'" file could not be downloaded', $status);
        $e->setHeaders($headers);
        $e->setResponse($body);

        throw $e;
    }
}