Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHPUnit 11.2.0 | AssertObjectNotEquals trait: polyfill the Assert::assertObjectNotEquals() method #199

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,17 @@ Refactoring tests which still use `Assert::assertArraySubset()` to use the new a
[`Assert::assertArrayIsIdenticalToArrayOnlyConsideringListOfKeys()`]: https://docs.phpunit.de/en/main/assertions.html#assertarrayisidenticaltoarrayonlyconsideringlistofkeys
[`Assert::assertArrayIsIdenticalToArrayIgnoringListOfKeys()`]: https://docs.phpunit.de/en/main/assertions.html#assertarrayisidenticaltoarrayignoringlistofkeys

#### PHPUnit < 11.2.0: `Yoast\PHPUnitPolyfills\Polyfills\AssertObjectNotEquals`

Polyfills the [`Assert::assertObjectNotEquals()`] method to verify two (value) objects are **_not_** considered equal.
This is the sister-method to the PHPUnit 9.4+ `Assert::assertObjectEquals()` method.

This assertion expects an object to contain a comparator method in the object itself. This comparator method is subsequently called to verify the "equalness" of the objects.

The `assertObjectNotEquals()` assertion was introduced in PHPUnit 11.2.0.

[`Assert::assertObjectNotEquals()`]: https://docs.phpunit.de/en/main/assertions.html#assertobjectequals


### TestCases

Expand Down
22 changes: 22 additions & 0 deletions phpunitpolyfills-autoload.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ public static function load( $className ) {
self::loadAssertArrayWithListKeys();
return true;

case 'Yoast\PHPUnitPolyfills\Polyfills\AssertObjectNotEquals':
self::loadAssertObjectNotEquals();
return true;

case 'Yoast\PHPUnitPolyfills\TestCases\TestCase':
self::loadTestCase();
return true;
Expand All @@ -97,6 +101,7 @@ public static function load( $className ) {
/*
* Handles:
* - Yoast\PHPUnitPolyfills\Exceptions\InvalidComparisonMethodException
* - Yoast\PHPUnitPolyfills\Helpers\ComparatorValidator
* - Yoast\PHPUnitPolyfills\Helpers\ResourceHelper
* - Yoast\PHPUnitPolyfills\TestCases\XTestCase
* - Yoast\PHPUnitPolyfills\TestListeners\TestListenerSnakeCaseMethods
Expand Down Expand Up @@ -334,6 +339,23 @@ public static function loadAssertArrayWithListKeys() {
require_once __DIR__ . '/src/Polyfills/AssertArrayWithListKeys_Empty.php';
}

/**
* Load the AssertObjectNotEquals polyfill or an empty trait with the same name
* if a PHPUnit version is used which already contains this functionality.
*
* @return void
*/
public static function loadAssertObjectNotEquals() {
if ( \method_exists( Assert::class, 'assertObjectNotEquals' ) === false ) {
// PHPUnit < 11.2.0.
require_once __DIR__ . '/src/Polyfills/AssertObjectNotEquals.php';
return;
}

// PHPUnit >= 11.2.0.
require_once __DIR__ . '/src/Polyfills/AssertObjectNotEquals_Empty.php';
}

/**
* Load the appropriate TestCase class based on the PHPUnit version being used.
*
Expand Down
4 changes: 2 additions & 2 deletions src/Exceptions/InvalidComparisonMethodException.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
use Exception;

/**
* Exception used for all errors throw by the polyfill for the `assertObjectEquals()` assertion.
* Exception used for all errors throw by the polyfill for the `assertObjectEquals()` and the `assertObjectNotEquals()` assertions.
*
* PHPUnit natively throws a range of different exceptions.
* The polyfill throws just one exception type with different messages.
* The polyfills throw just one exception type with different messages.
*/
final class InvalidComparisonMethodException extends Exception {

Expand Down
181 changes: 181 additions & 0 deletions src/Helpers/ComparatorValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?php

namespace Yoast\PHPUnitPolyfills\Helpers;

use ReflectionNamedType;
use ReflectionObject;
use ReflectionType;
use Yoast\PHPUnitPolyfills\Exceptions\InvalidComparisonMethodException;

/**
* Helper functions for validating a comparator method complies with the requirements set by PHPUnit.
*
* ---------------------------------------------------------------------------------------------
* This class is only intended for internal use by PHPUnit Polyfills and is not part of the public API.
* This also means that it has no promise of backward compatibility.
*
* End-users should use the {@see \Yoast\PHPUnitPolyfills\Polyfills\AssertObjectEquals} and/or the
* {@see \Yoast\PHPUnitPolyfills\Polyfills\AssertObjectNotEquals} trait instead.
* ---------------------------------------------------------------------------------------------
*
* @internal
*/
final class ComparatorValidator {

/**
* Asserts that a custom object comparison method complies with the requirements set by PHPUnit.
*
* The custom comparator method is expected to have the following method
* signature: `equals(self $other): bool` (or similar with a different method name).
*
* Basically, this method checks the following:
* - A method with name $method must exist on the $actual object.
* - The method must accept exactly one argument and this argument must be required.
* - This parameter must have a classname-based declared type.
* - The $expected object must be compatible with this declared type.
* - The method must have a declared bool return type.
*
* {@internal Type validation for the parameters should be done in the calling function.}
*
* @param object $expected Expected value.
* This object should comply with the type requirement set by the parameter type
* of the comparator method on $actual.
* @param object $actual The object on which the comparator method should exist.
* @param string $method The name of the comparator method expected within the object.
*
* @return void
*
* @throws InvalidComparisonMethodException When the comparator method does not comply with the requirements.
*/
public static function isValid( $expected, $actual, $method = 'equals' ) {
/*
* Verify the method exists.
*/
$reflObject = new ReflectionObject( $actual );

if ( $reflObject->hasMethod( $method ) === false ) {
throw new InvalidComparisonMethodException(
\sprintf(
'Comparison method %s::%s() does not exist.',
\get_class( $actual ),
$method
)
);
}

$reflMethod = $reflObject->getMethod( $method );

/*
* Comparator method return type requirements validation.
*/
$returnTypeError = \sprintf(
'Comparison method %s::%s() does not declare bool return type.',
\get_class( $actual ),
$method
);

if ( $reflMethod->hasReturnType() === false ) {
throw new InvalidComparisonMethodException( $returnTypeError );
}

$returnType = $reflMethod->getReturnType();

if ( \class_exists( 'ReflectionNamedType' ) ) {
// PHP >= 7.1: guard against union/intersection return types.
if ( ( $returnType instanceof ReflectionNamedType ) === false ) {
throw new InvalidComparisonMethodException( $returnTypeError );
}
}
elseif ( ( $returnType instanceof ReflectionType ) === false ) {
/*
* PHP 7.0.
* Checking for `ReflectionType` will not throw an error on union types,
* but then again union types are not supported on PHP 7.0.
*/
throw new InvalidComparisonMethodException( $returnTypeError );
}

if ( $returnType->allowsNull() === true ) {
throw new InvalidComparisonMethodException( $returnTypeError );
}

if ( \method_exists( $returnType, 'getName' ) ) {
// PHP >= 7.1.
if ( $returnType->getName() !== 'bool' ) {
throw new InvalidComparisonMethodException( $returnTypeError );
}
}
elseif ( (string) $returnType !== 'bool' ) {
// PHP 7.0.
throw new InvalidComparisonMethodException( $returnTypeError );
}

/*
* Comparator method parameter requirements validation.
*/
if ( $reflMethod->getNumberOfParameters() !== 1
|| $reflMethod->getNumberOfRequiredParameters() !== 1
) {
throw new InvalidComparisonMethodException(
\sprintf(
'Comparison method %s::%s() does not declare exactly one parameter.',
\get_class( $actual ),
$method
)
);
}

$noDeclaredTypeError = \sprintf(
'Parameter of comparison method %s::%s() does not have a declared type.',
\get_class( $actual ),
$method
);

$notAcceptableTypeError = \sprintf(
'%s is not an accepted argument type for comparison method %s::%s().',
\get_class( $expected ),
\get_class( $actual ),
$method
);

$reflParameter = $reflMethod->getParameters()[0];

$hasType = $reflParameter->hasType();
if ( $hasType === false ) {
throw new InvalidComparisonMethodException( $noDeclaredTypeError );
}

$type = $reflParameter->getType();
if ( \class_exists( 'ReflectionNamedType' ) ) {
// PHP >= 7.1.
if ( ( $type instanceof ReflectionNamedType ) === false ) {
throw new InvalidComparisonMethodException( $noDeclaredTypeError );
}

$typeName = $type->getName();
}
else {
/*
* PHP 7.0.
* Checking for `ReflectionType` will not throw an error on union types,
* but then again union types are not supported on PHP 7.0.
*/
if ( ( $type instanceof ReflectionType ) === false ) {
throw new InvalidComparisonMethodException( $noDeclaredTypeError );
}

$typeName = (string) $type;
}

/*
* Validate that the $expected object complies with the declared parameter type.
*/
if ( $typeName === 'self' ) {
$typeName = \get_class( $actual );
}

if ( ( $expected instanceof $typeName ) === false ) {
throw new InvalidComparisonMethodException( $notAcceptableTypeError );
}
}
}
Loading