phpunit icon indicating copy to clipboard operation
phpunit copied to clipboard

Feature: Assertion of Array Items by Inexact Match

Open sshymko opened this issue 11 years ago • 2 comments

The Problem

PHPUnit does offer assertions for almost every occasion. However, this is not the case for arrays (or traversables to be more generic). Only few assertions work with array contents: assertArrayHasKey assertContains, assertContainsOnly, assertContainsOnlyInstancesOf. There are also their negative counterparts. But that's pretty much it, array item/key support ends here.

Existing assertions that target arrays allow only for exact match. However, there are cases when exact match would overly complicate a test or make it too fragile. Other cases are impossible to cover by exact matching.

Actually, the problem is even bigger - not only inexact match is unavailable for array items, but arbitrary constraints cannot be used to assert array items.

Known Use Cases

Elaborate assertions of array items are fairly common. Some generic use cases are listed below.

Asserting Headers

Asserting that certain header is present among all headers. For example, a test may be interested in verifying the fact that redirection has been set, but not interested in matching exact target URL (to avoid test fragility). Unless matching exact header (case sensitive) is desirable, assertContains cannot be used here.

Asserting Filenames

Imagine a code that traverses file system and collects files/dirs. A test for such a code would contain fixture files/dirs. Asserting exact match would complicate such a test, because it would have to include a full fixture directory path. It also would encourage to dynamically build expected values, again, because of necessity to include fixture directory path.

Actually, asserting that files in array exist is currently impossible. It's not an example of inexact match, but rather unavailability of existing constraints (PHPUnit_Framework_Constraint_FileExists in this case) for array items.

Asserting Messages

It is typical for an application to collect error/warning/notification messages and display them to an end user. Of course, a test would be interested in verifying presence of a specific message. But also absence of error messages of any kind may need to be verified. If plain text messages are used, assertion would come down to verifying absence of such keywords as "error", "fail", etc.

The same is applicable to asserting log entries as well.

Proposed Solution

The idea is to to allow matching array items/keys against any constraint, i.e. an instance of PHPUnit_Framework_Constraint. In such a way the whole variety of existing constrains becomes available for asserting array items.

Proposed Syntax

At first, it appeared to make sense to name assertions around array keyword. More detailed analysis suggests more generalization to comply with traversable instances. Existing assertion assertContains seems to be a good prototype to borrow the naming from.

Usage example of assertContainsMatching:

$actualHeaders = array(
    'Location: /some/redirect/target/page.html',
    'Content-Type: text/html; charset=utf-8',
    // ...
);
$this->assertContainsMatching(
    $this->stringStartsWith('Location:'),
    $actualHeaders,
    'Redirect is expected.'
);

Usage example of assertContainsOnlyMatching:

$actualFilenames = array(
    '/project/tests/_files/fixture/path/1.txt',
    '/project/tests/_files/fixture/path/2.txt',
    '/project/tests/_files/fixture/path/sub/dir/3.txt',
    // ...
);
$this->assertContainsOnlyMatching(
    $this->stringEndsWith('.txt'),
    $actualFilenames,
    'Only text files are expected.'
);

Conventionally, corresponding factory methods would be containsMatching and containsOnlyMatching.

Assertion Array Keys

While assertion of array items is the primary use case, optional validation of array keys would create a complete solution.

Added Benefits

Introduction of the new assertions has positive consequences described below.

Eliminating Specialized Assertions

Proposed new assertions eliminate the need in the number of more specialized assertions. For instance, the following assertions are equivalent:

$this->assertContainsOnlyInstancesOf($expected, $actual);
$this->assertContainsOnlyMatching($this->isInstanceOf($expected), $actual);
$this->assertContainsOnly($expected, $actual);
$this->assertContainsOnlyMatching($this->isType($expected), $actual);
$this->assertContainsOnlyMatching($this->isInstanceOf($expected), $actual);
$this->assertContains($expected, $actual);
$this->assertContainsMatching($this->equalTo($expected), $actual);
$this->assertContainsMatching($this->identicalTo($expected), $actual);

Even assertArrayHasKey seems to be covered by assertContainsMatching if the latter implements array key matching besides the item value matching. However, assertArrayHasKey will probably survive because of performance considerations.

Asserting Multi-Dimensional Arrays

The syntax comes with the flexibility of constraining array items on any nesting level. For example:

$actual = array(
    array('a11', 'a12', 'a13'),
    array('a21', 'a22', 'a23'),
    // ...
);
$this->assertContainsOnlyMatching(
    $this->containsOnlyMatching(
        $this->matchesRegularExpression('/^a\d+$/')
    ),
    $actual
);

Note that containsMatching/containsOnlyMatching can be recursively nested as much as needed to cover array of any depth.

sshymko avatar Mar 11 '15 19:03 sshymko

This definitely makes sense! I second it.

zerkella avatar Mar 15 '15 00:03 zerkella

Dear contributor,

let me start by apologizing for not commenting and/or working on the issue you have reported or merging the pull request you have sent sooner.

PHPUnit 5.0 was released today. And today I am closing all open bug reports and pull requests for PHPUnit and its dependencies that I maintain. Please do not interpret the closing of this ticket as an insult or a lack of interest in your problem. I am sorry for any inconvenience this may cause.

If the topic of this ticket is still relevant then please open a new ticket or send a new pull request. If your ticket or pull request is about a defect then please check whether the issue still exists in PHPUnit 4.8 (which will received bug fixes until August 2016). If your ticket or pull request is about a new feature then please port your patch PHPUnit 5.0 before sending a new pull request.

I hope that today's extreme backlog grooming will allow me to respond to bug reports and pull requests in a more timely manner in the future.

Thank you for your understanding, Sebastian

sebastianbergmann avatar Oct 02 '15 04:10 sebastianbergmann