Passed
Push — develop ( 39bf77...a3afc7 )
by nguereza
01:40
created

PlatineTestCase::assertCommandOutput()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Platine Dev Tools
5
 *
6
 * Platine Dev Tools is a collection of some classes/functions
7
 * designed for development
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Dev Tools
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file PlatineTestCase.php
34
 *
35
 *  The Base class used for test case
36
 *
37
 *  @package    Platine\Dev
38
 *  @author Platine Developers Team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   https://www.platine-php.com
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Dev;
49
50
use InvalidArgumentException;
51
use org\bovigo\vfs\vfsStream;
52
use org\bovigo\vfs\vfsStreamContainer;
53
use org\bovigo\vfs\vfsStreamDirectory;
54
use org\bovigo\vfs\vfsStreamFile;
55
use PHPUnit\Framework\TestCase;
56
use ReflectionClass;
57
use ReflectionProperty;
58
59
/**
60
 * @class PlatineTestCase
61
 * @package Platine\Dev
62
 */
63
class PlatineTestCase extends TestCase
64
{
65
    /**
66
     * @codeCoverageIgnore
67
     * @return void
68
     */
69
    protected function tearDown(): void
70
    {
71
        //restore all mock variable global value to "false"
72
        foreach ($GLOBALS as $key => $value) {
73
            if (substr((string) $key, 0, 5) === 'mock_') {
74
                $GLOBALS[$key] = false;
75
            }
76
        }
77
    }
78
79
    /**
80
     * Method to test private & protected method
81
     *
82
     * @param object $object the class instance to use
83
     * @param string $method the name of the method
84
     * @param array<int, mixed> $args the list of method arguments
85
     * @return mixed
86
     */
87
    public function runPrivateProtectedMethod(
88
        object $object,
89
        string $method,
90
        array $args = []
91
    ) {
92
        $reflection = new ReflectionClass(get_class($object));
93
        $reflectionMethod = $reflection->getMethod($method);
94
        $reflectionMethod->setAccessible(true);
95
        return $reflectionMethod->invokeArgs($object, $args);
96
    }
97
98
    /**
99
     * Method to set/get private & protected attribute
100
     *
101
     * @param string $className the name of the class
102
     * @param string $attr the name of the class attribute
103
     */
104
    public function getPrivateProtectedAttribute(
105
        string $className,
106
        string $attr
107
    ): ReflectionProperty {
108
        $rProp = new ReflectionProperty($className, $attr);
109
        $rProp->setAccessible(true);
110
        return $rProp;
111
    }
112
113
    /**
114
     * Create virtual file with the given content
115
     * @param  string $filename
116
     * @param  vfsStreamContainer<vfsStreamContainerIterator> $destination
117
     * @param  string $content
118
     * @return vfsStreamFile
119
     */
120
    public function createVfsFile(
121
        string $filename,
122
        vfsStreamContainer $destination,
123
        string $content = ''
124
    ): vfsStreamFile {
125
        return vfsStream::newFile($filename)
126
                        ->at($destination)
127
                        ->setContent($content);
128
    }
129
130
    /**
131
     * Create virtual file without content
132
     * @param  string $filename
133
     * @param  vfsStreamContainer<vfsStreamContainerIterator> $destination
134
     * @return vfsStreamFile
135
     */
136
    public function createVfsFileOnly(
137
        string $filename,
138
        vfsStreamContainer $destination
139
    ): vfsStreamFile {
140
        return vfsStream::newFile($filename)
141
                        ->at($destination);
142
    }
143
144
    /**
145
     * Create virtual directory
146
     * @param  string $name
147
     * @param  vfsStreamContainer<vfsStreamContainerIterator> $destination
148
     * @return vfsStreamDirectory
149
     */
150
    public function createVfsDirectory(
151
        string $name,
152
        vfsStreamContainer $destination = null
153
    ): vfsStreamDirectory {
154
        if ($destination) {
155
            return vfsStream::newDirectory($name)->at($destination);
156
        }
157
        return vfsStream::newDirectory($name);
158
    }
159
160
    /**
161
     * Return the list of methods to mocks in the parameters of PHPUnit::TestCase::getMock()
162
     *
163
     * @param class-string<object>|object $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<object>|object at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<object>|object.
Loading history...
164
     * @param string[] $exclude list of methods to exclude
165
     * @return string[]
166
     */
167
    public function getClassMethodsToMock($class, array $exclude = []): array
168
    {
169
        $methods = [];
170
171
        if (is_string($class) && !class_exists($class)) {
172
            throw new InvalidArgumentException(
173
                sprintf('Can not find class [%s]', $class)
174
            );
175
        }
176
177
        $reflectionClass = new ReflectionClass($class);
178
179
        foreach ($reflectionClass->getMethods() as $reflectionMethod) {
180
            if (!in_array($reflectionMethod->name, $exclude)) {
181
                $methods[] = $reflectionMethod->name;
182
            }
183
        }
184
185
        return $methods;
186
    }
187
188
    /**
189
     * Get the instance of the given class
190
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
191
     * @param array<string, mixed> $mockMethods
192
     * @param array<int, string> $excludes
193
     * @return mixed
194
     */
195
    public function getMockInstance(
196
        string $class,
197
        array $mockMethods = [],
198
        array $excludes = []
199
    ) {
200
        $methods = $this->getClassMethodsToMock($class, $excludes);
201
202
        $mock = $this->getMockBuilder($class)
203
                    ->disableOriginalConstructor()
204
                    ->onlyMethods($methods)
205
                    ->getMock();
206
207
        foreach ($mockMethods as $method => $returnValue) {
208
            $mock->expects($this->any())
209
                ->method($method)
210
                ->will($this->returnValue($returnValue));
211
        }
212
213
        return $mock;
214
    }
215
216
    /**
217
     * Get the instance of the given class using return map
218
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
219
     * @param array<string, mixed> $mockMethods
220
     * @param array<int, string> $excludes
221
     * @return mixed
222
     */
223
    public function getMockInstanceMap(
224
        string $class,
225
        array $mockMethods = [],
226
        array $excludes = []
227
    ) {
228
        $methods = $this->getClassMethodsToMock($class, $excludes);
229
230
        $mock = $this->getMockBuilder($class)
231
                    ->disableOriginalConstructor()
232
                    ->onlyMethods($methods)
233
                    ->getMock();
234
235
        foreach ($mockMethods as $method => $returnValues) {
236
            $mock->expects($this->any())
237
                ->method($method)
238
                ->will(
239
                    $this->returnValueMap($returnValues)
240
                );
241
        }
242
243
        return $mock;
244
    }
245
246
    /**
247
     * Return the value of private or protected property
248
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
249
     * @param object $instance
250
     * @param string $name
251
     * @return mixed
252
     */
253
    public function getPropertyValue(string $class, object $instance, string $name)
254
    {
255
        $reflection = $this->getPrivateProtectedAttribute($class, $name);
256
        return $reflection->getValue($instance);
257
    }
258
259
    /**
260
     * Set the value of private or protected property
261
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
262
     * @param object $instance
263
     * @param string $name
264
     * @param mixed $value
265
     * @return void
266
     */
267
    public function setPropertyValue(string $class, object $instance, string $name, $value)
268
    {
269
        $reflection = $this->getPrivateProtectedAttribute($class, $name);
270
        $reflection->setValue($instance, $value);
271
    }
272
273
    /**
274
     * Test assert command expected given output
275
     * @param string $expected
276
     * @param string $output
277
     * @return void
278
     */
279
    public function assertCommandOutput(string $expected, string $output): void
280
    {
281
        $result = str_replace("\n", PHP_EOL, $expected);
282
        $this->assertEquals($result, $output);
283
    }
284
}
285