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

10up / wp_mock / 9711864001

28 Jun 2024 11:11AM UTC coverage: 66.312% (-0.1%) from 66.445%
9711864001

push

github

web-flow
Ignore throws in function mocks (#245)

# Summary <!-- Required -->

I have noticed that in some circumstances the mocks contained in
`API/function-mocks.php` could trigger false positives in static
analyzers like PhpStan or just the IDE if using WP_Mock within a
project. I think by removing the `@throws` solves this, although PhpStan
will complain about it _in this_ project. I suppose since these are just
internal mocks we can safely ignore.

I did try using `@noinspection` tags but PhpStorm wasn't happy (whether
specific to unhandled exceptions or not).

As for the strict type notations, same reason, externally it will
reflect WP behavior (the alternative was to leave non-strict and rely
only on phpdoc -- like WP does -- but then PhpStan would complain
again... could swap that for a phpstan-ignore again, up to you)

## Closes #248 

## Contributor checklist <!-- Required -->

<!--- Go over all the following points, and put an `x` in all the boxes
that apply. -->
<!--- If you are unsure about any of these, please ask for
clarification. We are here to help! -->

- [x] I agree to follow this project's [**Code of
Conduct**](https://github.com/10up/.github/blob/trunk/CODE_OF_CONDUCT.md).
- [x] I have updated the documentation accordingly 
- [x] I have added tests to cover changes introduced by this pull
request
- [x] All new and existing tests pass

## Testing <!-- Required -->

<!-- If applicable, add specific steps for the reviewer to perform as
part of their testing process prior to approving this pull request. -->

<!-- List any configuration requirements for testing. -->

### Reviewer checklist <!-- Required -->

<!-- The following checklist is for the reviewer: add any steps that may
be relevant while reviewing this pull request -->

- [x] Code changes review
- [ ] Documentation changes review
- [x] Unit tests pass
- [x] Static analysis passes

2 of 2 new or added lines in 1 file covered. (100.0%)

4 existing lines in 3 files now uncovered.

498 of 751 relevant lines covered (66.31%)

2.61 hits per line

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

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

3
/**
4
 * @package WP_Mock
5
 * @copyright 2013-2024 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;
13✔
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;
23✔
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;
13✔
82

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

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

88
            if (self::usingPatchwork()) {
13✔
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();
13✔
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) {
40✔
117
            \Mockery::close();
40✔
118

119
            self::$event_manager    = new \WP_Mock\EventManager();
40✔
120
            self::$functionsManager = new \WP_Mock\Functions();
40✔
121
        } else {
UNCOV
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);
4✔
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');
3✔
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');
3✔
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";
3✔
223
        self::$event_manager->called($type_name, 'callback');
3✔
224
    }
225

226
    /**
227
     * Adds an expectation that an action will be called during the test.
228
     *
229
     * @param string $action expected action
230
     * @returnv oid
231
     */
232
    public static function expectAction(string $action) : void
233
    {
234
        $intercept = Mockery::mock('intercept');
2✔
235
        $intercept->shouldReceive('intercepted')->atLeast()->once();
2✔
236
        $args = func_get_args();
2✔
237
        $args = count($args) > 1 ? array_slice($args, 1) : array( null );
2✔
238

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

244
    /**
245
     * Adds an expectation that a filter will be applied during the test.
246
     *
247
     * @param string $filter expected filter
248
     * @return void
249
     */
250
    public static function expectFilter(string $filter) : void
251
    {
252
        $intercept = Mockery::mock('intercept');
2✔
253
        $intercept->shouldReceive('intercepted')->atLeast()->once()->andReturnUsing(function ($value) {
2✔
254
            return $value;
1✔
255
        });
2✔
256
        $args = func_num_args() > 1 ? array_slice(func_get_args(), 1) : array( null );
2✔
257

258
        $mocked_filter = self::onFilter($filter);
2✔
259
        $responder     = call_user_func_array(array( $mocked_filter, 'with' ), $args);
2✔
260
        $responder->reply(new WP_Mock\InvokedFilterValue(array( $intercept, 'intercepted' )));
2✔
261
    }
262

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

275
    /**
276
     * Asserts that all filters are called.
277
     *
278
     * @return void
279
     */
280
    public static function assertFiltersCalled() : void
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
     * Adds an expectation that an action hook should be added.
289
     *
290
     * @param string $action the action hook name
291
     * @param string|callable-string|callable|Type $callback the callback that should be registered
292
     * @param int $priority the priority it should be registered at
293
     * @param int $args the number of arguments that should be allowed
294
     * @return void
295
     */
296
    public static function expectActionAdded(string $action, $callback, int $priority = 10, int $args = 1) : void
297
    {
298
        self::expectHookAdded('action', $action, $callback, $priority, $args);
3✔
299
    }
300

301
    /**
302
     * Adds an expectation that an action hook should not be added.
303
     *
304
     * @param string $action the action hook name
305
     * @param string|callable-string|callable|Type $callback the callback that should be registered
306
     * @param int $priority the priority it should be registered at
307
     * @param int $args the number of arguments that should be allowed
308
     * @return void
309
     */
310
    public static function expectActionNotAdded(string $action, $callback, int $priority = 10, int $args = 1) : void
311
    {
312
        self::expectHookNotAdded('action', $action, $callback, $priority, $args);
1✔
313
    }
314

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

329
    /**
330
     * Adds an expectation that a filter hook should not be added.
331
     *
332
     * @param string $filter the filter hook name
333
     * @param string|callable-string|callable|Type $callback the callback that should be registered
334
     * @param int $priority the priority it should be registered at
335
     * @param int $args the number of arguments that should be allowed
336
     * @return void
337
     */
338
    public static function expectFilterNotAdded(string $filter, $callback, int $priority = 10, int $args = 10) : void
339
    {
340
        self::expectHookNotAdded('filter', $filter, $callback, $priority, $args);
×
341
    }
342

343
    /**
344
     * Adds an expectation that a hook should be added.
345
     *
346
     * Based {@see Mockery\MockInterface::shouldReceive()}.
347
     *
348
     * @param string $type the type of hook being added ('action' or 'filter')
349
     * @param string $hook the hook name
350
     * @param string|callable-string|callable|Type $callback the callback that should be registered
351
     * @param int $priority the priority it should be registered at
352
     * @param int $args the number of arguments that should be allowed
353
     * @return void
354
     */
355
    public static function expectHookAdded(string $type, string $hook, $callback, int $priority = 10, int $args = 1) : void
356
    {
357
        $intercept = Mockery::mock('intercept');
3✔
358
        $intercept->shouldReceive('intercepted')->atLeast()->once();
3✔
359

360
        /** @var WP_Mock\HookedCallbackResponder $responder */
361
        $responder = self::onHookAdded($hook, $type)
3✔
362
            ->with($callback, $priority, $args);
3✔
363
        $responder->perform([$intercept, 'intercepted']);
3✔
364
    }
365

366
    /**
367
     * Adds an expectation that a hook should not be added.
368
     *
369
     * Based {@see Mockery\MockInterface::shouldNotReceive()}.
370
     *
371
     * @param string $type the type of hook being added ('action' or 'filter')
372
     * @param string $hook the hook name
373
     * @param string|callable-string|callable|Type $callback the callback that should be registered
374
     * @param int $priority the priority it should be registered at
375
     * @param int $args the number of arguments that should be allowed
376
     * @return void
377
     */
378
    public static function expectHookNotAdded(string $type, string $hook, $callback, int $priority = 10, int $args = 1) : void
379
    {
380
        $intercept = Mockery::mock('intercept');
1✔
381
        $intercept->shouldNotReceive('intercepted');
1✔
382

383
        /** @var WP_Mock\HookedCallbackResponder $responder */
384
        $responder = self::onHookAdded($hook, $type)
1✔
385
            ->with($callback, $priority, $args);
1✔
386
        $responder->perform([$intercept, 'intercepted']);
1✔
387
    }
388

389
    /**
390
     * Asserts that all hooks are added.
391
     *
392
     * @return void
393
     */
394
    public static function assertHooksAdded() : void
395
    {
396
        $allHooksAdded = self::$event_manager->allHooksAdded();
3✔
397
        $failed = implode(', ', self::$event_manager->expectedHooks());
3✔
398
        PHPUnit\Framework\Assert::assertTrue($allHooksAdded, 'Method failed to add hooks: ' . $failed);
3✔
399
    }
400

401
    /**
402
     * Mocks a WordPress API function.
403
     *
404
     * This function registers a mock object for a WordPress function and, if necessary, dynamically defines the function.
405
     *
406
     * Pass the function name as the first argument (e.g. `wp_remote_get()`) and pass in details about the expectations in the $args param.
407
     * The arguments have a few options for defining expectations about how the WordPress function should be used during a test.
408
     *
409
     * Currently, it accepts the following settings:
410
     *
411
     * - `times`: Defines expectations for the number of times a function should be called. The default is `0` or more times.
412
     *            To expect the function to be called an exact amount of times, set times to a non-negative numeric value.
413
     *            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).
414
     *            Append a '-' to indicate a maximum number of times a function should be called (e.g. '3-' means no more than 3 times).
415
     *            To indicate a range, use '-' between two numbers (e.g. '2-5' means at least 2 times and no more than 5 times).
416
     *
417
     * - `return`: Defines the value (if any) that the function should return.
418
     *             If you pass a `Closure` as the return value, the function will return whatever the closure's return value.
419
     *
420
     * - `return_in_order`: Use this if your function will be called multiple times in the test but needs to have different return values.
421
     *                      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.
422
     *                      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.
423
     *                      The second and all subsequent times it will return true. Setting this value overrides return, so if you set both, return will be ignored.
424
     *
425
     * - `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.
426
     *                 You can also set this to true, which is equivalent to `0`. This will override both return and return_in_order.
427
     *
428
     * - `args`: Use this to set expectations about what the arguments passed to the function should be.
429
     *           This value should always be an array with the arguments in order.
430
     *           Like with `return`, if you use a `Closure`, its return value will be used to validate the argument expectations.
431
     *           WP_Mock has several helper functions to make this feature more flexible. There are static methods on the \WP_Mock\Functions class. They are:
432
     *           - {@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.
433
     *           - {@see Functions::anyOf($values)} Expects the argument to be any value in the `$values` array.
434
     *           In addition to these helper functions, you can indicate that the argument can be any value of any type by using `*`.
435
     *           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]`.
436
     *
437
     * Returns the {@see Mockery\Expectation} object with the function expectations added.
438
     * 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.
439
     *
440
     * @param string $function function name
441
     * @param mixed[] $args optional arguments to set expectations
442
     * @return Mockery\Expectation
443
     * @throws InvalidArgumentException
444
     */
445
    public static function userFunction(string $function, array $args = [])
446
    {
447
        return self::$functionsManager->register($function, $args);
8✔
448
    }
449

450
    /**
451
     * 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.
452
     *
453
     * For example, `esc_attr_e()` may need to be mocked, and it must echo some value.
454
     * {@see WP_Mock::echoFunction()} will set `esc_attr_e()` to echo the value its passed:
455
     *
456
     *    WP_Mock::echoFunction('esc_attr_e');
457
     *    esc_attr_e('some_value'); // echoes "some_value"
458
     *
459
     * @param string $function function name
460
     * @param mixed[]|scalar $args optional arguments
461
     * @return Mockery\Expectation
462
     * @throws InvalidArgumentException
463
     */
464
    public static function echoFunction(string $function, $args = [])
465
    {
466
        /** @var array<string, mixed> $args */
467
        $args = (array) $args;
1✔
468
        $args['return'] = function ($param) {
1✔
469
            echo $param;
1✔
470
        };
1✔
471

472
        return self::$functionsManager->register($function, $args);
1✔
473
    }
474

475
    /**
476
     * 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.
477
     *
478
     * For example, `esc_attr()` may need to be mocked, and it must return some value.
479
     * {@see WP_Mock::passthruFunction()} will set `esc_attr()` to return the value its passed:
480
     *
481
     *    WP_Mock::passthruFunction('esc_attr');
482
     *    echo esc_attr('some_value'); // echoes "some_value"
483
     *
484
     * @param string $function function name
485
     * @param mixed[]|scalar $args function arguments (optional)
486
     * @return Mockery\Expectation
487
     * @throws InvalidArgumentException
488
     */
489
    public static function passthruFunction(string $function, $args = [])
490
    {
491
        /** @var array<string, mixed> $args */
492
        $args = (array) $args;
1✔
493
        $args['return'] = function ($param) {
1✔
494
            return $param;
×
495
        };
1✔
496

497
        return self::$functionsManager->register($function, $args);
1✔
498
    }
499

500
    /**
501
     * Adds a function mock that aliases another callable.
502
     *
503
     * e.g.: WP_Mock::alias('wp_hash', 'md5');
504
     *
505
     * @param string|callable-string $function function to alias
506
     * @param string|callable-string $aliasFunction actual function
507
     * @param mixed[]|scalar $args optional arguments
508
     * @return Mockery\Expectation
509
     * @throws InvalidArgumentException
510
     */
511
    public static function alias(string $function, string $aliasFunction, $args = [])
512
    {
513
        /** @var array<string, mixed> $args */
514
        $args = (array) $args;
1✔
515

516
        if (is_callable($aliasFunction)) {
1✔
517
            $args['return'] = function () use ($aliasFunction) {
1✔
518
                return call_user_func_array($aliasFunction, func_get_args());
1✔
519
            };
1✔
520
        }
521

522
        return self::$functionsManager->register($function, $args);
1✔
523
    }
524

525
    /**
526
     * Generates a fuzzy object match expectation.
527
     *
528
     * This will let you fuzzy match objects based on their properties without needing to use the identical (===) operator.
529
     * 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.
530
     *
531
     * @param object|array<mixed> $object
532
     * @return FuzzyObject
533
     * @throws MockeryException
534
     */
535
    public static function fuzzyObject($object): FuzzyObject
536
    {
537
        return new FuzzyObject($object);
3✔
538
    }
539

540
    /**
541
     * Gets the deprecated method listener instance.
542
     *
543
     * @return DeprecatedMethodListener
544
     */
545
    public static function getDeprecatedMethodListener(): DeprecatedMethodListener
546
    {
547
        return static::$deprecatedMethodListener;
2✔
548
    }
549
}
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