Giter Club home page Giter Club logo

comparator's Introduction

Hi!

I am Sebastian Bergmann. If you develop software using the PHP programming language then you may have come across my name. I am the creator and maintainer of PHPUnit as well as many other libraries and tools that are commonly used.

You cannot buy PHPUnit, but you can pay for PHPUnit. And the best way to do so benefits you, your team, and me: let me help you through consulting, coaching, and training.

Of course, you can also sponsor my work on PHPUnit.


๐Ÿ‘ท Check out what I'm currently working on


๐Ÿ”ญ Latest releases I've contributed to


๐Ÿ“ซ How to reach me

comparator's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

comparator's Issues

Modernize build automation

  • Use GitHub Actions instead of Travis CI
  • Have Composer in tools/composer and managed through composer self-update (see update-tools target in build.xml
  • Install Psalm using Phive as tools/psalm (phive install --copy psalm)
  • Install PHP-CS-Fixer using Phive as tools/php-cs-fixer (phive install --copy php-cs-fixer)
  • Create Psalm configuration
  • Add Psalm build step to GitHub Actions-based CI workflow
  • Add PHP-CS-Fixer build step to GitHub Actions-based CI workflow

Composer update error

Hi,
I have run composer update and it returns RuntimeException that you have unpushed changes on the current branch

Installation failed, reverting ./composer.json to its original content.
[RuntimeException]
Source directory ***sebastian/comparator has unpushed changes on the current branch:
M .gitignore
M .travis.yml
M build.xml
D build/travis-ci.xml
M composer.json
A phpunit.xml
D phpunit.xml.dist
M src/Comparator.php
M src/DoubleComparator.php
M src/NumericComparator.php
M src/ResourceComparator.php
M src/ScalarComparator.php
M src/SplObjectStorageComparator.php
M src/TypeComparator.php
D tests/_files/Author.php
D tests/_files/Book.php
D tests/_files/ClassWithToString.php
D tests/_files/SampleClass.php
D tests/_files/Struct.php
D tests/_files/TestClass.php
D tests/_files/TestClassComparator.php
A tests/_fixture/Author.php
A tests/_fixture/Book.php
A tests/_fixture/ClassWithToString.php
A tests/_fixture/SampleClass.php
A tests/_fixture/Struct.php
A tests/_fixture/TestClass.php
A tests/_fixture/TestClassComparator.php
D tests/autoload.php
D tests/bootstrap.php

please advise
Thanks

comparing array with bool: true value doesn't throw a ComparisonException

Hello,

I'm using your library to compare array recursively in dev environment.
One of my test was failing randomly while using generated data in it (with faker).
I figured out that the case below doesn't throw an exception, I think it's a weird behaviour so I wanted to notice you, maybe I should not use your library this way, let me know. :)

public function testCompareArrayWeirdBehavior()
{
    $body = [
        'somestr' => true,
    ];
    $toCompareBody = [
        'somestr' => 'some other str',
    ];
    Factory::getInstance()->getComparatorFor($body, $toCompareBody)->assertEquals(
        $body,
        $toCompareBody
    );
}

version of the library: 4.0.8

Thanks for your work anyway ! ๐Ÿ‘๐Ÿป

DateTimeComparator cannot use fractional second deltas

use SebastianBergmann\Comparator\DateTimeComparator;

$halfSecond = new \DateInterval('PT0S');
$halfSecond->f = 0.5;

$expected = new \DateTime();
$actual = (clone $expected)->add($halfSecond);

$comparator = new DateTimeComparator();
$comparator->assertEquals($expected, $actual, 0.5);
// Failed asserting that two DateTime objects are equal.

DateTimeComparator is invalid

  1. Required version of PHP moved up, but code not updated yet(partially fixes by PR #95)
  2. DateTimeComparator::assertEquals() calls setTimezone(), but DateTimeInterface not declare this method

DOMNodeComparator::nodeToText used C14N but don't do anything when it fail.

I have been experimenting false positives on asserting that two XML are equal on <4.0.1, and TypeError on >=4.0.1. The change on >=4.0.1 is the declare(strict_types=1).

$xml = <<<EOT
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [
  <!ENTITY ns_ai "http://ns.adobe.com/AdobeIllustrator/10.0/">
]>
<!-- This is a reduction of a much larger SVG file from Adobe Illustrator 15.0.0, SVG Export Plug-In. -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:i="&ns_ai;" foo="foo"/>
EOT;

// just change something to illustrate the problem
$modified = str_replace('foo="foo"', 'foo="bar"', $xml);

// on < 4.0.1 this is false positive
$this->assertXmlStringEqualsXmlString($xml, $modified);

// on => 4.0.1 this is a TypeError, but xmls contents are the same
$this->assertXmlStringEqualsXmlString($xml, $xml);

On >=4.0.1 the declare(strict_types=1) was set on DOMNodeComparator and it raises a TypeError.

TypeError : DOMDocument::loadXML() expects parameter 1 to be string, bool given
path-of-my-test.php:99

I trace down the error to DOMNodeComparator::nodeToText where it try to always canonicalize the XML by doing @$document->loadXML($node->C14N());. The problem is when DOMNode::C14N() fails and return false.

  • On <4.0.1 it just try lo load an empty string. In case that both, $actual and $expected fails, then it gives the false positive.

  • On >=4.0.1 because of strict types it throws TypeError, wich is good, but not explicit.

I think its possible to do something like: the error silence operator: the users of DOMNodeComparator will know that they are providing some object impossible to canonicalize and compare. The failing point will be raised by $node->C14N() returning false.

  • Separate and silence @$node->C14N(), but check the return value on false and fail.

  • Throw an exception that inform what the problem is instead of letting the TypeError to raise.

Would you like me to take care of this issue with a PR?

Would you suggest a better approach?

ArrayComparator::assertEquals declaration not compatible with Comparator::assertEquals

Hello and first of all thanks for making this package available to us all

Looks like that on the new version 5.0.0 there's a mismatch on the declaration of the abstract class Comparator and the ArrayComparator

public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0, bool $canonicalize = false, bool $ignoreCase = false, array &$processed = []): void
abstract public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0, bool $canonicalize = false, bool $ignoreCase = false): void;

this is causing a PHP fatal error ([email protected])

PHP Fatal error:  Declaration of SebastianBergmann\Comparator\ArrayComparator::assertEquals(mixed $expected, mixed $actual, float $delta = 0, bool $canonicalize = false, bool $ignoreCase = false, array &$processed = []): void must be compatible with SebastianBergmann\Comparator\Comparator::assertEquals($expected, $actual, $delta = 0, $canonicalize = false, $ignoreCase = false) in /var/www/symfony/vendor/sebastian/comparator/src/ArrayComparator.php on line 36

Best

DOMNodeComparator and preserveWhiteSpace

I had the issue that preserveWhiteSpace was not set on my document. So the following failed:

<root>
    <child />
</root>

which dod not successfully compare with

<root>
<child />
</root>

I see that you set preserveWhiteSpace to false in the tests for DOMNodeComparator. Should this be done in the implementation of the comparator (e.g. where formatOutput is set to false) ?

Regression in 3.0.4 and 4.0.7

After #99, there is now a failing test in PHPUnit's own test suite:

$ ./phpunit --filter testConstraintIsEqual2#7
PHPUnit 8.5.29-10-g1f265825a3 #StandWithUkraine

Runtime:       PHP 8.1.10 with PCOV 1.0.11
Configuration: /usr/local/src/phpunit/phpunit.xml

F                                                                   1 / 1 (100%)

Time: 154 ms, Memory: 14.00 MB

There was 1 failure:

1) PHPUnit\Framework\Constraint\IsEqualTest::testConstraintIsEqual2 with data set #7 (array(true), array('true'), 'Failed asserting that two arr...\n )\n')

/usr/local/src/phpunit/src/Framework/Assert.php:3383
/usr/local/src/phpunit/tests/unit/Framework/Constraint/IsEqualTest.php:72
/usr/local/src/phpunit/src/Framework/TestCase.php:1492
/usr/local/src/phpunit/src/Framework/TestCase.php:1112
/usr/local/src/phpunit/src/Framework/TestResult.php:703
/usr/local/src/phpunit/src/Framework/TestCase.php:838
/usr/local/src/phpunit/src/Framework/TestSuite.php:619
/usr/local/src/phpunit/src/Framework/TestSuite.php:619
/usr/local/src/phpunit/src/Framework/TestSuite.php:619
/usr/local/src/phpunit/src/Framework/TestSuite.php:619
/usr/local/src/phpunit/src/TextUI/TestRunner.php:659
/usr/local/src/phpunit/src/TextUI/Command.php:235
/usr/local/src/phpunit/src/TextUI/Command.php:194

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Before #99, PHPUnit's assertEquals() (which uses the code changed in the aforementioned PR) considered ['true'] == [true]. This is in line with PHP's behaviour of the == operator:

php > var_dump('true' == true);
bool(true)
php > var_dump(['true'] == [true]);
bool(true)

i run the composer update with my project ,then runt return some error .

i use Laravel framework , but today i run the composer with my project, they have some waring with

Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\MockObjectComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/MockObjectComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/MockObjectComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\Factory" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/Factory.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/Factory.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\TypeComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/TypeComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/TypeComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\DateTimeComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/DateTimeComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/DateTimeComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\ArrayComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/ArrayComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/ArrayComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\DoubleComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/DoubleComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/DoubleComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\Comparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/Comparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/Comparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\ComparisonFailure" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/ComparisonFailure.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/ComparisonFailure.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\ScalarComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/ScalarComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/ScalarComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\ResourceComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/ResourceComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/ResourceComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\ExceptionComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/ExceptionComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/ExceptionComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\DOMNodeComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/DOMNodeComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/DOMNodeComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\ObjectComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/ObjectComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/ObjectComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\SplObjectStorageComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/SplObjectStorageComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/SplObjectStorageComparator.php", the first will be used.
Warning: Ambiguous class resolution, "SebastianBergmann\Comparator\NumericComparator" was found in both "/var/www/enclaveapp/vendor/sebastian/comparator/src/NumericComparator.php" and "/var/www/enclaveapp/vendor/sebastian/comparator/src/src/NumericComparator.php", the first will be used.

how should i fix it ?

Mac OS - MAMP - phpunit fails silently with error in log file

In the MAMP php log file

[08-Nov-2018 09:14:00 UTC] PHP Fatal error: Declaration of SebastianBergmann\Comparator\DOMNodeComparator::assertEquals($expected, $actual, $delta = 0, $canonicalize = false, $ignoreCase = false) must be compatible with SebastianBergmann\Comparator\ObjectComparator::assertEquals($expected, $actual, $delta = 0, $canonicalize = false, $ignoreCase = false, array &$processed = Array) in phar:///Applications/MAMP/Library/bin/phpunit-5.1.3.phar/sebastian-comparator/DOMNodeComparator.php on line 110

composer info | sort

gives

No composer.json in current directory, do you want to use the one at /Applications/MAMP/htdocs/oraalgo? [Y,n]? Y
doctrine/instantiator              1.1.0 A small, lightweight utility to instantiate objects in PHP without invoking their constructors
myclabs/deep-copy                  1.8.1 Create deep copies (clones) of your objects
phar-io/manifest                   1.0.3 Component for reading phar.io manifest information from a PHP Archive (PHAR)
phar-io/version                    2.0.1 Library for handling version information and constraints
phpdocumentor/reflection-common    1.0.1 Common reflection classes used by phpdocumentor to reflect the code structure
phpdocumentor/reflection-docblock  4.3.0 With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.
phpdocumentor/type-resolver        0.4.0
phpspec/prophecy                   1.8.0 Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage          6.1.4 Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator          2.0.2 FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-text-template          1.2.1 Simple template engine.
phpunit/php-timer                  2.0.0 Utility class for timing
phpunit/php-token-stream           3.0.1 Wrapper around PHP's tokenizer extension.
phpunit/phpunit                    7.4.3 The PHP Unit Testing framework.
sebastian/code-unit-reverse-lookup 1.0.1 Looks up which function or method a line of code belongs to
sebastian/comparator               3.0.2 Provides the functionality to compare PHP values for equality
sebastian/diff                     3.0.1 Diff implementation
sebastian/environment              3.1.0 Provides functionality to handle HHVM/PHP environments
sebastian/exporter                 3.1.0 Provides the functionality to export PHP variables for visualization
sebastian/global-state             2.0.0 Snapshotting of global state
sebastian/object-enumerator        3.0.3 Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector         1.1.1 Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context        3.0.0 Provides functionality to recursively process PHP variables
sebastian/resource-operations      2.0.1 Provides a list of PHP built-in functions that operate on resources
sebastian/version                  2.0.1 Library that helps with managing the version number of Git-hosted PHP projects
theseer/tokenizer                  1.1.0 A small library for converting tokenized PHP source code into XML and potentially other formats
webmozart/assert                   1.3.0 Assertions to validate method input/output with nice error messages.

Any idea how i could make phpunit start correctly ?
Thanks

PHP 8.0 Support

Is There PHP 8.0 support?

I want to update to 4.0 but that tags requires 7.3

ObjectComparator fails on objects containing non empty SplObjectStorage

I'm not sure if this is the intended behavior of the ObjectComparator, but the following code throws a ComparisonFailure exception. I suspect it's because of the way SplObjectStorageComparator works.

Can someone confirm this? I'm already investigating in how to fix this, in case the bug is confirmed.

$storage1 = new \SplObjectStorage();
$storage1->attach(new \stdClass());
$object1 = new SampleClass($storage1, 'b', 'c');

$storage2 = new \SplObjectStorage();
$storage2->attach(new \stdClass());
$object2 = new SampleClass($storage2, 'b', 'c');


$comparator = new ObjectComparator;
$comparator->setFactory(new Factory);

// this throws ComparisonFailure exception
$comparator->assertEquals($object1, $object2);

Blank diff output of NumericComparator

The following assertion produces blank output:
$this->assertEquals(1, 0);

Output
There was 1 failure:

  1. Test: Run
    Test Test.php:testRun
    - Expected | + Actual

Expected output
There was 1 failure:

  1. Test: Run
    Test Test.php:testRun
    - Expected | + Actual -1 +0

ComparisonFailure exception should be provided with expectedAsString and actualAsString values (https://github.com/sebastianbergmann/comparator/blob/master/src/NumericComparator.php#L61) but it isn't.
As a result ComparisonFailure::getDiff() produces blank output:
https://github.com/sebastianbergmann/comparator/blob/master/src/ComparisonFailure.php#L114

Larave Test assertEaquals(0, null) bug

i look carefully into the code and i found

the 0,null pair matches the ScalarComparator
but the assertEquals method return true because it uses "!=" instead of "!=="

Project state (alive?)

Hello!

I see here some issues (one of them mine) that didn't det any reply for years and now they just become closed without any solution or commentary why it will not be fixed/changed/whatever. For example #21.

How that happened? I saw some activity like a month ago, so this project doesn't look dead.

DOMNodeComparator swallows comments

In DOMNodeComparator::nodeToText we call $node->C14n(); without any parameters.

That results in all Comment (<!-- ... -->) nodes to be stripped.

I'd consider that a bug.

Given we still have #87, and maybe #71, we should probably have a look into how this comparator works :)

comparation fails for 0 = NULL

if ($expectedToCompare != $actualToCompare) {

if ($expectedToCompare != $actualToCompare)

will fail for

$expectedToCompare is int(0)
$actualToCompare is NULL

meaning assertEquals(0, NULL) returns OK

EDIT:

ScalarComparator's assertEquals() is used by cakePHP's integration test assertSession() when testing for a NULL value variable like

    public function test_null_is_zero()
    {
        $this->session(['lastErrorCode' => NULL]);
        $this->get('/');
        $this->assertSession((int)0, 'lastErrorCode');
    }

meaning this is not the same bug as #29

Float comparison in 4.0.8

In 4.0.7 and prior checking the equality of 1/3 vs 1 - 2/3 came out as true, upgrading to 4.0.8 however it now declares

SebastianBergmann\Comparator\ComparisonFailure : Failed asserting that 0.33333333333333337 matches expected 0.3333333333333333

$comparatorFactory = ComparatorFactory::getInstance();
$comparator = $comparatorFactory->getComparatorFor(1/3, 1 - (2/3));

$comparator->assertEquals(1/3, 1 - (2/3));

I could see this being an intentional change as it's arguably "more correct" but seems like a pretty major change for a 3rd point release.

[PHP 7.2 nightly] DOMNodeComparator::assertEquals() bad method signature

Hi @sebastianbergmann,

I hit an issue with the signature of DOMNodeComparator::assertEquals() and PHP 7.2 nightly found by Travis CI, it seems the arguments don't match with ObjectComparator::assertEquals():

Fatal error: Declaration of
SebastianBergmann\Comparator\DOMNodeComparator::assertEquals($expected, $actual, $delta = 0, $canonicalize = false, $ignoreCase = false)
must be compatible with
SebastianBergmann\Comparator\ObjectComparator::assertEquals($expected, $actual, $delta = 0, $canonicalize = false, $ignoreCase = false, array &$processed = Array)
in phar:///home/travis/.phpenv/versions/master/bin/phpunit/sebastian-comparator/DOMNodeComparator.php
on line 0

PHP and Composer versions:

$ php --version
PHP 7.2.0-dev (cli) (built: Jan 28 2017 22:46:30) ( ZTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.2.0-dev, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.2.0-dev, Copyright (c) 1999-2017, by Zend Technologies
$ composer --version
Composer version 1.3.2 2017-01-27 18:23:41

Warning with PHP 7.4

./vendor/bin/phpunit
PHP Warning:  Creating default object from empty value in /usr/local/src/comparator/tests/MockObjectComparatorTest.php on line 95
PHPUnit 9.0.1 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.4.3 with PCOV 1.0.6
Configuration: /usr/local/src/comparator/phpunit.xml

...............................................................  63 / 311 ( 20%)
............................................................... 126 / 311 ( 40%)
............................................................... 189 / 311 ( 60%)
............................................................... 252 / 311 ( 81%)
...........................................................     311 / 311 (100%)

Time: 66 ms, Memory: 8.00 MB

OK (311 tests, 402 assertions)

Honor $canonicalize parameter in `DOMNodeComparator::assertEquals`

The private method DOMNodeComparator::nodeToText can receive a $canonicalize flag to avoid re-loading a node.
This function is only called twice in assertEquals, and the class is final, so no descendants could override this behavior.

In DOMNodeComparator::assertEquals, nodeToText is called with an hardcoded true argument, rather than making use of the $canonicalize parameter that could be passed to it.

Moreover, \SebastianBergmann\Comparator\DOMNodeComparatorTest::testAssertEqualsSucceeds only tests the method with the default false value for the parameter.

Is there a practical reason for this? I tried searching in other issues and in the git history for the assertEquals method, but I found nothing useful.

As per a possible solution, I think it would be rather straightforward to change this current code in DOMNodeComparator::assertEquals

  $expectedAsString = $this->nodeToText($expected, true, $ignoreCase);
  $actualAsString   = $this->nodeToText($actual, true, $ignoreCase);

with

  $expectedAsString = $this->nodeToText($expected, $canonicalize, $ignoreCase);
  $actualAsString   = $this->nodeToText($actual, $canonicalize, $ignoreCase);

A new test case or a modification for the old one would be needed.

I could open a pull request if this is deemed the right solution and there is a need for it; I am not sure if this is correct behavior for a design choice, though.

Canonicalizing array comparator leaks notices

class TestTest extends \PHPUnit\Framework\TestCase {
    public function testEmitNotice(): void {
        $exp = [1, new \stdClass];
        $act = [1, new \stdClass];
        $this->assertEqualsCanonicalizing($exp, $act);
    }
}
PHPUnit 9.0.1 by Sebastian Bergmann and contributors.

PHP Notice:  Object of class stdClass could not be converted to int in ./vendor/sebastian/comparator/src/ArrayComparator.php on line 49
PHP Notice:  Object of class stdClass could not be converted to int in ./vendor/sebastian/comparator/src/ArrayComparator.php on line 50
.                                                                   1 / 1 (100%)

Time: 174 ms, Memory: 8.00 MB

OK (1 test, 1 assertion)

ArrayComparator ignores order

Even with $canonicalize = false.

$expected = [
	"first" => "lel",
	"middle" => "hurr",
	"last" => "lol",
];
$different = [  // just to make sure the assert checks the sorting.
	"first" => "lel",
	"last" => "lol",
	"middle" => "hurr",
];


$comparator = SebastianBergmann\Comparator\ArrayComparator();
$comparator->assertEquals($expected, $different);

This should fail. But it doesn't.

Error comparing orphan DOM nodes

Consider the following examples:

Two different objects, same orphan element:

$document   = new DOMDocument();

$node1      = $document->createElement('foo');
$node2      = $document->createElement('foo');

$comparator = new DOMNodeComparator();
$comparator->assertEquals($node1, $node2);

I get the error:

DOMDocument::loadXML(): Empty string supplied as input

Same object, same orphan element:

$document   = new DOMDocument();

$node       = $document->createElement('foo');

$comparator = new DOMNodeComparator();
$comparator->assertEquals($node, $node);

I get the error:

DOMDocument::loadXML(): Empty string supplied as input

Same object, same non-orphan element

$document   = new DOMDocument();

$node       = $document->createElement('foo');
$document->appendChild($node);

$comparator = new DOMNodeComparator();
$comparator->assertEquals($node, $node);

Success.

Two different objects, two non-orphan elements

$document   = new DOMDocument();

$node1      = $document->createElement('foo');
$document->appendChild($node1);

$node2      = $document->createElement('foo');
$document->appendChild($node2);

$comparator = new DOMNodeComparator();
$comparator->assertEquals($node1, $node2);

Success.

I think this is related to #10.

Array comparator should highlight the difference?

Thanks for this great library, Sebastian. I'm going to get PHPSpec to use the ArrayComparator. I think I'm missing something because it's not built-in but seems so essential... can't be just me?

Anyway, there are these lines in ArrayComparator:

try {
    $comparator = $this->factory->getComparatorFor($value, $actual[$key]);
    $comparator->assertEquals($value, $actual[$key], $delta, $canonicalize, $ignoreCase, $processed);

    $expectedAsString .= \sprintf(
            "    %s => %s\n",
            $this->exporter->export($key),
            $this->exporter->shortenedExport($value)
            );

    $actualAsString .= \sprintf(
            "    %s => %s\n",
            $this->exporter->export($key),
            $this->exporter->shortenedExport($actual[$key])
            );
} catch (ComparisonFailure $e) {
    $expectedAsString .= \sprintf(
            "    %s => %s\n",
            $this->exporter->export($key),
            $e->getExpectedAsString() ? $this->indent($e->getExpectedAsString()) : $this->exporter->shortenedExport($e->getExpected())
            );

    $actualAsString .= \sprintf(
            "    %s => %s\n",
            $this->exporter->export($key),
            $e->getActualAsString() ? $this->indent($e->getActualAsString()) : $this->exporter->shortenedExport($e->getActual())
            );

    $equal = false;
}

I'm wondering why the second (failure) set of $actualAsString and $expectedAsString assignments aren't decorated so that the output highlights which key/values aren't matching? Something like:

Array (
    'a' => 'b'
--->'c' => 'e'
)

I'm happy to try a PR, but I'm thinking this is too obvious to be an idea that hasn't been considered already...

Failed test on 32bits

ON x86_64

 PHPUnit 4.3.0 by Sebastian Bergmann.
 Configuration read from /builddir/build/BUILD/comparator-e54a01c0da1b87db3c5a3c4c5277ddf331da4aef/phpunit.xml.dist
 The Xdebug extension is not loaded. No code coverage will be generated.
 ...............................................................  63 / 293 ( 21%)
 ............................................................... 126 / 293 ( 43%)
 ............................................................... 189 / 293 ( 64%)
 ............................................................... 252 / 293 ( 86%)
 .........................................
 Time: 54 ms, Memory: 6.75Mb
 OK (293 tests, 370 assertions)

On i386

 PHPUnit 4.3.0 by Sebastian Bergmann.
 Configuration read from /builddir/build/BUILD/comparator-e54a01c0da1b87db3c5a3c4c5277ddf331da4aef/phpunit.xml.dist
 The Xdebug extension is not loaded. No code coverage will be generated.
 ...............................................................  63 / 293 ( 21%)
 ............................................................... 126 / 293 ( 43%)
 .......................................F....................... 189 / 293 ( 64%)
 ............................................................... 252 / 293 ( 86%)
 .........................................
 Time: 74 ms, Memory: 4.00Mb
 There was 1 failure:
 1) SebastianBergmann\Comparator\NumericComparatorTest::testAcceptsSucceeds with data set #3 (4106465292, 42)
 Failed asserting that false is true.
 /builddir/build/BUILD/comparator-e54a01c0da1b87db3c5a3c4c5277ddf331da4aef/tests/NumericComparatorTest.php:117
 FAILURES!
 Tests: 293, Assertions: 370, Failures: 1.

Unsuspected escaping non ASCI symbols in DOMDocuments comparing result

When i try to compare two DOMDocuments with russian symbols in PHPUnit (which uses this comparator) i have a problem.
Information about encoding lost while comparing documents and in result all russian symbols become encoded like this: <TagName>&#x41F;&#x43E;&#x43B;&#x44C;&#x437;&#x43E;&#x432;&#x430;&#x442;&#x435;&#x43B;&#x44C</TagName> instead of expected <TagName>ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒ</TagName>
Encoding information lost in DOMNodeComparator::nodeToText. You can see it here:

$xml = '<?xml version="1.0" encoding="utf-8"?><root>ั‚ะตัั‚</root>';
$document = new \DOMDocument;
$document->loadXML($xml);
echo("encoding: " . $document ->encoding . "\n"); // encoding: utf-8
echo("xml: " . $document ->saveXml() . "\n"); // xml: <?xml version="1.0" encoding="utf-8"? ><root>ั‚ะตัั‚</root>
$document->loadXML($document->C14N());
echo("encoding: " . $document ->encoding . "\n"); //encoding:
echo("xml: " . $document ->saveXml() . "\n"); // xml: <?xml version="1.0"? ><root>&#x442;&#x435;&#x441;&#x442;</root>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.