wp_mock icon indicating copy to clipboard operation
wp_mock copied to clipboard

Reply to filter 'with' anything

Open Flynsarmy opened this issue 5 years ago • 1 comments

Is your feature request related to a problem? Please describe. If I have a pre-defined array as my first filter argument in some method, there's no easy way to write a test for how the method responds when the values this method passes to the filter change. Here's an example.

I have a static method that calls apply_filters with a large pre-defined array as its first argument:

$extensions_to_ignore = [
    '.bat',
    '.crt',
    '.DS_Store',
    ...
];

$extensions_to_ignore = apply_filters('extensions_to_ignore', $extensions_to_ignore);

When writing a test for the method this filter takes place in, I need to write something like so:

// with() array must always match FilesHelper::extensionCheck()'s $extensions_to_ignore array
\WP_Mock::onFilter( 'extensions_to_ignore' )->with([
    '.bat',
    '.crt',
    '.DS_Store',
    ...
])->reply(['.unknown']);
// We've disallowed .unknown - test it
$expected = false;
$actual = FilesHelper::extensionCheck( "/path/to/foo.unknown" );
$this->assertEquals( $expected, $actual );

The problem occurs in that my test needs to always have an exact clone of the $extensions_to_ignore array from my application's method. If I ever change the application's array, this test breaks even though I don't care about the input from the filter.

Describe the solution you'd like I'd like a way to create an onFilter that takes anything and responds with what i want. Something like:

\WP_Mock::onFilter( 'extensions_to_ignore' )->reply(['.unknown']);

^ This would accept any input to the extensions_to_ignore filter and return ['.unknown'].

Describe alternatives you've considered Maybe something like this?

\WP_Mock::onFilter( 'extensions_to_ignore' )->withAnything()->reply(['.unknown']);

Flynsarmy avatar Aug 19 '20 04:08 Flynsarmy

Just want to add a vote for this. If I have time I'll try to put together a PR, but please don't wait for me to do so.

rosswintle avatar Jan 25 '22 12:01 rosswintle