forked from googleapis/google-cloud-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestHelpers.php
299 lines (262 loc) · 8.54 KB
/
TestHelpers.php
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
<?php
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Core\Testing;
use Google\Cloud\Core\Testing\RegexFileFilter;
use Google\Cloud\Core\Testing\Snippet\Container;
use Google\Cloud\Core\Testing\Snippet\Coverage\Coverage;
use Google\Cloud\Core\Testing\Snippet\Coverage\Scanner;
use Google\Cloud\Core\Testing\Snippet\Parser\Parser;
use Google\Cloud\Core\Testing\System\SystemTestCase;
use PHPUnit\Framework\Assert;
/**
* Class TestHelpers is used to hold static functions required for testing
*
* @experimental
* @internal
*/
class TestHelpers
{
/**
* Create a test stub which extends a real class and allows overriding of private properties.
*
* @param string $extends The fully-qualified name of the class to extend.
* @param array $args An array of constructor arguments to use when creating the stub.
* @param array $props A list of private properties on which to enable overrriding.
* @return mixed
*
* @experimental
* @internal
*/
public static function stub($extends, array $args = [], array $props = [])
{
if (empty($props)) {
$props = ['connection'];
}
$tpl = 'class %s extends %s {private $___props = \'%s\'; use \Google\Cloud\Core\Testing\StubTrait; }';
$props = json_encode($props);
$name = 'Stub' . sha1($extends . $props);
if (!class_exists($name)) {
eval(sprintf($tpl, $name, $extends, $props));
}
$reflection = new \ReflectionClass($name);
return $reflection->newInstanceArgs(array_values($args));
}
/**
* Get a trait implementation.
*
* @param string $trait The fully-qualified name of the trait to implement.
* @return mixed
*
* @experimental
* @internal
*/
public static function impl($trait, array $props = [])
{
$properties = [];
foreach ($props as $prop) {
$properties[] = 'private $' . $prop . ';';
}
$tpl = 'class %s {
use %s;
use \Google\Cloud\Core\Testing\StubTrait;
private $___props = \'%s\';
%s
public function call($fn, array $args = []) { return call_user_func_array([$this, $fn], $args); }
}';
$name = 'Trait' . sha1($trait . json_encode($props));
if (!class_exists($name)) {
eval(sprintf($tpl, $name, $trait, json_encode($props), implode("\n", $properties)));
}
return new $name;
}
/**
* Setup snippet tests support.
*
* @return void
* @experimental
* @internal
*/
public static function snippetBootstrap()
{
putenv('GOOGLE_APPLICATION_CREDENTIALS='. \Google\Cloud\Core\Testing\Snippet\Fixtures::KEYFILE_STUB_FIXTURE());
$parser = new Parser;
$scanner = new Scanner($parser, self::projectRoot(), [
'/vendor/',
'/dev/',
new RegexFileFilter('/\w{0,}\/vendor\//'),
new RegexFileFilter('/\w{0,}\/V\d{1,}\w{0,}\//')
]);
$coverage = new Coverage($scanner);
$coverage->buildListToCover();
Container::$coverage = $coverage;
Container::$parser = $parser;
}
/**
* Setup performance tests support.
*
* @return void
* @experimental
* @internal
*/
public static function perfBootstrap()
{
$bootstraps = glob(self::projectRoot() .'/*tests/Perf/bootstrap.php');
foreach ($bootstraps as $bootstrap) {
require_once $bootstrap;
}
}
/**
* Check that the required environment variable keyfile paths are set and exist.
*
* @param array|string $env The environment variable(s) required.
* @throws \RuntimeException
* @experimental
* @internal
*/
public static function requireKeyfile($env)
{
$env = is_array($env) ? $env : [$env];
foreach ($env as $var) {
if (!getenv($var)) {
throw new \RuntimeException(sprintf(
'Please set the \'%s\' env var to run the tests',
$var
));
}
$path = getenv($var);
if (!file_exists($path)) {
throw new \RuntimeException(sprintf(
'The path \`%s\` specified in environment variable `%s` does not exist.',
$path,
$var
));
}
}
}
/**
* Setup stuff needed for the system test runner.
*
* This method can only be called once per run. Subsequent calls will thrown \RuntimeException.
*
* @internal
* @experimental
*/
public static function systemBootstrap()
{
static $started = false;
if ($started) {
throw new \RuntimeException('system tests cannot be bootstrapped more than once.');
}
SystemTestCase::setupQueue();
$bootstraps = glob(self::projectRoot() .'/*tests/System/bootstrap.php');
foreach ($bootstraps as $bootstrap) {
require_once $bootstrap;
}
// This should always be last.
self::systemTestShutdown(function () {
SystemTestCase::processQueue();
});
$started = true;
}
/**
* Setup stuff needed for the generated system tests.
* @internal
* @experimental
*/
public static function generatedSystemTestBootstrap()
{
// For generated system tests, we need to set GOOGLE_APPLICATION_CREDENTIALS
// and PROJECT_ID to appropriate values
$keyFilePath = getenv('GOOGLE_CLOUD_PHP_TESTS_KEY_PATH');
putenv("GOOGLE_APPLICATION_CREDENTIALS=$keyFilePath");
$keyFileData = json_decode(file_get_contents($keyFilePath), true);
putenv('PROJECT_ID=' . $keyFileData['project_id']);
}
/**
* Add cleanup function for system tests.
*
* Calls to this method enqueue a PHP shutdown function, scoped to the parent
* PID.
*
* @param callable $shutdown The shutdown function.
* @return void
* @experimental
* @internal
*/
public static function systemTestShutdown(callable $shutdown)
{
$pid = getmypid();
register_shutdown_function(function () use ($pid, $shutdown) {
// Skip flushing deletion queue if exiting a forked process.
if ($pid !== getmypid()) {
return;
}
$shutdown();
});
}
/**
* Get the value of a private property.
*
* @param mixed $class The class
* @param string $property The property name.
* @return mixed
*/
public static function getPrivateProperty($class, $property)
{
$className = get_class($class);
$c = \Closure::bind(function ($class) use ($property) {
return $class->$property;
}, null, $className);
return $c($class);
}
/**
* Compare actual and expected results when the requirement for comparision
* is `===` including outlier cases like:
* - Comparing NAN
* - Comparing floating point values with some delta
*/
public static function compareResult($expected, $actual)
{
if (is_float($expected)) {
if (is_nan($expected)) {
Assert::assertNan($actual);
} else {
Assert::assertEqualsWithDelta($expected, $actual, 0.01);
}
} else {
// Used because assertEquals(null, '') doesn't fails
Assert::assertSame($expected, $actual);
}
}
/**
* Determine the path of the project root based on where the composer
* autoloader is located.
*
* @return string
* @experimental
* @internal
*/
private static function projectRoot()
{
static $projectRoot;
if (!$projectRoot) {
$ref = new \ReflectionClass(\Composer\Autoload\ClassLoader::class);
$projectRoot = dirname(dirname(dirname($ref->getFileName())));
}
return $projectRoot;
}
}