• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

10up / wp_mock / 5642460430

pending completion
5642460430

push

github

web-flow
Restore CREDITS.md (#230)

492 of 751 relevant lines covered (65.51%)

2.58 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.0
/php/WP_Mock.php
1
<?php
2

3
/**
4
 * @package WP_Mock
5
 * @copyright 2013-2023 by the contributors
6
 * @license BSD-3-Clause
7
 * @see ../LICENSE.md
8
 */
9

10
use Mockery\Exception as MockeryException;
11
use WP_Mock\DeprecatedMethodListener;
12
use WP_Mock\Functions\Handler;
13
use WP_Mock\Matcher\FuzzyObject;
14
use Mockery\Matcher\Type;
15

16
/**
17
 * WP_Mock main class.
18
 */
19
class WP_Mock
20
{
21
    /**
22
     * @var \WP_Mock\EventManager
23
     */
24
    protected static $event_manager;
25

26
    /** @var WP_Mock\Functions */
27
    protected static $functionsManager;
28

29
    protected static $__bootstrapped = false;
30

31
    protected static $__use_patchwork = false;
32

33
    protected static $__strict_mode = false;
34

35
    /** @var DeprecatedMethodListener */
36
    protected static $deprecatedMethodListener;
37

38
    /**
39
     * @param boolean $use_patchwork
40
     */
41
    public static function setUsePatchwork($use_patchwork)
42
    {
43
        if (! self::$__bootstrapped) {
×
44
            self::$__use_patchwork = (bool) $use_patchwork;
×
45
        }
46
    }
47

48
    public static function usingPatchwork()
49
    {
50
        return (bool) self::$__use_patchwork;
12✔
51
    }
52

53
    /**
54
     * Check whether strict mode is turned on
55
     *
56
     * @return bool
57
     */
58
    public static function strictMode()
59
    {
60
        return (bool) self::$__strict_mode;
22✔
61
    }
62

63
    /**
64
     * Turns on strict mode
65
     */
66
    public static function activateStrictMode()
67
    {
68
        if (! self::$__bootstrapped) {
3✔
69
            self::$__strict_mode = true;
2✔
70
        }
71
    }
72

73
    /**
74
     * Bootstraps WP_Mock.
75
     *
76
     * @return void
77
     */
78
    public static function bootstrap(): void
79
    {
80
        if (! self::$__bootstrapped) {
14✔
81
            self::$__bootstrapped = true;
12✔
82

83
            static::$deprecatedMethodListener = new DeprecatedMethodListener();
12✔
84

85
            require_once __DIR__ . '/WP_Mock/API/function-mocks.php';
12✔
86
            require_once __DIR__ . '/WP_Mock/API/constant-mocks.php';
12✔
87

88
            if (self::usingPatchwork()) {
12✔
89
                $patchwork_path  = 'antecedent/patchwork/Patchwork.php';
×
90
                $possible_locations = [
×
91
                    'vendor',
×
92
                    '../..',
×
93
                ];
×
94

95
                foreach ($possible_locations as $loc) {
×
96
                    $path = __DIR__ . "/../$loc/$patchwork_path";
×
97

98
                    if (file_exists($path)) {
×
99
                        break;
×
100
                    }
101
                }
102

103
                // Will cause a fatal error if patchwork can't be found
104
                require_once($path);
×
105
            }
106

107
            self::setUp();
12✔
108
        }
109
    }
110

111
    /**
112
     * Make sure Mockery doesn't have anything set up already.
113
     */
114
    public static function setUp(): void
115
    {
116
        if (self::$__bootstrapped) {
37✔
117
            \Mockery::close();
37✔
118

119
            self::$event_manager    = new \WP_Mock\EventManager();
37✔
120
            self::$functionsManager = new \WP_Mock\Functions();
37✔
121
        } else {
122
            self::bootstrap();
×
123
        }
124
    }
125

126
    /**
127
     * Tear down anything built up inside Mockery when we're ready to do so.
128
     */
129
    public static function tearDown(): void
130
    {
131
        self::$event_manager->flush();
×
132
        self::$functionsManager->flush();
×
133

134
        Mockery::close();
×
135
        Handler::cleanup();
×
136
    }
137

138
    /**
139
     * Fire a specific (mocked) callback when an apply_filters() call is used.
140
     *
141
     * @param string $filter
142
     *
143
     * @return \WP_Mock\Filter
144
     */
145
    public static function onFilter($filter)
146
    {
147
        self::$event_manager->called($filter, 'filter');
2✔
148
        return self::$event_manager->filter($filter);
2✔
149
    }
150

151
    /**
152
     * Fire a specific (mocked) callback when a do_action() call is used.
153
     *
154
     * @param string $action
155
     *
156
     * @return \WP_Mock\Action
157
     */
158
    public static function onAction($action)
159
    {
160
        return self::$event_manager->action($action);
2✔
161
    }
162

163
    /**
164
     * Get a filter or action added callback object
165
     *
166
     * @param string $hook
167
     * @param string $type
168
     *
169
     * @return \WP_Mock\HookedCallback
170
     */
171
    public static function onHookAdded($hook, $type = 'filter')
172
    {
173
        return self::$event_manager->callback($hook, $type);
2✔
174
    }
175

176
    /**
177
     * Get a filter added callback object
178
     *
179
     * @param string $hook
180
     *
181
     * @return \WP_Mock\HookedCallback
182
     */
183
    public static function onFilterAdded($hook)
184
    {
185
        return self::onHookAdded($hook, 'filter');
1✔
186
    }
187

188
    /**
189
     * Get an action added callback object
190
     *
191
     * @param string $hook
192
     *
193
     * @return \WP_Mock\HookedCallback
194
     */
195
    public static function onActionAdded($hook)
196
    {
197
        return self::onHookAdded($hook, 'action');
1✔
198
    }
199

200
    /**
201
     * Alert the Event Manager that an action has been invoked.
202
     *
203
     * @param string $action
204
     */
205
    public static function invokeAction($action)
206
    {
207
        self::$event_manager->called($action);
1✔
208
    }
209

210
    public static function addFilter($hook)
211
    {
212
        self::addHook($hook, 'filter');
×
213
    }
214

215
    public static function addAction($hook)
216
    {
217
        self::addHook($hook, 'action');
×
218
    }
219

220
    public static function addHook($hook, $type = 'filter')
221
    {
222
        $type_name = "$type::$hook";
1✔
223
        self::$event_manager->called($type_name, 'callback');
1✔
224
    }
225

226
    /**
227
     * Set up the expectation that an action will be called during the test.
228
     *
229
     * Mock a WordPress action, regardless of the parameters used.  This call merely
230
     * verifies that the action is invoked by the tested method.
231
     *
232
     * @param string $action Action we expect the method to call
233
     */
234
    public static function expectAction($action)
235
    {
236
        $intercept = \Mockery::mock('intercept');
2✔
237
        $intercept->shouldReceive('intercepted')->atLeast()->once();
2✔
238
        $args = func_get_args();
2✔
239
        $args = count($args) > 1 ? array_slice($args, 1) : array( null );
2✔
240

241
        $mocked_action = self::onAction($action);
2✔
242
        $responder     = call_user_func_array(array( $mocked_action, 'with' ), $args);
2✔
243
        $responder->perform(array( $intercept, 'intercepted' ));
2✔
244
    }
245

246
    /**
247
     * Set up the expectation that a filter will be applied during the test.
248
     *
249
     * Mock a WordPress filter with specific arguments. You need all arguments that you expect
250
     * in order to fulfill the expectation.
251
     *
252
     * @param string $filter
253
     */
254
    public static function expectFilter($filter)
255
    {
256
        $intercept = \Mockery::mock('intercept');
2✔
257
        $intercept->shouldReceive('intercepted')->atLeast()->once()->andReturnUsing(function ($value) {
2✔
258
            return $value;
1✔
259
        });
2✔
260
        $args = func_num_args() > 1 ? array_slice(func_get_args(), 1) : array( null );
2✔
261

262
        $mocked_filter = self::onFilter($filter);
2✔
263
        $responder     = call_user_func_array(array( $mocked_filter, 'with' ), $args);
2✔
264
        $responder->reply(new \WP_Mock\InvokedFilterValue(array( $intercept, 'intercepted' )));
2✔
265
    }
266

267
    /**
268
     * Assert that all actions are called.
269
     */
270
    public static function assertActionsCalled()
271
    {
272
        $allActionsCalled = self::$event_manager->allActionsCalled();
2✔
273
        $failed = implode(', ', self::$event_manager->expectedActions());
2✔
274
        \PHPUnit\Framework\Assert::assertTrue($allActionsCalled, 'Method failed to invoke actions: ' . $failed);
2✔
275
    }
276

277
    /**
278
     * Assert that all filters are called.
279
     */
280
    public static function assertFiltersCalled()
281
    {
282
        $allFiltersCalled = self::$event_manager->allFiltersCalled();
1✔
283
        $failed           = implode(', ', self::$event_manager->expectedFilters());
1✔
284
        \PHPUnit\Framework\Assert::assertTrue($allFiltersCalled, 'Method failed to invoke filters: ' . $failed);
1✔
285
    }
286

287
    /**
288
     * Add an expectation that an action should be added
289
     *
290
     * Really just a wrapper function for expectHookAdded()
291
     *
292
     * @param string   $action   The action name
293
     * @param callable|Type $callback The callback that should be registered
294
     * @param int      $priority The priority it should be registered at
295
     * @param int      $args     The number of arguments that should be allowed
296
     */
297
    public static function expectActionAdded($action, $callback, $priority = 10, $args = 1)
298
    {
299
        self::expectHookAdded('action', $action, $callback, $priority, $args);
2✔
300
    }
301

302
    /**
303
     * Add an expection that an action should not be added. A wrapper
304
     * around the expectHookNotAdded function.
305
     *
306
     * @param string   $action   The action hook name
307
     * @param callable|Type $callback The action callback
308
     */
309
    public static function expectActionNotAdded($action, $callback)
310
    {
311
        self::expectHookNotAdded('action', $action, $callback);
×
312
    }
313

314
    /**
315
     * Add an expectation that a filter should be added
316
     *
317
     * Really just a wrapper function for expectHookAdded()
318
     *
319
     * @param string   $filter   The action name
320
     * @param callable|Type $callback The callback that should be registered
321
     * @param int      $priority The priority it should be registered at
322
     * @param int      $args     The number of arguments that should be allowed
323
     */
324
    public static function expectFilterAdded($filter, $callback, $priority = 10, $args = 1)
325
    {
326
        self::expectHookAdded('filter', $filter, $callback, $priority, $args);
2✔
327
    }
328

329
    /**
330
     * Adds an expectation that a filter will not be added. A wrapper
331
     * around the expectHookNotAdded function.
332
     *
333
     * @param string   $filter   The filter hook name
334
     * @param callable|Type $callback The filter callback
335
     */
336
    public static function expectFilterNotAdded($filter, $callback)
337
    {
338
        self::expectHookNotAdded('filter', $filter, $callback);
×
339
    }
340

341
    /**
342
     * Add an expectation that a hook should be added
343
     *
344
     * @param string   $type     The type of hook being added
345
     * @param string   $action   The action name
346
     * @param callable|Type $callback The callback that should be registered
347
     * @param int      $priority The priority it should be registered at
348
     * @param int      $args     The number of arguments that should be allowed
349
     */
350
    public static function expectHookAdded($type, $action, $callback, $priority = 10, $args = 1)
351
    {
352
        $intercept = \Mockery::mock('intercept');
2✔
353
        $intercept->shouldReceive('intercepted')->atLeast()->once();
2✔
354

355
        /** @var WP_Mock\HookedCallbackResponder $responder */
356
        $responder = self::onHookAdded($action, $type)
2✔
357
            ->with($callback, $priority, $args);
2✔
358
        $responder->perform(array( $intercept, 'intercepted' ));
2✔
359
    }
360

361
    /**
362
     * Adds an expectation that a hook should not be added. Based on the
363
     * shouldNotReceive API of Mocker.
364
     *
365
     * @param string   $type     The hook type, 'action' or 'filter'
366
     * @param string   $action   The name of the hook
367
     * @param callable|Type $callback The hooks callback handler.
368
     */
369
    public static function expectHookNotAdded($type, $action, $callback)
370
    {
371
        $intercept = \Mockery::mock('intercept');
×
372
        $intercept->shouldNotReceive('intercepted');
×
373

374
        /** @var WP_Mock\HookedCallbackResponder $responder */
375
        $responder = self::onHookAdded($action, $type)
×
376
            ->with($callback, 10, 1);
×
377
        $responder->perform(array( $intercept, 'intercepted' ));
×
378
    }
379

380
    /**
381
     * Assert that all hooks are added.
382
     */
383
    public static function assertHooksAdded()
384
    {
385
        $allHooksAdded = self::$event_manager->allHooksAdded();
2✔
386
        $failed = implode(', ', self::$event_manager->expectedHooks());
2✔
387
        PHPUnit\Framework\Assert::assertTrue($allHooksAdded, 'Method failed to add hooks: ' . $failed);
2✔
388
    }
389

390
    /**
391
     * Mocks a WordPress API function.
392
     *
393
     * This function registers a mock object for a WordPress function and, if necessary, dynamically defines the function.
394
     *
395
     * Pass the function name as the first argument (e.g. `wp_remote_get()`) and pass in details about the expectations in the $args param.
396
     * The arguments have a few options for defining expectations about how the WordPress function should be used during a test.
397
     *
398
     * Currently, it accepts the following settings:
399
     *
400
     * - `times`: Defines expectations for the number of times a function should be called. The default is `0` or more times.
401
     *            To expect the function to be called an exact amount of times, set times to a non-negative numeric value.
402
     *            To specify that the function should be called a minimum number of times, use a string with the minimum followed by '+' (e.g. '3+' means 3 or more times).
403
     *            Append a '-' to indicate a maximum number of times a function should be called (e.g. '3-' means no more than 3 times).
404
     *            To indicate a range, use '-' between two numbers (e.g. '2-5' means at least 2 times and no more than 5 times).
405
     *
406
     * - `return`: Defines the value (if any) that the function should return.
407
     *             If you pass a `Closure` as the return value, the function will return whatever the closure's return value.
408
     *
409
     * - `return_in_order`: Use this if your function will be called multiple times in the test but needs to have different return values.
410
     *                      Set this to an array of return values. Each time the function is called, it will return the next value in the sequence until it reaches the last value, which will become the return value for all subsequent calls.
411
     *                      For example, if you are mocking `is_single()`, you can set `return_in_order` to `[false, true]`. The first time is_single() is called it will return false.
412
     *                      The second and all subsequent times it will return true. Setting this value overrides return, so if you set both, return will be ignored.
413
     *
414
     * - `return_arg`: Use this to specify that the function should return one of its arguments. `return_arg` should be the position of the argument in the arguments array, so `0` for the first argument, `1` for the second, etc.
415
     *                 You can also set this to true, which is equivalent to `0`. This will override both return and return_in_order.
416
     *
417
     * - `args`: Use this to set expectations about what the arguments passed to the function should be.
418
     *           This value should always be an array with the arguments in order.
419
     *           Like with `return`, if you use a `Closure`, its return value will be used to validate the argument expectations.
420
     *           WP_Mock has several helper functions to make this feature more flexible. There are static methods on the \WP_Mock\Functions class. They are:
421
     *           - {@see Functions::type($type)} Expects an argument of a certain type. This can be any core PHP data type (string, int, resource, callable, etc.) or any class or interface name.
422
     *           - {@see Functions::anyOf($values)} Expects the argument to be any value in the `$values` array.
423
     *           In addition to these helper functions, you can indicate that the argument can be any value of any type by using `*`.
424
     *           So, for example, if you are expecting `get_post_meta()` to be called, the `args` array might look something like this: `[$post->ID, 'some_meta_key', true]`.
425
     *
426
     * Returns the {@see Mockery\Expectation} object with the function expectations added.
427
     * It is possible to use Mockery methods to add expectations to the object returned, which will then be combined with any expectations that may have been passed as arguments.
428
     *
429
     * @param string $function function name
430
     * @param mixed[] $args optional arguments to set expectations
431
     * @return Mockery\Expectation
432
     * @throws InvalidArgumentException
433
     */
434
    public static function userFunction(string $function, array $args = [])
435
    {
436
        return self::$functionsManager->register($function, $args);
8✔
437
    }
438

439
    /**
440
     * A wrapper for {@see WP_Mock::userFunction()} that will simply set/override the return to be a function that echoes the value that its passed.
441
     *
442
     * For example, `esc_attr_e()` may need to be mocked, and it must echo some value.
443
     * {@see WP_Mock::echoFunction()} will set `esc_attr_e()` to echo the value its passed:
444
     *
445
     *    WP_Mock::echoFunction('esc_attr_e');
446
     *    esc_attr_e('some_value'); // echoes "some_value"
447
     *
448
     * @param string $function function name
449
     * @param mixed[]|scalar $args optional arguments
450
     * @return Mockery\Expectation
451
     * @throws InvalidArgumentException
452
     */
453
    public static function echoFunction(string $function, $args = [])
454
    {
455
        /** @var array<string, mixed> $args */
456
        $args = (array) $args;
1✔
457
        $args['return'] = function ($param) {
1✔
458
            echo $param;
1✔
459
        };
1✔
460

461
        return self::$functionsManager->register($function, $args);
1✔
462
    }
463

464
    /**
465
     * A wrapper for {@see WP_Mock::userFunction()} that will simply set/override the return to be a function that returns the value that its passed.
466
     *
467
     * For example, `esc_attr()` may need to be mocked, and it must return some value.
468
     * {@see WP_Mock::passthruFunction()} will set `esc_attr()` to return the value its passed:
469
     *
470
     *    WP_Mock::passthruFunction('esc_attr');
471
     *    echo esc_attr('some_value'); // echoes "some_value"
472
     *
473
     * @param string $function function name
474
     * @param mixed[]|scalar $args function arguments (optional)
475
     * @return Mockery\Expectation
476
     * @throws InvalidArgumentException
477
     */
478
    public static function passthruFunction(string $function, $args = [])
479
    {
480
        /** @var array<string, mixed> $args */
481
        $args = (array) $args;
1✔
482
        $args['return'] = function ($param) {
1✔
483
            return $param;
×
484
        };
1✔
485

486
        return self::$functionsManager->register($function, $args);
1✔
487
    }
488

489
    /**
490
     * Adds a function mock that aliases another callable.
491
     *
492
     * e.g.: WP_Mock::alias('wp_hash', 'md5');
493
     *
494
     * @param string|callable-string $function function to alias
495
     * @param string|callable-string $aliasFunction actual function
496
     * @param mixed[]|scalar $args optional arguments
497
     * @return Mockery\Expectation
498
     * @throws InvalidArgumentException
499
     */
500
    public static function alias(string $function, string $aliasFunction, $args = [])
501
    {
502
        /** @var array<string, mixed> $args */
503
        $args = (array) $args;
1✔
504

505
        if (is_callable($aliasFunction)) {
1✔
506
            $args['return'] = function () use ($aliasFunction) {
1✔
507
                return call_user_func_array($aliasFunction, func_get_args());
1✔
508
            };
1✔
509
        }
510

511
        return self::$functionsManager->register($function, $args);
1✔
512
    }
513

514
    /**
515
     * Generates a fuzzy object match expectation.
516
     *
517
     * This will let you fuzzy match objects based on their properties without needing to use the identical (===) operator.
518
     * This is helpful when the object being passed to a function is constructed inside the scope of the function being tested but where you want to make assertions on more than just the type of the object.
519
     *
520
     * @param object|array<mixed> $object
521
     * @return FuzzyObject
522
     * @throws MockeryException
523
     */
524
    public static function fuzzyObject($object): FuzzyObject
525
    {
526
        return new FuzzyObject($object);
3✔
527
    }
528

529
    /**
530
     * Gets the deprecated method listener instance.
531
     *
532
     * @return DeprecatedMethodListener
533
     */
534
    public static function getDeprecatedMethodListener(): DeprecatedMethodListener
535
    {
536
        return static::$deprecatedMethodListener;
2✔
537
    }
538
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc