ALPHA 3.0.2a

This commit is contained in:
TheGamecraft
2018-09-10 08:51:18 -04:00
parent 7fe13ae0a7
commit 0e0ef86b71
1404 changed files with 10604 additions and 33714 deletions

View File

@@ -2,6 +2,7 @@
/.idea
/.php_cs
/.php_cs.cache
/.phpunit.result.cache
/build/documentation
/build/logfiles
/build/phar
@@ -11,10 +12,9 @@
/build/binary-phar-autoload.php
/cache.properties
/composer.lock
/tests/TextUI/*.diff
/tests/TextUI/*.exp
/tests/TextUI/*.log
/tests/TextUI/*.out
/tests/TextUI/*.php
/tests/end-to-end/*.diff
/tests/end-to-end/*.exp
/tests/end-to-end/*.log
/tests/end-to-end/*.out
/tests/end-to-end/*.php
/vendor

View File

@@ -58,7 +58,7 @@ jobs:
- travis_retry ./build/tools/composer require --no-update phpunit/php-invoker:^2.0
install: travis_retry ./build/tools/composer update --prefer-dist --prefer-stable
script:
- ./build/tools/phpstan analyse --level=0 src
- ./build/tools/phpstan analyse --level=0 -c phpstan.neon src
- ./build/tools/phpstan analyse --level=2 -c phpstan-tests.neon tests
- stage: Static Code Analysis
php: 7.2

View File

@@ -2,7 +2,30 @@
All notable changes of the PHPUnit 6.5 release series are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [6.5.9] - 2018-MM-DD
## [6.5.13] - 2018-09-08
* Fixed [#3181](https://github.com/sebastianbergmann/phpunit/issues/3181): `--filter` should be case-insensitive
* Fixed [#3234](https://github.com/sebastianbergmann/phpunit/issues/3234): `assertArraySubset()` with `$strict=true` does not display differences properly
* Fixed [#3254](https://github.com/sebastianbergmann/phpunit/issues/3254): TextUI test runner cannot run a `Test` instance that is not a `TestSuite`
## [6.5.12] - 2018-08-22
* Fixed [#3248](https://github.com/sebastianbergmann/phpunit/issues/3248) and [#3233](https://github.com/sebastianbergmann/phpunit/issues/3233): `phpunit.xsd` dictates element order where it should not
* Fixed [#3251](https://github.com/sebastianbergmann/phpunit/issues/3251): TeamCity result logger is missing test duration information
## [6.5.11] - 2018-08-07
* Fixed [#3219](https://github.com/sebastianbergmann/phpunit/issues/3219): `getMockFromWsdl()` generates invalid PHP code when WSDL filename contains special characters
## [6.5.10] - 2018-08-03
### Fixed
* Fixed [#3209](https://github.com/sebastianbergmann/phpunit/issues/3209): `Test::run()` and `TestCase::run()` interface contradiction
* Fixed [#3218](https://github.com/sebastianbergmann/phpunit/issues/3218): `prefix` attribute for `directory` node missing from `phpunit.xml` XSD
* Fixed [#3225](https://github.com/sebastianbergmann/phpunit/issues/3225): `coverage-php` missing from `phpunit.xsd`
## [6.5.9] - 2018-07-03
### Fixed
@@ -68,6 +91,10 @@ All notable changes of the PHPUnit 6.5 release series are documented in this fil
* Fixed [#2654](https://github.com/sebastianbergmann/phpunit/issues/2654): Problems with `assertJsonStringEqualsJsonString()`
* Fixed [#2810](https://github.com/sebastianbergmann/phpunit/pull/2810): Code Coverage for PHPT tests does not work
[6.5.13]: https://github.com/sebastianbergmann/phpunit/compare/6.5.12...6.5.13
[6.5.12]: https://github.com/sebastianbergmann/phpunit/compare/6.5.11...6.5.12
[6.5.11]: https://github.com/sebastianbergmann/phpunit/compare/6.5.10...6.5.11
[6.5.10]: https://github.com/sebastianbergmann/phpunit/compare/6.5.9...6.5.10
[6.5.9]: https://github.com/sebastianbergmann/phpunit/compare/6.5.8...6.5.9
[6.5.8]: https://github.com/sebastianbergmann/phpunit/compare/6.5.7...6.5.8
[6.5.7]: https://github.com/sebastianbergmann/phpunit/compare/6.5.6...6.5.7

View File

@@ -2,6 +2,14 @@
All notable changes of the PHPUnit 7.2 release series are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [7.2.7] - 2018-07-15
### Fixed
* Fixed [#3154](https://github.com/sebastianbergmann/phpunit/issues/3154): Global constants as default parameter values are not handled correctly in namespace
* Fixed [#3189](https://github.com/sebastianbergmann/phpunit/issues/3189): PHPUnit 7.2 potentially leaves a messy libxmlerror state
* Fixed [#3199](https://github.com/sebastianbergmann/phpunit/pull/3199): Code Coverage for PHPT tests does not work when PHPDBG is used
## [7.2.6] - 2018-06-21
### Fixed
@@ -59,6 +67,7 @@ All notable changes of the PHPUnit 7.2 release series are documented in this fil
* Fixed [#3069](https://github.com/sebastianbergmann/phpunit/issues/3069): Method `ResultPrinter::printWaitPrompt()` seems to be unused
[7.2.7]: https://github.com/sebastianbergmann/phpunit/compare/7.2.6...7.2.7
[7.2.6]: https://github.com/sebastianbergmann/phpunit/compare/7.2.5...7.2.6
[7.2.5]: https://github.com/sebastianbergmann/phpunit/compare/7.2.4...7.2.5
[7.2.4]: https://github.com/sebastianbergmann/phpunit/compare/7.2.3...7.2.4

View File

@@ -4,16 +4,16 @@ PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of
[![Latest Stable Version](https://img.shields.io/packagist/v/phpunit/phpunit.svg?style=flat-square)](https://packagist.org/packages/phpunit/phpunit)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.1-8892BF.svg?style=flat-square)](https://php.net/)
[![Build Status](https://img.shields.io/travis/sebastianbergmann/7.2/master.svg?style=flat-square)](https://phpunit.de/build-status.html)
[![Build Status](https://img.shields.io/travis/sebastianbergmann/phpunit/7.3.svg?style=flat-square)](https://phpunit.de/build-status.html)
## Installation
We distribute a [PHP Archive (PHAR)](https://php.net/phar) that has all required (as well as some optional) dependencies of PHPUnit 7.2 bundled in a single file:
We distribute a [PHP Archive (PHAR)](https://php.net/phar) that has all required (as well as some optional) dependencies of PHPUnit 7.3 bundled in a single file:
```bash
$ wget https://phar.phpunit.de/phpunit-7.2.phar
$ wget https://phar.phpunit.de/phpunit-7.3.phar
$ php phpunit-7.2.phar --version
$ php phpunit-7.3.phar --version
```
Alternatively, you may use [Composer](https://getcomposer.org/) to download and install PHPUnit as well as its dependencies. Please refer to the "[Getting Started](https://phpunit.de/getting-started-with-phpunit.html)" guide for details on how to install PHPUnit.

View File

@@ -127,7 +127,7 @@
<copy file="${basedir}/phpunit.xsd" tofile="${basedir}/build/phar/phpunit.xsd"/>
<exec executable="${basedir}/build/phar-manifest.php" output="${basedir}/build/phar/manifest.txt"/>
<exec executable="${basedir}/build/phar-manifest.php" output="${basedir}/build/phar/manifest.txt" failonerror="true"/>
<copy file="${basedir}/vendor/phpunit/php-code-coverage/LICENSE" tofile="${basedir}/build/phar/php-code-coverage/LICENSE"/>
<copy todir="${basedir}/build/phar/php-code-coverage">
@@ -326,12 +326,12 @@
</fileset>
</copy>
<exec executable="${basedir}/build/phar-version.php" outputproperty="_version">
<exec executable="${basedir}/build/phar-version.php" outputproperty="_version" failonerror="true">
<arg value="${version}"/>
<arg value="${type}"/>
</exec>
<exec executable="${basedir}/build/tools/phpab" taskname="phpab">
<exec executable="${basedir}/build/tools/phpab" taskname="phpab" failonerror="true">
<arg value="--all" />
<arg value="--static" />
<arg value="--once" />
@@ -348,7 +348,7 @@
<copy file="${basedir}/build/binary-phar-autoload.php.in" tofile="${basedir}/build/binary-phar-autoload.php"/>
<replace file="${basedir}/build/binary-phar-autoload.php" token="X.Y.Z" value="${_version}"/>
<exec executable="${basedir}/build/tools/phpab" taskname="phpab">
<exec executable="${basedir}/build/tools/phpab" taskname="phpab" failonerror="true">
<arg value="--all" />
<arg value="--nolower" />
<arg value="--static" />
@@ -369,7 +369,7 @@
</target>
<target name="-phar-determine-version">
<exec executable="${basedir}/build/version.php" outputproperty="version" />
<exec executable="${basedir}/build/version.php" outputproperty="version" failonerror="true" />
</target>
<target name="generate-project-documentation" depends="-phploc,-checkstyle,-phpunit">

View File

@@ -29,8 +29,8 @@
"ext-xml": "*",
"doctrine/instantiator": "^1.1",
"myclabs/deep-copy": "^1.7",
"phar-io/manifest": "^1.0.1",
"phar-io/version": "^1.0",
"phar-io/manifest": "^1.0.2",
"phar-io/version": "^2.0",
"phpspec/prophecy": "^1.7",
"phpunit/php-code-coverage": "^6.0.7",
"phpunit/php-file-iterator": "^2.0.1",
@@ -84,7 +84,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "7.2-dev"
"dev-master": "7.3-dev"
}
}
}

View File

@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<phive xmlns="https://phar.io/phive">
<phar name="phpab" version="^1.24.1" installed="1.24.1" location="./build/tools/phpab" copy="true"/>
<phar name="php-cs-fixer" version="^2.12.0" installed="2.12.1" location="./build/tools/php-cs-fixer" copy="true"/>
<phar name="phpab" version="^1.24.1" installed="1.25.0" location="./build/tools/phpab" copy="true"/>
<phar name="php-cs-fixer" version="^2.12.0" installed="2.13.0" location="./build/tools/php-cs-fixer" copy="true"/>
<phar name="phpdox" version="^0.11.2" installed="0.11.2" location="./build/tools/phpdox" copy="true"/>
<phar name="phploc" version="^4.0.1" installed="4.0.1" location="./build/tools/phploc" copy="true"/>
<phar name="phpstan" version="^0.10.1" installed="0.10.1" location="./build/tools/phpstan" copy="true"/>
</phive>

View File

@@ -1,5 +1,8 @@
parameters:
ignoreErrors:
# https://github.com/phpstan/phpstan/issues/1185
- '#Function xdebug_disable not found.#'
# parent calls are intentionally omitted
- '#Issue244Exception::__construct\(\) does not call parent constructor from Exception.#'
- '#Issue244ExceptionIntCode::__construct\(\) does not call parent constructor from Exception.#'
@@ -41,6 +44,7 @@ parameters:
- '#Result of method ClassWithAllPossibleReturnTypes::methodWithVoidReturnTypeDeclaration\(\) \(void\) is used#'
excludes_analyse:
# duplicated classname OneTest
- tests/_files/phpunit-example-extension/tests/OneTest.php
- tests/Regression/Trac/783/OneTest.php
- tests/end-to-end/regression/Trac/783/OneTest.php
- tests/_files/3194.php
- tests/_files/RouterTest.php

View File

@@ -2,18 +2,15 @@
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="phpunit.xsd"
bootstrap="tests/bootstrap.php"
cacheResult="true"
verbose="true">
<testsuites>
<testsuite name="small">
<directory>tests/Framework</directory>
<directory>tests/Runner</directory>
<directory>tests/Util</directory>
<testsuite name="unit">
<directory suffix="Test.php">tests/unit</directory>
</testsuite>
<testsuite name="large">
<directory suffix=".phpt">tests/Framework/MockObject/Generator</directory>
<directory suffix=".phpt">tests/TextUI</directory>
<directory suffix=".phpt">tests/Regression</directory>
<testsuite name="end-to-end">
<directory suffix=".phpt">tests/end-to-end</directory>
</testsuite>
</testsuites>

View File

@@ -1,288 +1,304 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:annotation>
<xs:documentation source="https://phpunit.de/documentation.html">
This Schema file defines the rules by which the XML configuration file of PHPUnit 7.2 may be structured.
</xs:documentation>
<xs:appinfo source="https://phpunit.de/documentation.html"/>
</xs:annotation>
<xs:element name="phpunit" type="phpUnitType">
<xs:annotation>
<xs:documentation>Root Element</xs:documentation>
<xs:documentation source="https://phpunit.de/documentation.html">
This Schema file defines the rules by which the XML configuration file of PHPUnit 7.3 may be structured.
</xs:documentation>
<xs:appinfo source="https://phpunit.de/documentation.html"/>
</xs:annotation>
</xs:element>
<xs:complexType name="filtersType">
<xs:sequence>
<xs:element name="whitelist" type="whiteListType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="filterType">
<xs:sequence>
<xs:group ref="pathGroup"/>
<xs:element name="exclude" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:group ref="pathGroup"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="whiteListType">
<xs:complexContent>
<xs:extension base="filterType">
<xs:attribute name="addUncoveredFilesFromWhitelist" default="true" type="xs:boolean"/>
<xs:attribute name="processUncoveredFilesFromWhitelist" default="false" type="xs:boolean"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="groupsType">
<xs:choice>
<xs:sequence>
<xs:element name="include" type="groupType"/>
<xs:element name="exclude" type="groupType" minOccurs="0"/>
</xs:sequence>
<xs:sequence>
<xs:element name="exclude" type="groupType"/>
</xs:sequence>
</xs:choice>
</xs:complexType>
<xs:complexType name="groupType">
<xs:sequence>
<xs:element name="group" type="xs:string" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="extensionsType">
<xs:sequence>
<xs:element name="extension" type="objectType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="listenersType">
<xs:sequence>
<xs:element name="listener" type="objectType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="objectType">
<xs:sequence>
<xs:element name="arguments" minOccurs="0">
<xs:complexType>
<xs:group ref="argumentsGroup"/>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="class" type="xs:string" use="required"/>
<xs:attribute name="file" type="xs:anyURI"/>
</xs:complexType>
<xs:complexType name="arrayType">
<xs:sequence>
<xs:element name="element" type="argumentType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="argumentType">
<xs:group ref="argumentChoice"/>
<xs:attribute name="key" use="required"/>
</xs:complexType>
<xs:group name="argumentsGroup">
<xs:sequence>
<xs:element name="array" type="arrayType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="integer" type="xs:integer" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="string" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="double" type="xs:double" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="null" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="object" type="objectType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="file" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="directory" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="boolean" type="xs:boolean" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:group>
<xs:group name="argumentChoice">
<xs:choice>
<xs:element name="array" type="arrayType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="integer" type="xs:integer" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="string" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="double" type="xs:double" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="null" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="object" type="objectType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="file" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="directory" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="boolean" type="xs:boolean" minOccurs="0" maxOccurs="unbounded"/>
</xs:choice>
</xs:group>
<xs:simpleType name="columnsType">
<xs:union>
<xs:simpleType>
<xs:restriction base="xs:integer"/>
</xs:simpleType>
<xs:simpleType>
<xs:element name="phpunit" type="phpUnitType">
<xs:annotation>
<xs:documentation>Root Element</xs:documentation>
</xs:annotation>
</xs:element>
<xs:complexType name="filtersType">
<xs:sequence>
<xs:element name="whitelist" type="whiteListType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="filterType">
<xs:sequence>
<xs:choice maxOccurs="unbounded" minOccurs="0">
<xs:group ref="pathGroup"/>
<xs:element name="exclude">
<xs:complexType>
<xs:group ref="pathGroup"/>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:complexType name="whiteListType">
<xs:complexContent>
<xs:extension base="filterType">
<xs:attribute name="addUncoveredFilesFromWhitelist" default="true" type="xs:boolean"/>
<xs:attribute name="processUncoveredFilesFromWhitelist" default="false" type="xs:boolean"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="groupsType">
<xs:choice>
<xs:sequence>
<xs:element name="include" type="groupType"/>
<xs:element name="exclude" type="groupType" minOccurs="0"/>
</xs:sequence>
<xs:sequence>
<xs:element name="exclude" type="groupType"/>
</xs:sequence>
</xs:choice>
</xs:complexType>
<xs:complexType name="groupType">
<xs:sequence>
<xs:element name="group" type="xs:string" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="extensionsType">
<xs:sequence>
<xs:element name="extension" type="objectType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="listenersType">
<xs:sequence>
<xs:element name="listener" type="objectType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="objectType">
<xs:sequence>
<xs:element name="arguments" minOccurs="0">
<xs:complexType>
<xs:group ref="argumentsGroup"/>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="class" type="xs:string" use="required"/>
<xs:attribute name="file" type="xs:anyURI"/>
</xs:complexType>
<xs:complexType name="arrayType">
<xs:sequence>
<xs:element name="element" type="argumentType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="argumentType">
<xs:group ref="argumentChoice"/>
<xs:attribute name="key" use="required"/>
</xs:complexType>
<xs:group name="argumentsGroup">
<xs:sequence>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="array" type="arrayType" />
<xs:element name="integer" type="xs:integer" />
<xs:element name="string" type="xs:string" />
<xs:element name="double" type="xs:double" />
<xs:element name="null" />
<xs:element name="object" type="objectType" />
<xs:element name="file" type="xs:anyURI" />
<xs:element name="directory" type="xs:anyURI" />
<xs:element name="boolean" type="xs:boolean" />
</xs:choice>
</xs:sequence>
</xs:group>
<xs:group name="argumentChoice">
<xs:choice>
<xs:element name="array" type="arrayType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="integer" type="xs:integer" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="string" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="double" type="xs:double" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="null" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="object" type="objectType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="file" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="directory" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="boolean" type="xs:boolean" minOccurs="0" maxOccurs="unbounded"/>
</xs:choice>
</xs:group>
<xs:simpleType name="columnsType">
<xs:union>
<xs:simpleType>
<xs:restriction base="xs:integer"/>
</xs:simpleType>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="max"/>
</xs:restriction>
</xs:simpleType>
</xs:union>
</xs:simpleType>
<xs:complexType name="loggersType">
<xs:sequence>
<xs:element name="log" type="loggerType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="loggerType">
<xs:attribute name="type">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="coverage-html"/>
<xs:enumeration value="coverage-text"/>
<xs:enumeration value="coverage-clover"/>
<xs:enumeration value="coverage-crap4j"/>
<xs:enumeration value="coverage-xml"/>
<xs:enumeration value="coverage-php"/>
<xs:enumeration value="json"/>
<xs:enumeration value="plain"/>
<xs:enumeration value="tap"/>
<xs:enumeration value="teamcity"/>
<xs:enumeration value="junit"/>
<xs:enumeration value="testdox-html"/>
<xs:enumeration value="testdox-text"/>
<xs:enumeration value="testdox-xml"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="target" type="xs:anyURI"/>
<xs:attribute name="lowUpperBound" type="xs:nonNegativeInteger" default="35"/>
<xs:attribute name="highLowerBound" type="xs:nonNegativeInteger" default="70"/>
<xs:attribute name="showUncoveredFiles" type="xs:boolean" default="false"/>
<xs:attribute name="showOnlySummary" type="xs:boolean" default="false"/>
<xs:attribute name="threshold" type="xs:nonNegativeInteger" default="30"/>
</xs:complexType>
<xs:group name="pathGroup">
<xs:sequence>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="directory" type="directoryFilterType"/>
<xs:element name="file" type="fileFilterType"/>
</xs:choice>
</xs:sequence>
</xs:group>
<xs:complexType name="directoryFilterType">
<xs:simpleContent>
<xs:extension base="xs:anyURI">
<xs:attribute type="xs:string" name="prefix" default=""/>
<xs:attribute type="xs:string" name="suffix" default="Test.php"/>
<xs:attributeGroup ref="phpVersionGroup"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:simpleType name="executionOrderType">
<xs:restriction base="xs:string">
<xs:enumeration value="max"/>
<xs:enumeration value="default"/>
<xs:enumeration value="defects"/>
<xs:enumeration value="depends"/>
<xs:enumeration value="depends,defects"/>
<xs:enumeration value="random"/>
<xs:enumeration value="reverse"/>
<xs:enumeration value="depends,random"/>
<xs:enumeration value="depends,reverse"/>
</xs:restriction>
</xs:simpleType>
</xs:union>
</xs:simpleType>
<xs:complexType name="loggersType">
<xs:sequence>
<xs:element name="log" type="loggerType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="loggerType">
<xs:attribute name="type">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="coverage-html"/>
<xs:enumeration value="coverage-text"/>
<xs:enumeration value="coverage-clover"/>
<xs:enumeration value="coverage-crap4j"/>
<xs:enumeration value="coverage-xml"/>
<xs:enumeration value="json"/>
<xs:enumeration value="plain"/>
<xs:enumeration value="tap"/>
<xs:enumeration value="teamcity"/>
<xs:enumeration value="junit"/>
<xs:enumeration value="testdox-html"/>
<xs:enumeration value="testdox-text"/>
<xs:enumeration value="testdox-xml"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="target" type="xs:anyURI"/>
<xs:attribute name="lowUpperBound" type="xs:nonNegativeInteger" default="35"/>
<xs:attribute name="highLowerBound" type="xs:nonNegativeInteger" default="70"/>
<xs:attribute name="showUncoveredFiles" type="xs:boolean" default="false"/>
<xs:attribute name="showOnlySummary" type="xs:boolean" default="false"/>
<xs:attribute name="threshold" type="xs:nonNegativeInteger" default="30"/>
</xs:complexType>
<xs:group name="pathGroup">
<xs:sequence>
<xs:element name="directory" type="directoryFilterType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="file" type="fileFilterType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:group>
<xs:complexType name="directoryFilterType">
<xs:simpleContent>
<xs:extension base="xs:anyURI">
<xs:attribute type="xs:string" name="suffix" default="Test.php"/>
<xs:attributeGroup ref="phpVersionGroup"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:simpleType name="executionOrderType">
<xs:restriction base="xs:string">
<xs:enumeration value="default"/>
<xs:enumeration value="reverse"/>
<xs:enumeration value="random"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="fileFilterType">
<xs:simpleContent>
<xs:extension base="xs:anyURI">
<xs:attributeGroup ref="phpVersionGroup"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:attributeGroup name="phpVersionGroup">
<xs:attribute name="phpVersion" type="xs:string" default="5.3.0"/>
<xs:attribute name="phpVersionOperator" type="xs:string" default="&gt;="/>
</xs:attributeGroup>
<xs:complexType name="phpType">
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="includePath" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="ini" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="const" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="var" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="env" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="post" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="get" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="cookie" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="server" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="files" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="request" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:complexType name="namedValueType">
<xs:attribute name="name" use="required" type="xs:string"/>
<xs:attribute name="value" use="required" type="xs:anySimpleType"/>
<xs:attribute name="verbatim" use="optional" type="xs:boolean"/>
<xs:attribute name="force" use="optional" type="xs:boolean"/>
</xs:complexType>
<xs:complexType name="phpUnitType">
<xs:annotation>
<xs:documentation>The main type specifying the document structure</xs:documentation>
</xs:annotation>
<xs:group ref="configGroup"/>
<xs:attributeGroup ref="configAttributeGroup"/>
</xs:complexType>
<xs:attributeGroup name="configAttributeGroup">
<xs:attribute name="backupGlobals" type="xs:boolean" default="false"/>
<xs:attribute name="backupStaticAttributes" type="xs:boolean" default="false"/>
<xs:attribute name="bootstrap" type="xs:anyURI"/>
<xs:attribute name="cacheTokens" type="xs:boolean"/>
<xs:attribute name="colors" type="xs:boolean" default="false"/>
<xs:attribute name="columns" type="columnsType" default="80"/>
<xs:attribute name="convertDeprecationsToExceptions" type="xs:boolean" default="true"/>
<xs:attribute name="convertErrorsToExceptions" type="xs:boolean" default="true"/>
<xs:attribute name="convertNoticesToExceptions" type="xs:boolean" default="true"/>
<xs:attribute name="convertWarningsToExceptions" type="xs:boolean" default="true"/>
<xs:attribute name="disableCodeCoverageIgnore" type="xs:boolean" default="false"/>
<xs:attribute name="forceCoversAnnotation" type="xs:boolean" default="false"/>
<xs:attribute name="printerClass" type="xs:string" default="PHPUnit\TextUI\ResultPrinter"/>
<xs:attribute name="printerFile" type="xs:anyURI"/>
<xs:attribute name="processIsolation" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnError" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnFailure" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnWarning" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnIncomplete" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnRisky" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnSkipped" type="xs:boolean" default="false"/>
<xs:attribute name="failOnRisky" type="xs:boolean" default="false"/>
<xs:attribute name="failOnWarning" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutChangesToGlobalState" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutOutputDuringTests" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutResourceUsageDuringSmallTests" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutTestsThatDoNotTestAnything" type="xs:boolean" default="true"/>
<xs:attribute name="beStrictAboutTodoAnnotatedTests" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutCoversAnnotation" type="xs:boolean" default="false"/>
<xs:attribute name="enforceTimeLimit" type="xs:boolean" default="false"/>
<xs:attribute name="ignoreDeprecatedCodeUnitsFromCodeCoverage" type="xs:boolean" default="false"/>
<xs:attribute name="timeoutForSmallTests" type="xs:integer" default="1"/>
<xs:attribute name="timeoutForMediumTests" type="xs:integer" default="10"/>
<xs:attribute name="timeoutForLargeTests" type="xs:integer" default="60"/>
<xs:attribute name="testSuiteLoaderClass" type="xs:string" default="PHPUnit\Runner\StandardTestSuiteLoader"/>
<xs:attribute name="testSuiteLoaderFile" type="xs:anyURI"/>
<xs:attribute name="defaultTestSuite" type="xs:string" default=""/>
<xs:attribute name="verbose" type="xs:boolean" default="false"/>
<xs:attribute name="stderr" type="xs:boolean" default="false"/>
<xs:attribute name="reverseDefectList" type="xs:boolean" default="false"/>
<xs:attribute name="registerMockObjectsFromTestArgumentsRecursively" type="xs:boolean" default="false"/>
<xs:attribute name="extensionsDirectory" type="xs:string"/>
<xs:attribute name="executionOrder" type="executionOrderType" default="default"/>
<xs:attribute name="resolveDependencies" type="xs:boolean" default="false"/>
</xs:attributeGroup>
<xs:group name="configGroup">
<xs:all>
<xs:element ref="testSuiteFacet" minOccurs="0"/>
<xs:element name="groups" type="groupsType" minOccurs="0"/>
<xs:element name="testdoxGroups" type="groupsType" minOccurs="0"/>
<xs:element name="filter" type="filtersType" minOccurs="0"/>
<xs:element name="logging" type="loggersType" minOccurs="0"/>
<xs:element name="extensions" type="extensionsType" minOccurs="0"/>
<xs:element name="listeners" type="listenersType" minOccurs="0"/>
<xs:element name="php" type="phpType" minOccurs="0"/>
</xs:all>
</xs:group>
<xs:element name="testSuiteFacet" abstract="true"/>
<xs:element name="testsuite" type="testSuiteType" substitutionGroup="testSuiteFacet"/>
<xs:element name="testsuites" type="testSuitesType" substitutionGroup="testSuiteFacet"/>
<xs:complexType name="testSuitesType">
<xs:sequence>
<xs:element name="testsuite" type="testSuiteType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="testSuiteType">
<xs:sequence>
<xs:group ref="pathGroup"/>
<xs:element name="exclude" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
</xs:simpleType>
<xs:complexType name="fileFilterType">
<xs:simpleContent>
<xs:extension base="xs:anyURI">
<xs:attributeGroup ref="phpVersionGroup"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:attributeGroup name="phpVersionGroup">
<xs:attribute name="phpVersion" type="xs:string" default="5.3.0"/>
<xs:attribute name="phpVersionOperator" type="xs:string" default="&gt;="/>
</xs:attributeGroup>
<xs:complexType name="phpType">
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="includePath" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="ini" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="const" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="var" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="env" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="post" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="get" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="cookie" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="server" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="files" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="request" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:complexType name="namedValueType">
<xs:attribute name="name" use="required" type="xs:string"/>
<xs:attribute name="value" use="required" type="xs:anySimpleType"/>
<xs:attribute name="verbatim" use="optional" type="xs:boolean"/>
<xs:attribute name="force" use="optional" type="xs:boolean"/>
</xs:complexType>
<xs:complexType name="phpUnitType">
<xs:annotation>
<xs:documentation>The main type specifying the document structure</xs:documentation>
</xs:annotation>
<xs:group ref="configGroup"/>
<xs:attributeGroup ref="configAttributeGroup"/>
</xs:complexType>
<xs:attributeGroup name="configAttributeGroup">
<xs:attribute name="backupGlobals" type="xs:boolean" default="false"/>
<xs:attribute name="backupStaticAttributes" type="xs:boolean" default="false"/>
<xs:attribute name="bootstrap" type="xs:anyURI"/>
<xs:attribute name="cacheResult" type="xs:boolean" default="false"/>
<xs:attribute name="cacheResultFile" type="xs:anyURI"/>
<xs:attribute name="cacheTokens" type="xs:boolean"/>
<xs:attribute name="colors" type="xs:boolean" default="false"/>
<xs:attribute name="columns" type="columnsType" default="80"/>
<xs:attribute name="convertDeprecationsToExceptions" type="xs:boolean" default="true"/>
<xs:attribute name="convertErrorsToExceptions" type="xs:boolean" default="true"/>
<xs:attribute name="convertNoticesToExceptions" type="xs:boolean" default="true"/>
<xs:attribute name="convertWarningsToExceptions" type="xs:boolean" default="true"/>
<xs:attribute name="disableCodeCoverageIgnore" type="xs:boolean" default="false"/>
<xs:attribute name="forceCoversAnnotation" type="xs:boolean" default="false"/>
<xs:attribute name="printerClass" type="xs:string" default="PHPUnit\TextUI\ResultPrinter"/>
<xs:attribute name="printerFile" type="xs:anyURI"/>
<xs:attribute name="processIsolation" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnDefect" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnError" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnFailure" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnWarning" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnIncomplete" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnRisky" type="xs:boolean" default="false"/>
<xs:attribute name="stopOnSkipped" type="xs:boolean" default="false"/>
<xs:attribute name="failOnRisky" type="xs:boolean" default="false"/>
<xs:attribute name="failOnWarning" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutChangesToGlobalState" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutOutputDuringTests" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutResourceUsageDuringSmallTests" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutTestsThatDoNotTestAnything" type="xs:boolean" default="true"/>
<xs:attribute name="beStrictAboutTodoAnnotatedTests" type="xs:boolean" default="false"/>
<xs:attribute name="beStrictAboutCoversAnnotation" type="xs:boolean" default="false"/>
<xs:attribute name="enforceTimeLimit" type="xs:boolean" default="false"/>
<xs:attribute name="ignoreDeprecatedCodeUnitsFromCodeCoverage" type="xs:boolean" default="false"/>
<xs:attribute name="timeoutForSmallTests" type="xs:integer" default="1"/>
<xs:attribute name="timeoutForMediumTests" type="xs:integer" default="10"/>
<xs:attribute name="timeoutForLargeTests" type="xs:integer" default="60"/>
<xs:attribute name="testSuiteLoaderClass" type="xs:string" default="PHPUnit\Runner\StandardTestSuiteLoader"/>
<xs:attribute name="testSuiteLoaderFile" type="xs:anyURI"/>
<xs:attribute name="defaultTestSuite" type="xs:string" default=""/>
<xs:attribute name="verbose" type="xs:boolean" default="false"/>
<xs:attribute name="stderr" type="xs:boolean" default="false"/>
<xs:attribute name="reverseDefectList" type="xs:boolean" default="false"/>
<xs:attribute name="registerMockObjectsFromTestArgumentsRecursively" type="xs:boolean" default="false"/>
<xs:attribute name="extensionsDirectory" type="xs:string"/>
<xs:attribute name="executionOrder" type="executionOrderType" default="default"/>
<xs:attribute name="resolveDependencies" type="xs:boolean" default="false"/>
</xs:attributeGroup>
<xs:group name="configGroup">
<xs:all>
<xs:element ref="testSuiteFacet" minOccurs="0"/>
<xs:element name="groups" type="groupsType" minOccurs="0"/>
<xs:element name="testdoxGroups" type="groupsType" minOccurs="0"/>
<xs:element name="filter" type="filtersType" minOccurs="0"/>
<xs:element name="logging" type="loggersType" minOccurs="0"/>
<xs:element name="extensions" type="extensionsType" minOccurs="0"/>
<xs:element name="listeners" type="listenersType" minOccurs="0"/>
<xs:element name="php" type="phpType" minOccurs="0"/>
</xs:all>
</xs:group>
<xs:element name="testSuiteFacet" abstract="true"/>
<xs:element name="testsuite" type="testSuiteType" substitutionGroup="testSuiteFacet"/>
<xs:element name="testsuites" type="testSuitesType" substitutionGroup="testSuiteFacet"/>
<xs:complexType name="testSuitesType">
<xs:sequence>
<xs:element name="testsuite" type="testSuiteType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="testSuiteType">
<xs:sequence>
<xs:group ref="pathGroup"/>
<xs:element name="exclude" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
</xs:schema>

View File

@@ -60,7 +60,6 @@ use PHPUnit\Util\Xml;
use ReflectionClass;
use ReflectionException;
use ReflectionObject;
use ReflectionProperty;
use Traversable;
/**
@@ -288,8 +287,6 @@ abstract class Assert
/**
* Asserts that a haystack contains only values of a given type.
*
* @param null|bool $isNativeType
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
@@ -350,8 +347,6 @@ abstract class Assert
/**
* Asserts that a haystack does not contain only values of a given type.
*
* @param null|bool $isNativeType
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
@@ -1259,10 +1254,6 @@ abstract class Assert
*/
public static function assertSame($expected, $actual, string $message = ''): void
{
if (\is_bool($expected) && \is_bool($actual)) {
static::assertEquals($expected, $actual, $message);
}
static::assertThat(
$actual,
new IsIdentical($expected),
@@ -1791,14 +1782,14 @@ abstract class Assert
unset($tmp);
static::assertEquals(
static::assertSame(
$expectedElement->tagName,
$actualElement->tagName,
$message
);
if ($checkAttributes) {
static::assertEquals(
static::assertSame(
$expectedElement->attributes->length,
$actualElement->attributes->length,
\sprintf(
@@ -1832,7 +1823,7 @@ abstract class Assert
Xml::removeCharacterDataNodes($expectedElement);
Xml::removeCharacterDataNodes($actualElement);
static::assertEquals(
static::assertSame(
$expectedElement->childNodes->length,
$actualElement->childNodes->length,
\sprintf(
@@ -2355,30 +2346,25 @@ abstract class Assert
}
try {
$attribute = new ReflectionProperty($object, $attributeName);
} catch (ReflectionException $e) {
$reflector = new ReflectionObject($object);
while ($reflector = $reflector->getParentClass()) {
do {
try {
$attribute = $reflector->getProperty($attributeName);
break;
if (!$attribute || $attribute->isPublic()) {
return $object->$attributeName;
}
$attribute->setAccessible(true);
$value = $attribute->getValue($object);
$attribute->setAccessible(false);
return $value;
} catch (ReflectionException $e) {
}
}
}
if (isset($attribute)) {
if (!$attribute || $attribute->isPublic()) {
return $object->$attributeName;
}
$attribute->setAccessible(true);
$value = $attribute->getValue($object);
$attribute->setAccessible(false);
return $value;
} while ($reflector = $reflector->getParentClass());
} catch (ReflectionException $e) {
}
throw new Exception(

View File

@@ -157,8 +157,6 @@ function assertAttributeNotContains($needle, string $haystackAttributeName, $hay
/**
* Asserts that a haystack contains only values of a given type.
*
* @param null|bool $isNativeType
*
* @throws Exception
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
@@ -197,8 +195,6 @@ function assertAttributeContainsOnly(string $type, string $haystackAttributeName
/**
* Asserts that a haystack does not contain only values of a given type.
*
* @param null|bool $isNativeType
*
* @throws Exception
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException

View File

@@ -28,14 +28,14 @@ class ArraySubset extends Constraint
/**
* @var bool
*/
private $checkForObjectIdentity;
private $strict;
public function __construct(iterable $subset, bool $checkForObjectIdentity = false)
public function __construct(iterable $subset, bool $strict = false)
{
parent::__construct();
$this->checkForObjectIdentity = $checkForObjectIdentity;
$this->subset = $subset;
$this->strict = $strict;
$this->subset = $subset;
}
/**
@@ -64,7 +64,7 @@ class ArraySubset extends Constraint
$patched = \array_replace_recursive($other, $this->subset);
if ($this->checkForObjectIdentity) {
if ($this->strict) {
$result = $other === $patched;
} else {
$result = $other == $patched;
@@ -78,8 +78,8 @@ class ArraySubset extends Constraint
$f = new ComparisonFailure(
$patched,
$other,
\print_r($patched, true),
\print_r($other, true)
\var_export($patched, true),
\var_export($other, true)
);
$this->fail($other, $description, $f);

View File

@@ -75,38 +75,24 @@ class StringMatchesFormatDescription extends RegularExpression
private function createPatternFromFormat(string $string): string
{
$string = \preg_replace(
$string = \strtr(
\preg_quote($string, '/'),
[
'/(?<!%)%e/',
'/(?<!%)%s/',
'/(?<!%)%S/',
'/(?<!%)%a/',
'/(?<!%)%A/',
'/(?<!%)%w/',
'/(?<!%)%i/',
'/(?<!%)%d/',
'/(?<!%)%x/',
'/(?<!%)%f/',
'/(?<!%)%c/'
],
[
\str_replace('\\', '\\\\', '\\' . \DIRECTORY_SEPARATOR),
'[^\r\n]+',
'[^\r\n]*',
'.+',
'.*',
'\s*',
'[+-]?\d+',
'\d+',
'[0-9a-fA-F]+',
'[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?',
'.'
],
\preg_quote($string, '/')
'%%' => '%',
'%e' => '\\' . \DIRECTORY_SEPARATOR,
'%s' => '[^\r\n]+',
'%S' => '[^\r\n]*',
'%a' => '.+',
'%A' => '.*',
'%w' => '\s*',
'%i' => '[+-]?\d+',
'%d' => '\d+',
'%x' => '[0-9a-fA-F]+',
'%f' => '[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?',
'%c' => '.'
]
);
$string = \str_replace('%%', '%', $string);
return '/^' . $string . '$/s';
}

View File

@@ -102,8 +102,6 @@ class ExceptionWrapper extends Exception
* Method to contain static originalException to exclude it from stacktrace to prevent the stacktrace contents,
* which can be quite big, from being garbage-collected, thus blocking memory until shutdown.
* Approach works both for var_dump() and var_export() and print_r()
*
* @param null|Throwable $exceptionToStore
*/
private function originalException(Throwable $exceptionToStore = null): ?Throwable
{

View File

@@ -398,35 +398,38 @@ class Generator
\sort($type);
}
if ($mockClassName === '') {
$key = \md5(
\is_array($type) ? \implode('_', $type) : $type .
\serialize($methods) .
\serialize($callOriginalClone) .
\serialize($cloneArguments) .
\serialize($callOriginalMethods)
if ($mockClassName !== '') {
return $this->generateMock(
$type,
$methods,
$mockClassName,
$callOriginalClone,
$callAutoload,
$cloneArguments,
$callOriginalMethods
);
if (isset(self::$cache[$key])) {
return self::$cache[$key];
}
}
$mock = $this->generateMock(
$type,
$methods,
$mockClassName,
$callOriginalClone,
$callAutoload,
$cloneArguments,
$callOriginalMethods
$key = \md5(
\is_array($type) ? \implode('_', $type) : $type .
\serialize($methods) .
\serialize($callOriginalClone) .
\serialize($cloneArguments) .
\serialize($callOriginalMethods)
);
if (isset($key)) {
self::$cache[$key] = $mock;
if (!isset(self::$cache[$key])) {
self::$cache[$key] = $this->generateMock(
$type,
$methods,
$mockClassName,
$callOriginalClone,
$callAutoload,
$cloneArguments,
$callOriginalMethods
);
}
return $mock;
return self::$cache[$key];
}
/**
@@ -485,13 +488,13 @@ class Generator
}
}
$optionsBuffer = 'array(';
$optionsBuffer = '[';
foreach ($options as $key => $value) {
$optionsBuffer .= $key . ' => ' . $value;
}
$optionsBuffer .= ')';
$optionsBuffer .= ']';
$classTemplate = $this->getTemplate('wsdl_class.tpl');
$namespace = '';
@@ -1167,6 +1170,9 @@ class Generator
if ($value === null) {
$value = \var_export($parameter->getDefaultValue(), true);
} elseif (!\defined($value)) {
$rootValue = \preg_replace('/^.*\\\\/', '', $value);
$value = \defined($rootValue) ? $rootValue : $value;
}
$default = ' = ' . $value;

View File

@@ -88,9 +88,7 @@ class ConsecutiveParameters extends StatelessInvocation
*/
private function verifyInvocation(BaseInvocation $invocation, $callIndex): void
{
if (isset($this->parameterGroups[$callIndex])) {
$parameters = $this->parameterGroups[$callIndex];
} else {
if (!isset($this->parameterGroups[$callIndex])) {
// no parameter assertion for this call index
return;
}
@@ -101,6 +99,8 @@ class ConsecutiveParameters extends StatelessInvocation
);
}
$parameters = $this->parameterGroups[$callIndex];
if (\count($invocation->getParameters()) < \count($parameters)) {
throw new ExpectationFailedException(
\sprintf(

View File

@@ -177,8 +177,6 @@ class MockBuilder
/**
* Specifies the subset of methods to mock. Default is to mock none of them.
*
* @param null|array $methods
*
* @return MockBuilder
*/
public function setMethods(array $methods = null)

View File

@@ -894,17 +894,13 @@ abstract class TestCase extends Assert implements Test, SelfDescribing
}
}
} catch (Throwable $_e) {
if (!isset($e)) {
$e = $_e;
}
$e = $e ?? $_e;
}
try {
$this->stopOutputBuffering();
} catch (RiskyTestError $_e) {
if (!isset($e)) {
$e = $_e;
}
$e = $e ?? $_e;
}
if (isset($_e)) {
@@ -1121,6 +1117,14 @@ abstract class TestCase extends Assert implements Test, SelfDescribing
return $buffer;
}
/**
* Gets the data set of a TestCase.
*/
public function getProvidedData(): array
{
return $this->data;
}
/**
* Override to run the test and assert its state.
*
@@ -1144,52 +1148,48 @@ abstract class TestCase extends Assert implements Test, SelfDescribing
try {
$testResult = $this->{$this->name}(...\array_values($testArguments));
} catch (Throwable $t) {
$exception = $t;
}
if (isset($exception)) {
if ($this->checkExceptionExpectations($exception)) {
if ($this->expectedException !== null) {
$this->assertThat(
$exception,
new ExceptionConstraint(
$this->expectedException
)
);
}
if ($this->expectedExceptionMessage !== null) {
$this->assertThat(
$exception,
new ExceptionMessage(
$this->expectedExceptionMessage
)
);
}
if ($this->expectedExceptionMessageRegExp !== null) {
$this->assertThat(
$exception,
new ExceptionMessageRegularExpression(
$this->expectedExceptionMessageRegExp
)
);
}
if ($this->expectedExceptionCode !== null) {
$this->assertThat(
$exception,
new ExceptionCode(
$this->expectedExceptionCode
)
);
}
return;
} catch (Throwable $exception) {
if (!$this->checkExceptionExpectations($exception)) {
throw $exception;
}
throw $exception;
if ($this->expectedException !== null) {
$this->assertThat(
$exception,
new ExceptionConstraint(
$this->expectedException
)
);
}
if ($this->expectedExceptionMessage !== null) {
$this->assertThat(
$exception,
new ExceptionMessage(
$this->expectedExceptionMessage
)
);
}
if ($this->expectedExceptionMessageRegExp !== null) {
$this->assertThat(
$exception,
new ExceptionMessageRegularExpression(
$this->expectedExceptionMessageRegExp
)
);
}
if ($this->expectedExceptionCode !== null) {
$this->assertThat(
$exception,
new ExceptionCode(
$this->expectedExceptionCode
)
);
}
return;
}
if ($this->expectedException !== null) {
@@ -1447,7 +1447,8 @@ abstract class TestCase extends Assert implements Test, SelfDescribing
protected function getMockFromWsdl($wsdlFile, $originalClassName = '', $mockClassName = '', array $methods = [], $callOriginalConstructor = true, array $options = []): MockObject
{
if ($originalClassName === '') {
$originalClassName = \pathinfo(\basename(\parse_url($wsdlFile)['path']), \PATHINFO_FILENAME);
$fileName = \pathinfo(\basename(\parse_url($wsdlFile)['path']), \PATHINFO_FILENAME);
$originalClassName = \preg_replace('/[^a-zA-Z0-9_]/', '', $fileName);
}
if (!\class_exists($originalClassName)) {
@@ -1550,14 +1551,6 @@ abstract class TestCase extends Assert implements Test, SelfDescribing
return $this->getProphet()->prophesize($classOrInterface);
}
/**
* Gets the data set of a TestCase.
*/
protected function getProvidedData(): array
{
return $this->data;
}
/**
* Creates a default TestResult object.
*/

View File

@@ -179,11 +179,35 @@ class TestResult implements Countable
*/
protected $lastTestFailed = false;
/**
* @var bool
*/
private $stopOnDefect = false;
/**
* @var bool
*/
private $registerMockObjectsFromTestArgumentsRecursively = false;
public static function isAnyCoverageRequired(TestCase $test)
{
$annotations = $test->getAnnotations();
// If any methods have covers, coverage must me generated
if (isset($annotations['method']['covers'])) {
return true;
}
// If there are no explicit covers, and the test class is
// marked as covers nothing, all coverage can be skipped
if (isset($annotations['class']['coversNothing'])) {
return false;
}
// Otherwise each test method can generate coverage
return true;
}
/**
* Registers a TestListener.
*/
@@ -229,7 +253,7 @@ class TestResult implements Countable
$test->markAsRisky();
}
if ($this->stopOnRisky) {
if ($this->stopOnRisky || $this->stopOnDefect) {
$this->stop();
}
} elseif ($t instanceof IncompleteTest) {
@@ -274,7 +298,7 @@ class TestResult implements Countable
*/
public function addWarning(Test $test, Warning $e, float $time): void
{
if ($this->stopOnWarning) {
if ($this->stopOnWarning || $this->stopOnDefect) {
$this->stop();
}
@@ -301,7 +325,7 @@ class TestResult implements Countable
$test->markAsRisky();
}
if ($this->stopOnRisky) {
if ($this->stopOnRisky || $this->stopOnDefect) {
$this->stop();
}
} elseif ($e instanceof IncompleteTest) {
@@ -322,7 +346,7 @@ class TestResult implements Countable
$this->failures[] = new TestFailure($test, $e);
$notifyMethod = 'addFailure';
if ($this->stopOnFailure) {
if ($this->stopOnFailure || $this->stopOnDefect) {
$this->stop();
}
}
@@ -566,11 +590,7 @@ class TestResult implements Countable
$this->registerMockObjectsFromTestArgumentsRecursively
);
$annotations = $test->getAnnotations();
if (isset($annotations['class']['coversNothing']) || isset($annotations['method']['coversNothing'])) {
$coversNothing = true;
}
$isAnyCoverageRequired = self::isAnyCoverageRequired($test);
}
$error = false;
@@ -599,7 +619,7 @@ class TestResult implements Countable
$collectCodeCoverage = $this->codeCoverage !== null &&
!$test instanceof WarningTestCase &&
!$coversNothing;
$isAnyCoverageRequired;
if ($collectCodeCoverage) {
$this->codeCoverage->start($test);
@@ -792,9 +812,7 @@ class TestResult implements Countable
} catch (OriginalCodeCoverageException $cce) {
$error = true;
if (!isset($e)) {
$e = $cce;
}
$e = $e ?? $cce;
}
}
@@ -811,11 +829,19 @@ class TestResult implements Countable
} elseif ($this->beStrictAboutTestsThatDoNotTestAnything &&
!$test->doesNotPerformAssertions() &&
$test->getNumAssertions() == 0) {
$reflected = new \ReflectionClass($test);
$name = $test->getName(false);
if ($name && $reflected->hasMethod($name)) {
$reflected = $reflected->getMethod($name);
}
$this->addFailure(
$test,
new RiskyTestError(
'This test did not perform any assertions'
),
new RiskyTestError(\sprintf(
"This test did not perform any assertions\n\n%s:%d",
$reflected->getFileName(),
$reflected->getStartLine()
)),
$time
);
} elseif ($this->beStrictAboutTestsThatDoNotTestAnything &&
@@ -1011,6 +1037,14 @@ class TestResult implements Countable
$this->stopOnSkipped = $flag;
}
/**
* Enables or disables the stopping for defects: error, failure, warning
*/
public function stopOnDefect(bool $flag): void
{
$this->stopOnDefect = $flag;
}
/**
* Returns the time spent running the tests.
*/

View File

@@ -141,136 +141,127 @@ class TestSuite implements Test, SelfDescribing, IteratorAggregate
$constructor = $theClass->getConstructor();
if ($constructor !== null) {
$parameters = $constructor->getParameters();
// TestCase() or TestCase($name)
if (\count($parameters) < 2) {
$test = new $className;
} // TestCase($name, $data)
else {
try {
$data = \PHPUnit\Util\Test::getProvidedData(
$className,
$name
);
} catch (IncompleteTestError $e) {
$message = \sprintf(
'Test for %s::%s marked incomplete by data provider',
$className,
$name
);
$_message = $e->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::incompleteTest($className, $name, $message);
} catch (SkippedTestError $e) {
$message = \sprintf(
'Test for %s::%s skipped by data provider',
$className,
$name
);
$_message = $e->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::skipTest($className, $name, $message);
} catch (Throwable $_t) {
$t = $_t;
} catch (Exception $_t) {
$t = $_t;
}
if (isset($t)) {
$message = \sprintf(
'The data provider specified for %s::%s is invalid.',
$className,
$name
);
$_message = $t->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::warning($message);
}
// Test method with @dataProvider.
if (isset($data)) {
$test = new DataProviderTestSuite(
$className . '::' . $name
);
if (empty($data)) {
$data = self::warning(
\sprintf(
'No tests found in suite "%s".',
$test->getName()
)
);
}
$groups = \PHPUnit\Util\Test::getGroups($className, $name);
if ($data instanceof WarningTestCase ||
$data instanceof SkippedTestCase ||
$data instanceof IncompleteTestCase) {
$test->addTest($data, $groups);
} else {
foreach ($data as $_dataName => $_data) {
$_test = new $className($name, $_data, $_dataName);
/* @var TestCase $_test */
if ($runTestInSeparateProcess) {
$_test->setRunTestInSeparateProcess(true);
if ($preserveGlobalState !== null) {
$_test->setPreserveGlobalState($preserveGlobalState);
}
}
if ($runClassInSeparateProcess) {
$_test->setRunClassInSeparateProcess(true);
if ($preserveGlobalState !== null) {
$_test->setPreserveGlobalState($preserveGlobalState);
}
}
if ($backupSettings['backupGlobals'] !== null) {
$_test->setBackupGlobals(
$backupSettings['backupGlobals']
);
}
if ($backupSettings['backupStaticAttributes'] !== null) {
$_test->setBackupStaticAttributes(
$backupSettings['backupStaticAttributes']
);
}
$test->addTest($_test, $groups);
}
}
} else {
$test = new $className;
}
}
}
if (!isset($test)) {
if ($constructor === null) {
throw new Exception('No valid test provided.');
}
$parameters = $constructor->getParameters();
// TestCase() or TestCase($name)
if (\count($parameters) < 2) {
$test = new $className;
} // TestCase($name, $data)
else {
try {
$data = \PHPUnit\Util\Test::getProvidedData(
$className,
$name
);
} catch (IncompleteTestError $e) {
$message = \sprintf(
'Test for %s::%s marked incomplete by data provider',
$className,
$name
);
$_message = $e->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::incompleteTest($className, $name, $message);
} catch (SkippedTestError $e) {
$message = \sprintf(
'Test for %s::%s skipped by data provider',
$className,
$name
);
$_message = $e->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::skipTest($className, $name, $message);
} catch (Throwable $t) {
$message = \sprintf(
'The data provider specified for %s::%s is invalid.',
$className,
$name
);
$_message = $t->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::warning($message);
}
// Test method with @dataProvider.
if (isset($data)) {
$test = new DataProviderTestSuite(
$className . '::' . $name
);
if (empty($data)) {
$data = self::warning(
\sprintf(
'No tests found in suite "%s".',
$test->getName()
)
);
}
$groups = \PHPUnit\Util\Test::getGroups($className, $name);
if ($data instanceof WarningTestCase ||
$data instanceof SkippedTestCase ||
$data instanceof IncompleteTestCase) {
$test->addTest($data, $groups);
} else {
foreach ($data as $_dataName => $_data) {
$_test = new $className($name, $_data, $_dataName);
/* @var TestCase $_test */
if ($runTestInSeparateProcess) {
$_test->setRunTestInSeparateProcess(true);
if ($preserveGlobalState !== null) {
$_test->setPreserveGlobalState($preserveGlobalState);
}
}
if ($runClassInSeparateProcess) {
$_test->setRunClassInSeparateProcess(true);
if ($preserveGlobalState !== null) {
$_test->setPreserveGlobalState($preserveGlobalState);
}
}
if ($backupSettings['backupGlobals'] !== null) {
$_test->setBackupGlobals(
$backupSettings['backupGlobals']
);
}
if ($backupSettings['backupStaticAttributes'] !== null) {
$_test->setBackupStaticAttributes(
$backupSettings['backupStaticAttributes']
);
}
$test->addTest($_test, $groups);
}
}
} else {
$test = new $className;
}
}
if ($test instanceof TestCase) {
$test->setName($name);
@@ -725,13 +716,7 @@ class TestSuite implements Test, SelfDescribing, IteratorAggregate
$result->endTestSuite($this);
return $result;
} catch (Throwable $_t) {
$t = $_t;
} catch (Exception $_t) {
$t = $_t;
}
if (isset($t)) {
} catch (Throwable $t) {
$numTests = \count($this);
for ($i = 0; $i < $numTests; $i++) {

View File

@@ -12,7 +12,6 @@ namespace PHPUnit\Runner\Filter;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\WarningTestCase;
use PHPUnit\Util\RegularExpression;
use PHPUnit\Util\Test;
use RecursiveFilterIterator;
use RecursiveIterator;
@@ -51,12 +50,12 @@ class NameFilterIterator extends RecursiveFilterIterator
return true;
}
$tmp = Test::describe($test);
$tmp = \PHPUnit\Util\Test::describe($test);
if ($test instanceof WarningTestCase) {
$name = $test->getMessage();
} else {
if ($tmp[0] != '') {
if ($tmp[0] !== '') {
$name = \implode('::', $tmp);
} else {
$name = $tmp[1];
@@ -70,7 +69,7 @@ class NameFilterIterator extends RecursiveFilterIterator
$accepted = $set >= $this->filterMin && $set <= $this->filterMax;
}
return $accepted;
return (bool) $accepted;
}
/**
@@ -111,7 +110,7 @@ class NameFilterIterator extends RecursiveFilterIterator
// Escape delimiters in regular expression. Do NOT use preg_quote,
// to keep magic characters.
$filter = \sprintf('/%s/', \str_replace(
$filter = \sprintf('/%s/i', \str_replace(
'/',
'\\/',
$filter

View File

@@ -150,7 +150,7 @@ class PhptTestCase implements Test, SelfDescribing
}
if ($result->getCollectCodeCoverageInformation()) {
$this->renderForCoverage($settings);
$this->renderForCoverage($code);
}
Timer::start();
@@ -269,22 +269,18 @@ class PhptTestCase implements Test, SelfDescribing
foreach ($assertions as $sectionName => $sectionAssertion) {
if (isset($sections[$sectionName])) {
$sectionContent = \preg_replace('/\r\n/', "\n", \trim($sections[$sectionName]));
$assertion = $sectionAssertion;
$expected = $sectionName === 'EXPECTREGEX' ? "/{$sectionContent}/" : $sectionContent;
break;
if ($expected === null) {
throw new Exception('No PHPT expectation found');
}
Assert::$sectionAssertion($expected, $actual);
return;
}
}
if (!isset($assertion)) {
throw new Exception('No PHPT assertion found');
}
if (!isset($expected)) {
throw new Exception('No PHPT expectation found');
}
Assert::$assertion($expected, $actual);
throw new Exception('No PHPT assertion found');
}
/**
@@ -479,7 +475,7 @@ class PhptTestCase implements Test, SelfDescribing
private function getCoverageFiles(): array
{
$baseDir = \dirname($this->filename) . \DIRECTORY_SEPARATOR;
$baseDir = \dirname(\realpath($this->filename)) . \DIRECTORY_SEPARATOR;
$basename = \basename($this->filename, 'phpt');
return [
@@ -488,7 +484,7 @@ class PhptTestCase implements Test, SelfDescribing
];
}
private function renderForCoverage(array &$settings): void
private function renderForCoverage(string &$job): void
{
$files = $this->getCoverageFiles();
@@ -520,17 +516,12 @@ class PhptTestCase implements Test, SelfDescribing
'phar' => $phar,
'globals' => $globals,
'job' => $files['job'],
'coverageFile' => $files['coverage'],
'autoPrependFile' => \var_export(
!empty($settings['auto_prepend_file']) ? $settings['auto_prepend_file'] : false,
true
)
'coverageFile' => $files['coverage']
]
);
\file_put_contents($files['job'], $template->render());
$settings['auto_prepend_file'] = $files['job'];
\file_put_contents($files['job'], $job);
$job = $template->render();
}
private function cleanupForCoverage(): array
@@ -538,6 +529,10 @@ class PhptTestCase implements Test, SelfDescribing
$files = $this->getCoverageFiles();
$coverage = @\unserialize(\file_get_contents($files['coverage']));
if ($coverage === false) {
$coverage = [];
}
foreach ($files as $file) {
@\unlink($file);
}

View File

@@ -31,10 +31,43 @@ final class TestSuiteSorter
*/
public const ORDER_REVERSED = 2;
/**
* @var int
*/
public const ORDER_DEFECTS_FIRST = 3;
/**
* List of sorting weights for all test result codes. A higher number gives higher priority.
*/
private const DEFECT_SORT_WEIGHT = [
BaseTestRunner::STATUS_ERROR => 6,
BaseTestRunner::STATUS_FAILURE => 5,
BaseTestRunner::STATUS_WARNING => 4,
BaseTestRunner::STATUS_INCOMPLETE => 3,
BaseTestRunner::STATUS_RISKY => 2,
BaseTestRunner::STATUS_SKIPPED => 1,
BaseTestRunner::STATUS_UNKNOWN => 0
];
/**
* @var array<string, int> Associative array of (string => DEFECT_SORT_WEIGHT) elements
*/
private $defectSortOrder = [];
/**
* @var TestResultCacheInterface
*/
private $cache;
public function __construct(?TestResultCacheInterface $cache = null)
{
$this->cache = $cache ?? new NullTestResultCache;
}
/**
* @throws Exception
*/
public function reorderTestsInSuite(Test $suite, int $order, bool $resolveDependencies): void
public function reorderTestsInSuite(Test $suite, int $order, bool $resolveDependencies, int $orderDefects): void
{
if ($order !== self::ORDER_DEFAULT && $order !== self::ORDER_REVERSED && $order !== self::ORDER_RANDOMIZED) {
throw new Exception(
@@ -42,16 +75,26 @@ final class TestSuiteSorter
);
}
if ($suite instanceof TestSuite && !empty($suite->tests())) {
if ($orderDefects !== self::ORDER_DEFAULT && $orderDefects !== self::ORDER_DEFECTS_FIRST) {
throw new Exception(
'$orderDefects must be one of TestSuiteSorter::ORDER_DEFAULT, TestSuiteSorter::ORDER_DEFECTS_FIRST'
);
}
if ($suite instanceof TestSuite) {
foreach ($suite as $_suite) {
$this->reorderTestsInSuite($_suite, $order, $resolveDependencies);
$this->reorderTestsInSuite($_suite, $order, $resolveDependencies, $orderDefects);
}
$this->sort($suite, $order, $resolveDependencies);
if ($orderDefects === self::ORDER_DEFECTS_FIRST) {
$this->addSuiteToDefectSortOrder($suite);
}
$this->sort($suite, $order, $resolveDependencies, $orderDefects);
}
}
private function sort(TestSuite $suite, int $order, bool $resolveDependencies): void
private function sort(TestSuite $suite, int $order, bool $resolveDependencies, int $orderDefects): void
{
if (empty($suite->tests())) {
return;
@@ -63,16 +106,38 @@ final class TestSuiteSorter
$suite->setTests($this->randomize($suite->tests()));
}
if ($orderDefects === self::ORDER_DEFECTS_FIRST && $this->cache !== null) {
$suite->setTests($this->sortDefectsFirst($suite->tests()));
}
if ($resolveDependencies && !($suite instanceof DataProviderTestSuite) && $this->suiteOnlyContainsTests($suite)) {
$suite->setTests($this->resolveDependencies($suite->tests()));
}
}
private function addSuiteToDefectSortOrder(TestSuite $suite): void
{
$max = 0;
foreach ($suite->tests() as $test) {
if (!isset($this->defectSortOrder[$test->getName()])) {
$this->defectSortOrder[$test->getName()] = self::DEFECT_SORT_WEIGHT[$this->cache->getState($test->getName())];
$max = \max($max, $this->defectSortOrder[$test->getName()]);
}
}
$this->defectSortOrder[$suite->getName()] = $max;
}
private function suiteOnlyContainsTests(TestSuite $suite): bool
{
return \array_reduce($suite->tests(), function ($carry, $test) {
return $carry && ($test instanceof TestCase || $test instanceof DataProviderTestSuite);
}, true);
return \array_reduce(
$suite->tests(),
function ($carry, $test) {
return $carry && ($test instanceof TestCase || $test instanceof DataProviderTestSuite);
},
true
);
}
private function reverse(array $tests): array
@@ -87,6 +152,43 @@ final class TestSuiteSorter
return $tests;
}
private function sortDefectsFirst(array $tests): array
{
\usort(
$tests,
function ($left, $right) {
return $this->cmpDefectPriorityAndTime($left, $right);
}
);
return $tests;
}
/**
* Comparator callback function to sort tests for "reach failure as fast as possible":
* 1. sort tests by defect weight defined in self::DEFECT_SORT_WEIGHT
* 2. when tests are equally defective, sort the fastest to the front
* 3. do not reorder successful tests
*/
private function cmpDefectPriorityAndTime(Test $a, Test $b): int
{
$priorityA = $this->defectSortOrder[$a->getName()] ?? 0;
$priorityB = $this->defectSortOrder[$b->getName()] ?? 0;
if ($priorityB <=> $priorityA) {
// Sort defect weight descending
return $priorityB <=> $priorityA;
}
if ($priorityA || $priorityB) {
// Sort test duration ascending
return $this->cache->getTime($a->getName()) <=> $this->cache->getTime($b->getName());
}
// do not change execution order
return 0;
}
/**
* Reorder Tests within a TestCase in such a way as to resolve as many dependencies as possible.
* The algorithm will leave the tests in original running order when it can.
@@ -108,9 +210,12 @@ final class TestSuiteSorter
$i = 0;
do {
$todoNames = \array_map(function ($test) {
return $this->getNormalizedTestName($test);
}, $tests);
$todoNames = \array_map(
function ($test) {
return $this->getNormalizedTestName($test);
},
$tests
);
if (!$tests[$i]->hasDependencies() || empty(\array_intersect($this->getNormalizedDependencyNames($tests[$i]), $todoNames))) {
$newTestOrder = \array_merge($newTestOrder, \array_splice($tests, $i, 1));
@@ -150,11 +255,12 @@ final class TestSuiteSorter
$testClass = \get_class($test);
}
$names = \array_map(function ($name) use ($testClass) {
return \strpos($name, '::') === false
? $testClass . '::' . $name
: $name;
}, $test->getDependencies());
$names = \array_map(
function ($name) use ($testClass) {
return \strpos($name, '::') === false ? $testClass . '::' . $name : $name;
},
$test->getDependencies()
);
return $names;
}

View File

@@ -30,7 +30,7 @@ class Version
}
if (self::$version === null) {
$version = new VersionId('7.2.6', \dirname(__DIR__, 2));
$version = new VersionId('7.3.5', \dirname(__DIR__, 2));
self::$version = $version->getVersion();
}

View File

@@ -68,6 +68,8 @@ class Command
protected $longOptions = [
'atleast-version=' => null,
'bootstrap=' => null,
'cache-result' => null,
'cache-result-file=' => null,
'check-version' => null,
'colors==' => null,
'columns=' => null,
@@ -103,6 +105,7 @@ class Command
'no-coverage' => null,
'no-logging' => null,
'no-extensions' => null,
'order-by=' => null,
'printer=' => null,
'process-isolation' => null,
'repeat=' => null,
@@ -113,6 +116,7 @@ class Command
'reverse-list' => null,
'static-backup' => null,
'stderr' => null,
'stop-on-defect' => null,
'stop-on-error' => null,
'stop-on-failure' => null,
'stop-on-warning' => null,
@@ -193,8 +197,7 @@ class Command
return $this->handleListTestsXml($suite, $this->arguments['listTestsXml'], $exit);
}
unset($this->arguments['test'], $this->arguments['testFile']
);
unset($this->arguments['test'], $this->arguments['testFile']);
try {
$result = $runner->doRun($suite, $this->arguments, $exit);
@@ -294,6 +297,16 @@ class Command
break;
case '--cache-result':
$this->arguments['cacheResult'] = true;
break;
case '--cache-result-file':
$this->arguments['cacheResultFile'] = $option[1];
break;
case '--columns':
if (\is_numeric($option[1])) {
$this->arguments['columns'] = (int) $option[1];
@@ -490,6 +503,11 @@ class Command
break;
case '--order-by':
$this->handleOrderByOption($option[1]);
break;
case '--process-isolation':
$this->arguments['processIsolation'] = true;
@@ -505,6 +523,11 @@ class Command
break;
case '--stop-on-defect':
$this->arguments['stopOnDefect'] = true;
break;
case '--stop-on-error':
$this->arguments['stopOnError'] = true;
@@ -693,7 +716,7 @@ class Command
break;
case '--random-order':
$this->arguments['executionOrder'] = TestSuiteSorter::ORDER_RANDOMIZED;
$this->handleOrderByOption('random');
break;
@@ -703,7 +726,7 @@ class Command
break;
case '--resolve-dependencies':
$this->arguments['resolveDependencies'] = true;
$this->handleOrderByOption('depends');
break;
@@ -713,7 +736,7 @@ class Command
break;
case '--reverse-order':
$this->arguments['executionOrder'] = TestSuiteSorter::ORDER_REVERSED;
$this->handleOrderByOption('reverse');
break;
@@ -1057,6 +1080,7 @@ Code Coverage Options:
--coverage-xml <dir> Generate code coverage report in PHPUnit XML format
--whitelist <dir> Whitelist <dir> for code coverage analysis
--disable-coverage-ignore Disable annotations for ignoring code coverage
--no-coverage Ignore code coverage configuration
Logging Options:
@@ -1098,6 +1122,7 @@ Test Execution Options:
--columns <n> Number of columns to use for progress output
--columns max Use maximum number of columns for progress output
--stderr Write to STDERR instead of STDOUT
--stop-on-defect Stop execution upon first not-passed test
--stop-on-error Stop execution upon first error
--stop-on-failure Stop execution upon first error or failure
--stop-on-warning Stop execution upon first warning
@@ -1118,21 +1143,21 @@ Test Execution Options:
--printer <printer> TestListener implementation to use
--resolve-dependencies Resolve dependencies between tests
--random-order Run tests in random order
--order-by=<order> Run tests in order: default|reverse|random|defects|depends
--random-order-seed=<N> Use a specific random seed <N> for random order
--reverse-order Run tests last-to-first
--cache-result Write run result to cache to enable ordering tests defects-first
Configuration Options:
--bootstrap <file> A "bootstrap" PHP file that is run before the tests
-c|--configuration <file> Read configuration from XML file
--no-configuration Ignore default configuration file (phpunit.xml)
--no-coverage Ignore code coverage configuration
--no-logging Ignore logging configuration
--no-extensions Do not load PHPUnit extensions
--include-path <path(s)> Prepend PHP's include_path with given path(s)
-d key[=value] Sets a php.ini value
--generate-configuration Generate configuration file with suggested settings
--cache-result-file==<FILE> Specify result cache path and filename
Miscellaneous Options:
@@ -1293,4 +1318,41 @@ EOT;
return TestRunner::SUCCESS_EXIT;
}
private function handleOrderByOption(string $value): void
{
foreach (\explode(',', $value) as $order) {
switch ($order) {
case 'default':
$this->arguments['executionOrder'] = TestSuiteSorter::ORDER_DEFAULT;
$this->arguments['executionOrderDefects'] = TestSuiteSorter::ORDER_DEFAULT;
$this->arguments['resolveDependencies'] = false;
break;
case 'reverse':
$this->arguments['executionOrder'] = TestSuiteSorter::ORDER_REVERSED;
break;
case 'random':
$this->arguments['executionOrder'] = TestSuiteSorter::ORDER_RANDOMIZED;
break;
case 'defects':
$this->arguments['executionOrderDefects'] = TestSuiteSorter::ORDER_DEFECTS_FIRST;
break;
case 'depends':
$this->arguments['resolveDependencies'] = true;
break;
default:
$this->exitWithErrorMessage("unrecognized --order-by option: $order");
}
}
}
}

View File

@@ -25,9 +25,12 @@ use PHPUnit\Runner\Filter\Factory;
use PHPUnit\Runner\Filter\IncludeGroupFilterIterator;
use PHPUnit\Runner\Filter\NameFilterIterator;
use PHPUnit\Runner\Hook;
use PHPUnit\Runner\NullTestResultCache;
use PHPUnit\Runner\ResultCacheExtension;
use PHPUnit\Runner\StandardTestSuiteLoader;
use PHPUnit\Runner\TestHook;
use PHPUnit\Runner\TestListenerAdapter;
use PHPUnit\Runner\TestResultCache;
use PHPUnit\Runner\TestSuiteLoader;
use PHPUnit\Runner\TestSuiteSorter;
use PHPUnit\Runner\Version;
@@ -152,8 +155,6 @@ class TestRunner extends BaseTestRunner
$this->handleConfiguration($arguments);
$this->processSuiteFilters($suite, $arguments);
if (isset($arguments['bootstrap'])) {
$GLOBALS['__PHPUNIT_BOOTSTRAP'] = $arguments['bootstrap'];
}
@@ -174,10 +175,24 @@ class TestRunner extends BaseTestRunner
\mt_srand($arguments['randomOrderSeed']);
}
if ($arguments['executionOrder'] !== TestSuiteSorter::ORDER_DEFAULT || $arguments['resolveDependencies']) {
$sorter = new TestSuiteSorter;
if ($arguments['cacheResult']) {
if (isset($arguments['cacheResultFile'])) {
$cache = new TestResultCache($arguments['cacheResultFile']);
} else {
$cache = new TestResultCache;
}
$sorter->reorderTestsInSuite($suite, $arguments['executionOrder'], $arguments['resolveDependencies']);
$this->extensions[] = new ResultCacheExtension($cache);
}
if ($arguments['executionOrder'] !== TestSuiteSorter::ORDER_DEFAULT || $arguments['executionOrderDefects'] !== TestSuiteSorter::ORDER_DEFAULT || $arguments['resolveDependencies']) {
$cache = $cache ?? new NullTestResultCache;
$cache->load();
$sorter = new TestSuiteSorter($cache);
$sorter->reorderTestsInSuite($suite, $arguments['executionOrder'], $arguments['resolveDependencies'], $arguments['executionOrderDefects']);
unset($sorter);
}
@@ -253,6 +268,10 @@ class TestRunner extends BaseTestRunner
$result->stopOnSkipped(true);
}
if ($arguments['stopOnDefect']) {
$result->stopOnDefect(true);
}
if ($arguments['registerMockObjectsFromTestArgumentsRecursively']) {
$result->setRegisterMockObjectsFromTestArgumentsRecursively(true);
}
@@ -554,6 +573,7 @@ class TestRunner extends BaseTestRunner
$result->setTimeoutForLargeTests($arguments['timeoutForLargeTests']);
if ($suite instanceof TestSuite) {
$this->processSuiteFilters($suite, $arguments);
$suite->setRunTestInSeparateProcess($arguments['processIsolation']);
}
@@ -806,6 +826,18 @@ class TestRunner extends BaseTestRunner
$arguments['bootstrap'] = $phpunitConfiguration['bootstrap'];
}
if (isset($phpunitConfiguration['cacheResult']) && !isset($arguments['cacheResult'])) {
$arguments['cacheResult'] = $phpunitConfiguration['cacheResult'];
}
if (isset($phpunitConfiguration['cacheResultFile']) && !isset($arguments['cacheResultFile'])) {
$arguments['cacheResultFile'] = $phpunitConfiguration['cacheResultFile'];
}
if (isset($phpunitConfiguration['cacheTokens']) && !isset($arguments['cacheTokens'])) {
$arguments['cacheTokens'] = $phpunitConfiguration['cacheTokens'];
}
if (isset($phpunitConfiguration['cacheTokens']) && !isset($arguments['cacheTokens'])) {
$arguments['cacheTokens'] = $phpunitConfiguration['cacheTokens'];
}
@@ -834,6 +866,10 @@ class TestRunner extends BaseTestRunner
$arguments['processIsolation'] = $phpunitConfiguration['processIsolation'];
}
if (isset($phpunitConfiguration['stopOnDefect']) && !isset($arguments['stopOnDefect'])) {
$arguments['stopOnDefect'] = $phpunitConfiguration['stopOnDefect'];
}
if (isset($phpunitConfiguration['stopOnError']) && !isset($arguments['stopOnError'])) {
$arguments['stopOnError'] = $phpunitConfiguration['stopOnError'];
}
@@ -930,6 +966,10 @@ class TestRunner extends BaseTestRunner
$arguments['executionOrder'] = $phpunitConfiguration['executionOrder'];
}
if (isset($phpunitConfiguration['executionOrderDefects']) && !isset($arguments['executionOrderDefects'])) {
$arguments['executionOrderDefects'] = $phpunitConfiguration['executionOrderDefects'];
}
if (isset($phpunitConfiguration['resolveDependencies']) && !isset($arguments['resolveDependencies'])) {
$arguments['resolveDependencies'] = $phpunitConfiguration['resolveDependencies'];
}
@@ -1116,6 +1156,7 @@ class TestRunner extends BaseTestRunner
$arguments['backupStaticAttributes'] = $arguments['backupStaticAttributes'] ?? null;
$arguments['beStrictAboutChangesToGlobalState'] = $arguments['beStrictAboutChangesToGlobalState'] ?? null;
$arguments['beStrictAboutResourceUsageDuringSmallTests'] = $arguments['beStrictAboutResourceUsageDuringSmallTests'] ?? false;
$arguments['cacheResult'] = $arguments['cacheResult'] ?? false;
$arguments['cacheTokens'] = $arguments['cacheTokens'] ?? false;
$arguments['colors'] = $arguments['colors'] ?? ResultPrinter::COLOR_DEFAULT;
$arguments['columns'] = $arguments['columns'] ?? 80;
@@ -1130,6 +1171,7 @@ class TestRunner extends BaseTestRunner
$arguments['excludeGroups'] = $arguments['excludeGroups'] ?? [];
$arguments['failOnRisky'] = $arguments['failOnRisky'] ?? false;
$arguments['failOnWarning'] = $arguments['failOnWarning'] ?? false;
$arguments['executionOrderDefects'] = $arguments['executionOrderDefects'] ?? TestSuiteSorter::ORDER_DEFAULT;
$arguments['groups'] = $arguments['groups'] ?? [];
$arguments['processIsolation'] = $arguments['processIsolation'] ?? false;
$arguments['processUncoveredFilesFromWhitelist'] = $arguments['processUncoveredFilesFromWhitelist'] ?? false;
@@ -1148,6 +1190,7 @@ class TestRunner extends BaseTestRunner
$arguments['stopOnRisky'] = $arguments['stopOnRisky'] ?? false;
$arguments['stopOnSkipped'] = $arguments['stopOnSkipped'] ?? false;
$arguments['stopOnWarning'] = $arguments['stopOnWarning'] ?? false;
$arguments['stopOnDefect'] = $arguments['stopOnDefect'] ?? false;
$arguments['strictCoverage'] = $arguments['strictCoverage'] ?? false;
$arguments['testdoxExcludeGroups'] = $arguments['testdoxExcludeGroups'] ?? [];
$arguments['testdoxGroups'] = $arguments['testdoxGroups'] ?? [];

View File

@@ -27,6 +27,8 @@ use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;
* <phpunit backupGlobals="false"
* backupStaticAttributes="false"
* bootstrap="/path/to/bootstrap.php"
* cacheResult="false"
* cacheResultFile=".phpunit.result.cache"
* cacheTokens="false"
* columns="80"
* colors="false"
@@ -38,6 +40,7 @@ use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;
* disableCodeCoverageIgnore="false"
* forceCoversAnnotation="false"
* processIsolation="false"
* stopOnDefect="false"
* stopOnError="false"
* stopOnFailure="false"
* stopOnWarning="false"
@@ -65,6 +68,7 @@ use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;
* reverseDefectList="false"
* registerMockObjectsFromTestArgumentsRecursively="false"
* executionOrder="default"
* executionOrderDefects="default"
* resolveDependencies="false">
* <testsuites>
* <testsuite name="My Test Suite">
@@ -716,6 +720,13 @@ final class Configuration
);
}
if ($root->hasAttribute('stopOnDefect')) {
$result['stopOnDefect'] = $this->getBoolean(
(string) $root->getAttribute('stopOnDefect'),
false
);
}
if ($root->hasAttribute('stopOnError')) {
$result['stopOnError'] = $this->getBoolean(
(string) $root->getAttribute('stopOnError'),
@@ -908,21 +919,45 @@ final class Configuration
);
}
if ($root->hasAttribute('cacheResult')) {
$result['cacheResult'] = $this->getBoolean(
(string) $root->getAttribute('cacheResult'),
false
);
}
if ($root->hasAttribute('cacheResultFile')) {
$result['cacheResultFile'] = $this->toAbsolutePath(
(string) $root->getAttribute('cacheResultFile')
);
}
if ($root->hasAttribute('executionOrder')) {
switch ((string) $root->getAttribute('executionOrder')) {
case 'random':
$result['executionOrder'] = TestSuiteSorter::ORDER_RANDOMIZED;
foreach (\explode(',', $root->getAttribute('executionOrder')) as $order) {
switch ($order) {
case 'default':
$result['executionOrder'] = TestSuiteSorter::ORDER_DEFAULT;
$result['executionOrderDefects'] = TestSuiteSorter::ORDER_DEFAULT;
$result['resolveDependencies'] = false;
break;
break;
case 'reverse':
$result['executionOrder'] = TestSuiteSorter::ORDER_REVERSED;
case 'reverse':
$result['executionOrder'] = TestSuiteSorter::ORDER_REVERSED;
break;
case 'random':
$result['executionOrder'] = TestSuiteSorter::ORDER_RANDOMIZED;
break;
break;
case 'defects':
$result['executionOrderDefects'] = TestSuiteSorter::ORDER_DEFECTS_FIRST;
default:
$result['executionOrder'] = TestSuiteSorter::ORDER_DEFAULT;
break;
case 'depends':
$result['resolveDependencies'] = true;
break;
}
}
}
@@ -990,6 +1025,7 @@ final class Configuration
$this->document->schemaValidate($xsdFilename);
$this->errors = \libxml_get_errors();
\libxml_clear_errors();
\libxml_use_internal_errors($original);
}

View File

@@ -54,6 +54,7 @@ final class Filter
foreach ($eTrace as $frame) {
if (isset($frame['file']) && \is_file($frame['file']) &&
(empty($GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST']) || !\in_array($frame['file'], $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'])) &&
!$blacklist->isBlacklisted($frame['file']) &&
($prefix === false || \strpos($frame['file'], $prefix) !== 0) &&
$frame['file'] !== $script) {

View File

@@ -28,7 +28,7 @@ final class Json
);
}
return \json_encode($decodedJson, \JSON_PRETTY_PRINT);
return \json_encode($decodedJson, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES);
}
/*

View File

@@ -364,7 +364,7 @@ class JUnit extends Printer implements TestListener
* This is a "hack" needed for the integration of
* PHPUnit with Phing.
*/
public function setWriteDocument($flag): ?string
public function setWriteDocument(/*bool*/ $flag): void
{
if (\is_bool($flag)) {
$this->writeDocument = $flag;

View File

@@ -60,9 +60,10 @@ class TeamCity extends ResultPrinter
$this->printEvent(
'testFailed',
[
'name' => $test->getName(),
'message' => self::getMessage($t),
'details' => self::getDetails($t),
'name' => $test->getName(),
'message' => self::getMessage($t),
'details' => self::getDetails($t),
'duration' => self::toMilliseconds($time),
]
);
}
@@ -77,9 +78,10 @@ class TeamCity extends ResultPrinter
$this->printEvent(
'testFailed',
[
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e)
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e),
'duration' => self::toMilliseconds($time),
]
);
}
@@ -92,9 +94,10 @@ class TeamCity extends ResultPrinter
public function addFailure(Test $test, AssertionFailedError $e, float $time): void
{
$parameters = [
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e),
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e),
'duration' => self::toMilliseconds($time),
];
if ($e instanceof ExpectationFailedException) {
@@ -129,7 +132,7 @@ class TeamCity extends ResultPrinter
*/
public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
{
$this->printIgnoredTest($test->getName(), $t);
$this->printIgnoredTest($test->getName(), $t, $time);
}
/**
@@ -153,21 +156,22 @@ class TeamCity extends ResultPrinter
if ($this->startedTestName !== $testName) {
$this->startTest($test);
$this->printIgnoredTest($testName, $t);
$this->printIgnoredTest($testName, $t, $time);
$this->endTest($test, $time);
} else {
$this->printIgnoredTest($testName, $t);
$this->printIgnoredTest($testName, $t, $time);
}
}
public function printIgnoredTest($testName, \Throwable $t): void
public function printIgnoredTest($testName, \Throwable $t, float $time): void
{
$this->printEvent(
'testIgnored',
[
'name' => $testName,
'message' => self::getMessage($t),
'details' => self::getDetails($t),
'name' => $testName,
'message' => self::getMessage($t),
'details' => self::getDetails($t),
'duration' => self::toMilliseconds($time),
]
);
}
@@ -273,7 +277,7 @@ class TeamCity extends ResultPrinter
'testFinished',
[
'name' => $test->getName(),
'duration' => (int) (\round($time, 2) * 1000)
'duration' => self::toMilliseconds($time)
]
);
}
@@ -376,4 +380,12 @@ class TeamCity extends ResultPrinter
return $reflectionClass->getFileName();
}
/**
* @param float $time microseconds
*/
private static function toMilliseconds(float $time): int
{
return \round($time * 1000);
}
}

View File

@@ -180,19 +180,22 @@ abstract class AbstractPhpProcess
$command .= $this->settingsToParameters($settings);
if (\PHP_SAPI === 'phpdbg') {
$command .= ' -qrr ';
$command .= ' -qrr';
if ($file) {
$command .= '-e ' . \escapeshellarg($file);
} else {
$command .= \escapeshellarg(__DIR__ . '/eval-stdin.php');
if (!$file) {
$command .= 's=';
}
} elseif ($file) {
$command .= ' -f ' . \escapeshellarg($file);
}
if ($file) {
$command .= ' ' . \escapeshellarg($file);
}
if ($this->args) {
$command .= ' -- ' . $this->args;
if (!$file) {
$command .= ' --';
}
$command .= ' ' . $this->args;
}
if ($this->stderrRedirection === true) {

View File

@@ -3,7 +3,6 @@ use SebastianBergmann\CodeCoverage\CodeCoverage;
$composerAutoload = {composerAutoload};
$phar = {phar};
$autoPrependFile = {autoPrependFile};
ob_start();
@@ -28,7 +27,7 @@ if (class_exists('SebastianBergmann\CodeCoverage\CodeCoverage')) {
$coverage->start(__FILE__);
}
register_shutdown_function(function() use ($coverage, $autoPrependFile) {
register_shutdown_function(function() use ($coverage) {
$output = null;
if ($coverage) {
$output = $coverage->stop();
@@ -38,9 +37,4 @@ register_shutdown_function(function() use ($coverage, $autoPrependFile) {
ob_end_clean();
if ($autoPrependFile) {
require $autoPrependFile;
$includes = get_included_files();
$GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'][] = array_pop($includes);
unset($includes);
}
require '{job}';

View File

@@ -58,6 +58,7 @@ function __phpunit_run_isolated_test()
$output = $test->getActualOutput();
}
ini_set('xdebug.scream', 0);
@rewind(STDOUT); /* @ as not every STDOUT target stream is rewindable */
if ($stdout = stream_get_contents(STDOUT)) {
$output = $stdout . $output;
@@ -69,12 +70,12 @@ function __phpunit_run_isolated_test()
}
print serialize(
array(
[
'testResult' => $test->getResult(),
'numAssertions' => $test->getNumAssertions(),
'result' => $result,
'output' => $output
)
]
);
}

View File

@@ -60,6 +60,7 @@ function __phpunit_run_isolated_test()
$output = $test->getActualOutput();
}
ini_set('xdebug.scream', '0');
@rewind(STDOUT); /* @ as not every STDOUT target stream is rewindable */
if ($stdout = stream_get_contents(STDOUT)) {
$output = $stdout . $output;
@@ -71,12 +72,12 @@ function __phpunit_run_isolated_test()
}
print serialize(
array(
[
'testResult' => $test->getResult(),
'numAssertions' => $test->getNumAssertions(),
'result' => $result,
'output' => $output
)
]
);
}

View File

@@ -782,6 +782,15 @@ final class Test
$element = \explode(' ', $element);
$element = $element[0];
if ($mode === 'covers' && \interface_exists($element)) {
throw new InvalidCoversTargetException(
\sprintf(
'Trying to @cover interface "%s".',
$element
)
);
}
$codeList = \array_merge(
$codeList,
self::resolveElementToReflectionObjects($element)
@@ -1039,6 +1048,14 @@ final class Test
{
$result = [];
foreach ($reflectors as $reflector) {
if ($reflector instanceof ReflectionClass) {
foreach ($reflector->getTraits() as $trait) {
$reflectors[] = $trait;
}
}
}
foreach ($reflectors as $reflector) {
$filename = $reflector->getFileName();

View File

@@ -55,31 +55,15 @@ class CliTestDoxPrinter extends ResultPrinter
public function startTest(Test $test): void
{
if (!$test instanceof TestCase
&& !$test instanceof PhptTestCase
&& !$test instanceof TestSuite
) {
if (!$test instanceof TestCase && !$test instanceof PhptTestCase && !$test instanceof TestSuite) {
return;
}
$class = \get_class($test);
if ($test instanceof TestCase) {
$annotations = $test->getAnnotations();
if (isset($annotations['class']['testdox'][0])) {
$className = $annotations['class']['testdox'][0];
} else {
$className = $this->prettifier->prettifyTestClass($class);
}
if (isset($annotations['method']['testdox'][0])) {
$testMethod = $annotations['method']['testdox'][0];
} else {
$testMethod = $this->prettifier->prettifyTestMethod($test->getName(false));
}
$testMethod .= \substr($test->getDataSetAsString(false), 5);
$className = $this->prettifier->prettifyTestClass($class);
$testMethod = $this->prettifier->prettifyTestCase($test);
} elseif ($test instanceof TestSuite) {
$className = $test->getName();
$testMethod = \sprintf(
@@ -104,10 +88,7 @@ class CliTestDoxPrinter extends ResultPrinter
public function endTest(Test $test, float $time): void
{
if (!$test instanceof TestCase
&& !$test instanceof PhptTestCase
&& !$test instanceof TestSuite
) {
if (!$test instanceof TestCase && !$test instanceof PhptTestCase && !$test instanceof TestSuite) {
return;
}

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Util\TestDox;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Exporter\Exporter;
/**
* Prettifies class and method names for use in TestDox documentation.
*/
@@ -22,25 +25,70 @@ final class NamePrettifier
/**
* Prettifies the name of a test class.
*/
public function prettifyTestClass(string $name): string
public function prettifyTestClass(string $className): string
{
$title = $name;
try {
$annotations = \PHPUnit\Util\Test::parseTestMethodAnnotations($className);
if (\substr($name, -1 * \strlen('Test')) === 'Test') {
$title = \substr($title, 0, \strripos($title, 'Test'));
if (isset($annotations['class']['testdox'][0])) {
return $annotations['class']['testdox'][0];
}
} catch (\ReflectionException $e) {
}
if (\strpos($name, 'Tests') === 0) {
$title = \substr($title, \strlen('Tests'));
} elseif (\strpos($name, 'Test') === 0) {
$title = \substr($title, \strlen('Test'));
$result = $className;
if (\substr($className, -1 * \strlen('Test')) === 'Test') {
$result = \substr($result, 0, \strripos($result, 'Test'));
}
if ($title[0] === '\\') {
$title = \substr($title, 1);
if (\strpos($className, 'Tests') === 0) {
$result = \substr($result, \strlen('Tests'));
} elseif (\strpos($className, 'Test') === 0) {
$result = \substr($result, \strlen('Test'));
}
return $title;
if ($result[0] === '\\') {
$result = \substr($result, 1);
}
return $result;
}
/**
* @throws \ReflectionException
*/
public function prettifyTestCase(TestCase $test): string
{
$annotations = $test->getAnnotations();
$annotationWithPlaceholders = false;
if (isset($annotations['method']['testdox'][0])) {
$result = $annotations['method']['testdox'][0];
if (\strpos($result, '$') !== false) {
$annotation = $annotations['method']['testdox'][0];
$providedData = $this->mapTestMethodParameterNamesToProvidedDataValues($test);
$result = \trim(
\str_replace(
\array_keys($providedData),
$providedData,
$annotation
)
);
$annotationWithPlaceholders = true;
}
} else {
$result = $this->prettifyTestMethod($test->getName(false));
}
if ($test->usesDataProvider() && !$annotationWithPlaceholders) {
$result .= ' data set "' . $test->dataDescription() . '"';
}
return $result;
}
/**
@@ -102,4 +150,41 @@ final class NamePrettifier
return $buffer;
}
/**
* @throws \ReflectionException
*/
private function mapTestMethodParameterNamesToProvidedDataValues(TestCase $test): array
{
$reflector = new \ReflectionMethod(\get_class($test), $test->getName(false));
$providedData = [];
$providedDataValues = $test->getProvidedData();
$i = 0;
foreach ($reflector->getParameters() as $parameter) {
$value = $providedDataValues[$i++];
if (\is_object($value)) {
$reflector = new \ReflectionObject($value);
if ($reflector->hasMethod('__toString')) {
$value = (string) $value;
}
}
if (!\is_scalar($value)) {
$value = \gettype($value);
}
if (\is_bool($value) || \is_numeric($value)) {
$exporter = new Exporter;
$value = $exporter->export($value);
}
$providedData['$' . $parameter->getName()] = $value;
}
return $providedData;
}
}

View File

@@ -231,32 +231,15 @@ abstract class ResultPrinter extends Printer implements TestListener
$this->doEndClass();
}
$classAnnotations = \PHPUnit\Util\Test::parseTestMethodAnnotations($class);
if (isset($classAnnotations['class']['testdox'][0])) {
$this->currentTestClassPrettified = $classAnnotations['class']['testdox'][0];
} else {
$this->currentTestClassPrettified = $this->prettifier->prettifyTestClass($class);
}
$this->currentTestClassPrettified = $this->prettifier->prettifyTestClass($class);
$this->testClass = $class;
$this->tests = [];
$this->startClass($class);
$this->testClass = $class;
$this->tests = [];
}
if ($test instanceof TestCase) {
$annotations = $test->getAnnotations();
if (isset($annotations['method']['testdox'][0])) {
$this->currentTestMethodPrettified = $annotations['method']['testdox'][0];
} else {
$this->currentTestMethodPrettified = $this->prettifier->prettifyTestMethod($test->getName(false));
}
if ($test->usesDataProvider()) {
$this->currentTestMethodPrettified .= ' ' . $test->dataDescription();
}
$this->currentTestMethodPrettified = $this->prettifier->prettifyTestCase($test);
}
$this->testStatus = BaseTestRunner::STATUS_PASSED;

View File

@@ -162,7 +162,7 @@ class XmlResultPrinter extends Printer implements TestListener
$node->setAttribute('className', \get_class($test));
$node->setAttribute('methodName', $test->getName());
$node->setAttribute('prettifiedClassName', $this->prettifier->prettifyTestClass(\get_class($test)));
$node->setAttribute('prettifiedMethodName', $this->prettifier->prettifyTestMethod($test->getName()));
$node->setAttribute('prettifiedMethodName', $this->prettifier->prettifyTestCase($test));
$node->setAttribute('status', $test->getStatus());
$node->setAttribute('time', $time);
$node->setAttribute('size', $test->getSize());

View File

@@ -1,5 +0,0 @@
--TEST--
// This test intentionally fails and it is checked by Travis.
--FILE--
--EXPECTF--
unexpected

File diff suppressed because it is too large Load Diff

View File

@@ -1,64 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class ArrayHasKeyTest extends ConstraintTestCase
{
public function testConstraintArrayHasKey(): void
{
$constraint = new ArrayHasKey(0);
$this->assertFalse($constraint->evaluate([], '', true));
$this->assertEquals('has the key 0', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate([]);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that an array has the key 0.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintArrayHasKey2(): void
{
$constraint = new ArrayHasKey(0);
try {
$constraint->evaluate([], 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message\nFailed asserting that an array has the key 0.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,86 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
class ArraySubsetTest extends ConstraintTestCase
{
public static function evaluateDataProvider()
{
return [
'loose array subset and array other' => [
'expected' => true,
'subset' => ['bar' => 0],
'other' => ['foo' => '', 'bar' => '0'],
'strict' => false
],
'strict array subset and array other' => [
'expected' => false,
'subset' => ['bar' => 0],
'other' => ['foo' => '', 'bar' => '0'],
'strict' => true
],
'loose array subset and ArrayObject other' => [
'expected' => true,
'subset' => ['bar' => 0],
'other' => new \ArrayObject(['foo' => '', 'bar' => '0']),
'strict' => false
],
'strict ArrayObject subset and array other' => [
'expected' => true,
'subset' => new \ArrayObject(['bar' => 0]),
'other' => ['foo' => '', 'bar' => 0],
'strict' => true
],
];
}
/**
* @param bool $expected
* @param array|\Traversable $subset
* @param array|\Traversable $other
* @param bool $strict
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @dataProvider evaluateDataProvider
*/
public function testEvaluate($expected, $subset, $other, $strict): void
{
$constraint = new ArraySubset($subset, $strict);
$this->assertSame($expected, $constraint->evaluate($other, '', true));
}
public function testEvaluateWithArrayAccess(): void
{
$arrayAccess = new \ArrayAccessible(['foo' => 'bar']);
$constraint = new ArraySubset(['foo' => 'bar']);
$this->assertTrue($constraint->evaluate($arrayAccess, '', true));
}
public function testEvaluateFailMessage(): void
{
$constraint = new ArraySubset(['foo' => 'bar']);
try {
$constraint->evaluate(['baz' => 'bar'], '', false);
$this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class));
} catch (ExpectationFailedException $expectedException) {
$comparisonFailure = $expectedException->getComparisonFailure();
$this->assertNotNull($comparisonFailure);
$this->assertContains('[foo] => bar', $comparisonFailure->getExpectedAsString());
$this->assertContains('[baz] => bar', $comparisonFailure->getActualAsString());
}
}
}

View File

@@ -1,80 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class AttributeTest extends ConstraintTestCase
{
public function testAttributeEqualTo(): void
{
$object = new \ClassWithNonPublicAttributes;
$constraint = new Attribute(
new IsEqual(1),
'foo'
);
$this->assertTrue($constraint->evaluate($object, '', true));
$this->assertEquals('attribute "foo" is equal to 1', $constraint->toString());
$this->assertCount(1, $constraint);
$constraint = new Attribute(
new IsEqual(2),
'foo'
);
$this->assertFalse($constraint->evaluate($object, '', true));
try {
$constraint->evaluate($object);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that attribute "foo" is equal to 2.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testAttributeEqualTo2(): void
{
$object = new \ClassWithNonPublicAttributes;
$constraint = new Attribute(
new IsEqual(2),
'foo'
);
try {
$constraint->evaluate($object, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message\nFailed asserting that attribute "foo" is equal to 2.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,65 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
class CallbackTest extends ConstraintTestCase
{
public static function staticCallbackReturningTrue()
{
return true;
}
public function callbackReturningTrue()
{
return true;
}
public function testConstraintCallback(): void
{
$closureReflect = function ($parameter) {
return $parameter;
};
$closureWithoutParameter = function () {
return true;
};
$constraint = new Callback($closureWithoutParameter);
$this->assertTrue($constraint->evaluate('', '', true));
$constraint = new Callback($closureReflect);
$this->assertTrue($constraint->evaluate(true, '', true));
$this->assertFalse($constraint->evaluate(false, '', true));
$callback = [$this, 'callbackReturningTrue'];
$constraint = new Callback($callback);
$this->assertTrue($constraint->evaluate(false, '', true));
$callback = [self::class, 'staticCallbackReturningTrue'];
$constraint = new Callback($callback);
$this->assertTrue($constraint->evaluate(null, '', true));
$this->assertEquals('is accepted by specified callback', $constraint->toString());
}
public function testConstraintCallbackFailure(): void
{
$constraint = new Callback(function () {
return false;
});
$this->expectException(ExpectationFailedException::class);
$this->expectExceptionMessage('Failed asserting that \'This fails\' is accepted by specified callback.');
$constraint->evaluate('This fails');
}
}

View File

@@ -1,70 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class ClassHasAttributeTest extends ConstraintTestCase
{
public function testConstraintClassHasAttribute(): void
{
$constraint = new ClassHasAttribute(
'privateAttribute'
);
$this->assertTrue($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true));
$this->assertFalse($constraint->evaluate(\stdClass::class, '', true));
$this->assertEquals('has attribute "privateAttribute"', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(\stdClass::class);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that class "stdClass" has attribute "privateAttribute".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintClassHasAttribute2(): void
{
$constraint = new ClassHasAttribute(
'privateAttribute'
);
try {
$constraint->evaluate(\stdClass::class, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that class "stdClass" has attribute "privateAttribute".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,66 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class ClassHasStaticAttributeTest extends ConstraintTestCase
{
public function testConstraintClassHasStaticAttribute(): void
{
$constraint = new ClassHasStaticAttribute('privateStaticAttribute');
$this->assertTrue($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true));
$this->assertFalse($constraint->evaluate(\stdClass::class, '', true));
$this->assertEquals('has static attribute "privateStaticAttribute"', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(\stdClass::class);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that class "stdClass" has static attribute "privateStaticAttribute".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintClassHasStaticAttribute2(): void
{
$constraint = new ClassHasStaticAttribute('foo');
try {
$constraint->evaluate(\stdClass::class, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that class "stdClass" has static attribute "foo".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,54 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\SelfDescribing;
use PHPUnit\Framework\TestCase;
abstract class ConstraintTestCase extends TestCase
{
final public function testIsCountable(): void
{
$className = $this->className();
$reflection = new \ReflectionClass($className);
$this->assertTrue($reflection->implementsInterface(\Countable::class), \sprintf(
'Failed to assert that "%s" implements "%s".',
$className,
\Countable::class
));
}
final public function testIsSelfDescribing(): void
{
$className = $this->className();
$reflection = new \ReflectionClass($className);
$this->assertTrue($reflection->implementsInterface(SelfDescribing::class), \sprintf(
'Failed to assert that "%s" implements "%s".',
$className,
\Countable::class
));
}
/**
* Returns the class name of the constraint.
*/
final protected function className(): string
{
return \preg_replace(
'/Test$/',
'',
static::class
);
}
}

View File

@@ -1,145 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
class CountTest extends ConstraintTestCase
{
public function testCount(): void
{
$countConstraint = new Count(3);
$this->assertTrue($countConstraint->evaluate([1, 2, 3], '', true));
$countConstraint = new Count(0);
$this->assertTrue($countConstraint->evaluate([], '', true));
$countConstraint = new Count(2);
$it = new \TestIterator([1, 2]);
$ia = new \TestIteratorAggregate($it);
$ia2 = new \TestIteratorAggregate2($ia);
$this->assertTrue($countConstraint->evaluate($it, '', true));
$this->assertTrue($countConstraint->evaluate($ia, '', true));
$this->assertTrue($countConstraint->evaluate($ia2, '', true));
}
public function testCountDoesNotChangeIteratorKey(): void
{
$countConstraint = new Count(2);
// test with 1st implementation of Iterator
$it = new \TestIterator([1, 2]);
$countConstraint->evaluate($it, '', true);
$this->assertEquals(1, $it->current());
$it->next();
$countConstraint->evaluate($it, '', true);
$this->assertEquals(2, $it->current());
$it->next();
$countConstraint->evaluate($it, '', true);
$this->assertFalse($it->valid());
// test with 2nd implementation of Iterator
$it = new \TestIterator2([1, 2]);
$countConstraint = new Count(2);
$countConstraint->evaluate($it, '', true);
$this->assertEquals(1, $it->current());
$it->next();
$countConstraint->evaluate($it, '', true);
$this->assertEquals(2, $it->current());
$it->next();
$countConstraint->evaluate($it, '', true);
$this->assertFalse($it->valid());
// test with IteratorAggregate
$it = new \TestIterator([1, 2]);
$ia = new \TestIteratorAggregate($it);
$countConstraint = new Count(2);
$countConstraint->evaluate($ia, '', true);
$this->assertEquals(1, $it->current());
$it->next();
$countConstraint->evaluate($ia, '', true);
$this->assertEquals(2, $it->current());
$it->next();
$countConstraint->evaluate($ia, '', true);
$this->assertFalse($it->valid());
// test with nested IteratorAggregate
$it = new \TestIterator([1, 2]);
$ia = new \TestIteratorAggregate($it);
$ia2 = new \TestIteratorAggregate2($ia);
$countConstraint = new Count(2);
$countConstraint->evaluate($ia2, '', true);
$this->assertEquals(1, $it->current());
$it->next();
$countConstraint->evaluate($ia2, '', true);
$this->assertEquals(2, $it->current());
$it->next();
$countConstraint->evaluate($ia2, '', true);
$this->assertFalse($it->valid());
}
public function testCountGeneratorsDoNotRewind(): void
{
$generatorMaker = new \TestGeneratorMaker;
$countConstraint = new Count(3);
$generator = $generatorMaker->create([1, 2, 3]);
$this->assertEquals(1, $generator->current());
$countConstraint->evaluate($generator, '', true);
$this->assertEquals(null, $generator->current());
$countConstraint = new Count(2);
$generator = $generatorMaker->create([1, 2, 3]);
$this->assertEquals(1, $generator->current());
$generator->next();
$this->assertEquals(2, $generator->current());
$countConstraint->evaluate($generator, '', true);
$this->assertEquals(null, $generator->current());
$countConstraint = new Count(1);
$generator = $generatorMaker->create([1, 2, 3]);
$this->assertEquals(1, $generator->current());
$generator->next();
$this->assertEquals(2, $generator->current());
$generator->next();
$this->assertEquals(3, $generator->current());
$countConstraint->evaluate($generator, '', true);
$this->assertEquals(null, $generator->current());
}
public function testCountTraversable(): void
{
$countConstraint = new Count(5);
// DatePeriod is used as an object that is Traversable but does not
// implement Iterator or IteratorAggregate. The following ISO 8601
// recurring time interval will yield five total DateTime objects.
$datePeriod = new \DatePeriod('R4/2017-05-01T00:00:00Z/P1D');
$this->assertInstanceOf(\Traversable::class, $datePeriod);
$this->assertNotInstanceOf(\Iterator::class, $datePeriod);
$this->assertNotInstanceOf(\IteratorAggregate::class, $datePeriod);
$this->assertTrue($countConstraint->evaluate($datePeriod, '', true));
}
}

View File

@@ -1,66 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class DirectoryExistsTest extends ConstraintTestCase
{
public function testDefaults(): void
{
$constraint = new DirectoryExists();
$this->assertCount(1, $constraint);
$this->assertSame('directory exists', $constraint->toString());
}
public function testEvaluateReturnsFalseWhenDirectoryDoesNotExist(): void
{
$directory = __DIR__ . '/NonExistentDirectory';
$constraint = new DirectoryExists();
$this->assertFalse($constraint->evaluate($directory, '', true));
}
public function testEvaluateReturnsTrueWhenDirectoryExists(): void
{
$directory = __DIR__;
$constraint = new DirectoryExists();
$this->assertTrue($constraint->evaluate($directory, '', true));
}
public function testEvaluateThrowsExpectationFailedExceptionWhenDirectoryDoesNotExist(): void
{
$directory = __DIR__ . '/NonExistentDirectory';
$constraint = new DirectoryExists();
try {
$constraint->evaluate($directory);
} catch (ExpectationFailedException $e) {
$this->assertSame(
<<<PHP
Failed asserting that directory "$directory" exists.
PHP
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,55 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\TestCase;
class ExceptionMessageRegExpTest extends TestCase
{
/**
* @expectedException \Exception
* @expectedExceptionMessageRegExp /^A polymorphic \w+ message/
*/
public function testRegexMessage(): void
{
throw new \Exception('A polymorphic exception message');
}
/**
* @expectedException \Exception
* @expectedExceptionMessageRegExp /^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i
*/
public function testRegexMessageExtreme(): void
{
throw new \Exception('A polymorphic exception message');
}
/**
* @runInSeparateProcess
* @requires extension xdebug
* @expectedException \Exception
* @expectedExceptionMessageRegExp #Screaming preg_match#
*/
public function testMessageXdebugScreamCompatibility(): void
{
\ini_set('xdebug.scream', '1');
throw new \Exception('Screaming preg_match');
}
/**
* @expectedException \Exception variadic
* @expectedExceptionMessageRegExp /^A variadic \w+ message/
*/
public function testSimultaneousLiteralAndRegExpExceptionMessage(): void
{
throw new \Exception('A variadic exception message');
}
}

View File

@@ -1,51 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\TestCase;
class ExceptionMessageTest extends TestCase
{
/**
* @expectedException \Exception
* @expectedExceptionMessage A literal exception message
*/
public function testLiteralMessage(): void
{
throw new \Exception('A literal exception message');
}
/**
* @expectedException \Exception
* @expectedExceptionMessage A partial
*/
public function testPartialMessageBegin(): void
{
throw new \Exception('A partial exception message');
}
/**
* @expectedException \Exception
* @expectedExceptionMessage partial exception
*/
public function testPartialMessageMiddle(): void
{
throw new \Exception('A partial exception message');
}
/**
* @expectedException \Exception
* @expectedExceptionMessage exception message
*/
public function testPartialMessageEnd(): void
{
throw new \Exception('A partial exception message');
}
}

View File

@@ -1,65 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class FileExistsTest extends ConstraintTestCase
{
public function testConstraintFileExists(): void
{
$constraint = new FileExists();
$this->assertFalse($constraint->evaluate('foo', '', true));
$this->assertEquals('file exists', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate('foo');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that file "foo" exists.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintFileExists2(): void
{
$constraint = new FileExists();
try {
$constraint->evaluate('foo', 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that file "foo" exists.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,66 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class GreaterThanTest extends ConstraintTestCase
{
public function testConstraintGreaterThan(): void
{
$constraint = new GreaterThan(1);
$this->assertFalse($constraint->evaluate(0, '', true));
$this->assertTrue($constraint->evaluate(2, '', true));
$this->assertEquals('is greater than 1', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(0);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that 0 is greater than 1.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintGreaterThan2(): void
{
$constraint = new GreaterThan(1);
try {
$constraint->evaluate(0, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that 0 is greater than 1.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,67 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class IsEmptyTest extends ConstraintTestCase
{
public function testConstraintIsEmpty(): void
{
$constraint = new IsEmpty();
$this->assertFalse($constraint->evaluate(['foo'], '', true));
$this->assertTrue($constraint->evaluate([], '', true));
$this->assertFalse($constraint->evaluate(new \ArrayObject(['foo']), '', true));
$this->assertTrue($constraint->evaluate(new \ArrayObject([]), '', true));
$this->assertEquals('is empty', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(['foo']);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that an array is empty.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintIsEmpty2(): void
{
$constraint = new IsEmpty();
try {
$constraint->evaluate(['foo'], 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message\nFailed asserting that an array is empty.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,321 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class IsEqualTest extends ConstraintTestCase
{
public function testConstraintIsEqual(): void
{
$constraint = new IsEqual(1);
$this->assertTrue($constraint->evaluate(1, '', true));
$this->assertFalse($constraint->evaluate(0, '', true));
$this->assertEquals('is equal to 1', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(0);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that 0 matches expected 1.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
/**
* @dataProvider isEqualProvider
*/
public function testConstraintIsEqual2($expected, $actual, $message): void
{
$constraint = new IsEqual($expected);
try {
$constraint->evaluate($actual, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
"custom message\n$message",
$this->trimnl(TestFailure::exceptionToString($e))
);
return;
}
$this->fail();
}
public function isEqualProvider()
{
$a = new \stdClass;
$a->foo = 'bar';
$b = new \stdClass;
$ahash = \spl_object_hash($a);
$bhash = \spl_object_hash($b);
$c = new \stdClass;
$c->foo = 'bar';
$c->int = 1;
$c->array = [0, [1], [2], 3];
$c->related = new \stdClass;
$c->related->foo = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk";
$c->self = $c;
$c->c = $c;
$d = new \stdClass;
$d->foo = 'bar';
$d->int = 2;
$d->array = [0, [4], [2], 3];
$d->related = new \stdClass;
$d->related->foo = "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk";
$d->self = $d;
$d->c = $c;
$storage1 = new \SplObjectStorage;
$storage1->attach($a);
$storage1->attach($b);
$storage2 = new \SplObjectStorage;
$storage2->attach($b);
$storage1hash = \spl_object_hash($storage1);
$storage2hash = \spl_object_hash($storage2);
$dom1 = new \DOMDocument;
$dom1->preserveWhiteSpace = false;
$dom1->loadXML('<root></root>');
$dom2 = new \DOMDocument;
$dom2->preserveWhiteSpace = false;
$dom2->loadXML('<root><foo/></root>');
return [
[1, 0, <<<EOF
Failed asserting that 0 matches expected 1.
EOF
],
[1.1, 0, <<<EOF
Failed asserting that 0 matches expected 1.1.
EOF
],
['a', 'b', <<<EOF
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'a'
+'b'
EOF
],
["a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk", "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk", <<<EOF
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
'a\\n
-b\\n
+p\\n
c\\n
d\\n
e\\n
@@ @@
g\\n
h\\n
i\\n
-j\\n
+w\\n
k'
EOF
],
[1, [0], <<<EOF
Array (...) does not match expected type "integer".
EOF
],
[[0], 1, <<<EOF
1 does not match expected type "array".
EOF
],
[[0], [1], <<<EOF
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 0 => 0
+ 0 => 1
)
EOF
],
[[true], ['true'], <<<EOF
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 0 => true
+ 0 => 'true'
)
EOF
],
[[0, [1], [2], 3], [0, [4], [2], 3], <<<EOF
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
0 => 0
1 => Array (
- 0 => 1
+ 0 => 4
)
2 => Array (...)
3 => 3
)
EOF
],
[$a, [0], <<<EOF
Array (...) does not match expected type "object".
EOF
],
[[0], $a, <<<EOF
stdClass Object (...) does not match expected type "array".
EOF
],
[$a, $b, <<<EOF
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
stdClass Object (
- 'foo' => 'bar'
)
EOF
],
[$c, $d, <<<EOF
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
stdClass Object (
'foo' => 'bar'
- 'int' => 1
+ 'int' => 2
'array' => Array (
0 => 0
1 => Array (
- 0 => 1
+ 0 => 4
)
2 => Array (...)
3 => 3
@@ @@
)
'related' => stdClass Object (
'foo' => 'a\\n
- b\\n
+ p\\n
c\\n
d\\n
e\\n
@@ @@
g\\n
h\\n
i\\n
- j\\n
+ w\\n
k'
)
'self' => stdClass Object (...)
'c' => stdClass Object (...)
)
EOF
],
[$dom1, $dom2, <<<EOF
Failed asserting that two DOM documents are equal.
--- Expected
+++ Actual
@@ @@
<?xml version="1.0"?>
-<root/>
+<root>
+ <foo/>
+</root>
EOF
],
[
new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')),
new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/Chicago')),
<<<EOF
Failed asserting that two DateTime objects are equal.
--- Expected
+++ Actual
@@ @@
-2013-03-29T04:13:35.000000-0400
+2013-03-29T04:13:35.000000-0500
EOF
],
[$storage1, $storage2, <<<EOF
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
-SplObjectStorage Object &$storage1hash (
- '$ahash' => Array &0 (
- 'obj' => stdClass Object &$ahash (
- 'foo' => 'bar'
- )
- 'inf' => null
- )
- '$bhash' => Array &1 (
+SplObjectStorage Object &$storage2hash (
+ '$bhash' => Array &0 (
'obj' => stdClass Object &$bhash ()
'inf' => null
)
)
EOF
],
];
}
/**
* Removes spaces in front of newlines
*
* @param string $string
*
* @return string
*/
private function trimnl($string)
{
return \preg_replace('/[ ]*\n/', "\n", $string);
}
}

View File

@@ -1,197 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class IsIdenticalTest extends ConstraintTestCase
{
public function testConstraintIsIdentical(): void
{
$a = new \stdClass;
$b = new \stdClass;
$constraint = new IsIdentical($a);
$this->assertFalse($constraint->evaluate($b, '', true));
$this->assertTrue($constraint->evaluate($a, '', true));
$this->assertEquals('is identical to an object of class "stdClass"', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate($b);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that two variables reference the same object.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintIsIdentical2(): void
{
$a = new \stdClass;
$b = new \stdClass;
$constraint = new IsIdentical($a);
try {
$constraint->evaluate($b, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that two variables reference the same object.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintIsIdentical3(): void
{
$constraint = new IsIdentical('a');
try {
$constraint->evaluate('b', 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that two strings are identical.
--- Expected
+++ Actual
@@ @@
-'a'
+'b'
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintIsIdenticalArrayDiff(): void
{
$expected = [1, 2, 3, 4, 5, 6];
$actual = [1, 2, 33, 4, 5, 6];
$constraint = new IsIdentical($expected);
try {
$constraint->evaluate($actual, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertSame(
<<<EOF
custom message
Failed asserting that two arrays are identical.
--- Expected
+++ Actual
@@ @@
Array &0 (
0 => 1
1 => 2
- 2 => 3
+ 2 => 33
3 => 4
4 => 5
5 => 6
)
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintIsIdenticalNestedArrayDiff(): void
{
$expected = [
['A' => 'B'],
[
'C' => [
'D',
'E',
],
],
];
$actual = [
['A' => 'C'],
[
'C' => [
'C',
'E',
'F'
],
],
];
$constraint = new IsIdentical($expected);
try {
$constraint->evaluate($actual, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that two arrays are identical.
--- Expected
+++ Actual
@@ @@
Array &0 (
0 => Array &1 (
- 'A' => 'B'
+ 'A' => 'C'
)
1 => Array &2 (
'C' => Array &3 (
- 0 => 'D'
+ 0 => 'C'
1 => 'E'
+ 2 => 'F'
)
)
)
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,41 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
final class IsInstanceOfTest extends ConstraintTestCase
{
public function testConstraintInstanceOf(): void
{
$constraint = new IsInstanceOf(\stdClass::class);
self::assertTrue($constraint->evaluate(new \stdClass, '', true));
}
public function testConstraintFailsOnString(): void
{
$constraint = new IsInstanceOf(\stdClass::class);
try {
$constraint->evaluate('stdClass');
} catch (ExpectationFailedException $e) {
self::assertSame(
<<<EOT
Failed asserting that 'stdClass' is an instance of class "stdClass".
EOT
,
TestFailure::exceptionToString($e)
);
}
}
}

View File

@@ -1,34 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
class IsJsonTest extends ConstraintTestCase
{
public static function evaluateDataprovider()
{
return [
'valid JSON' => [true, '{}'],
'empty string should be treated as invalid JSON' => [false, ''],
];
}
/**
* @dataProvider evaluateDataprovider
*
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testEvaluate($expected, $jsonOther): void
{
$constraint = new IsJson;
$this->assertEquals($expected, $constraint->evaluate($jsonOther, '', true));
}
}

View File

@@ -1,66 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class IsNullTest extends ConstraintTestCase
{
public function testConstraintIsNull(): void
{
$constraint = new IsNull();
$this->assertFalse($constraint->evaluate(0, '', true));
$this->assertTrue($constraint->evaluate(null, '', true));
$this->assertEquals('is null', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(0);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that 0 is null.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintIsNull2(): void
{
$constraint = new IsNull();
try {
$constraint->evaluate(0, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that 0 is null.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,42 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class IsReadableTest extends ConstraintTestCase
{
public function testConstraintIsReadable(): void
{
$constraint = new IsReadable();
$this->assertFalse($constraint->evaluate('foo', '', true));
$this->assertEquals('is readable', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate('foo');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that "foo" is readable.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,111 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class IsTypeTest extends ConstraintTestCase
{
public function testConstraintIsType(): void
{
$constraint = Assert::isType('string');
$this->assertFalse($constraint->evaluate(0, '', true));
$this->assertTrue($constraint->evaluate('', '', true));
$this->assertEquals('is of type "string"', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(new \stdClass);
} catch (ExpectationFailedException $e) {
$this->assertStringMatchesFormat(
<<<EOF
Failed asserting that stdClass Object &%x () is of type "string".
EOF
,
$this->trimnl(TestFailure::exceptionToString($e))
);
return;
}
$this->fail();
}
public function testConstraintIsType2(): void
{
$constraint = Assert::isType('string');
try {
$constraint->evaluate(new \stdClass, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertStringMatchesFormat(
<<<EOF
custom message
Failed asserting that stdClass Object &%x () is of type "string".
EOF
,
$this->trimnl(TestFailure::exceptionToString($e))
);
return;
}
$this->fail();
}
/**
* @dataProvider resources
*/
public function testConstraintIsResourceTypeEvaluatesCorrectlyWithResources($resource): void
{
$constraint = Assert::isType('resource');
$this->assertTrue($constraint->evaluate($resource, '', true));
@\fclose($resource);
}
public function resources()
{
$fh = \fopen(__FILE__, 'r');
\fclose($fh);
return [
'open resource' => [\fopen(__FILE__, 'r')],
'closed resource' => [$fh],
];
}
public function testIterableTypeIsSupported(): void
{
$constraint = Assert::isType('iterable');
$this->assertFalse($constraint->evaluate('', '', true));
$this->assertTrue($constraint->evaluate([], '', true));
$this->assertEquals('is of type "iterable"', $constraint->toString());
}
/**
* Removes spaces in front of newlines
*
* @param string $string
*
* @return string
*/
private function trimnl($string)
{
return \preg_replace('/[ ]*\n/', "\n", $string);
}
}

View File

@@ -1,42 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class IsWritableTest extends ConstraintTestCase
{
public function testConstraintIsWritable(): void
{
$constraint = new IsWritable();
$this->assertFalse($constraint->evaluate('foo', '', true));
$this->assertEquals('is writable', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate('foo');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that "foo" is writable.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,87 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\TestCase;
class JsonMatchesErrorMessageProviderTest extends TestCase
{
public static function determineJsonErrorDataprovider()
{
return [
'JSON_ERROR_NONE' => [
null, 'json_error_none', ''
],
'JSON_ERROR_DEPTH' => [
'Maximum stack depth exceeded', \JSON_ERROR_DEPTH, ''
],
'prefixed JSON_ERROR_DEPTH' => [
'TUX: Maximum stack depth exceeded', \JSON_ERROR_DEPTH, 'TUX: '
],
'JSON_ERROR_STATE_MISMatch' => [
'Underflow or the modes mismatch', \JSON_ERROR_STATE_MISMATCH, ''
],
'JSON_ERROR_CTRL_CHAR' => [
'Unexpected control character found', \JSON_ERROR_CTRL_CHAR, ''
],
'JSON_ERROR_SYNTAX' => [
'Syntax error, malformed JSON', \JSON_ERROR_SYNTAX, ''
],
'JSON_ERROR_UTF8`' => [
'Malformed UTF-8 characters, possibly incorrectly encoded',
\JSON_ERROR_UTF8,
''
],
'Invalid error indicator' => [
'Unknown error', 55, ''
],
];
}
public static function translateTypeToPrefixDataprovider()
{
return [
'expected' => ['Expected value JSON decode error - ', 'expected'],
'actual' => ['Actual value JSON decode error - ', 'actual'],
'default' => ['', ''],
];
}
/**
* @dataProvider translateTypeToPrefixDataprovider
*
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testTranslateTypeToPrefix($expected, $type): void
{
$this->assertEquals(
$expected,
JsonMatchesErrorMessageProvider::translateTypeToPrefix($type)
);
}
/**
* @dataProvider determineJsonErrorDataprovider
*
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testDetermineJsonError($expected, $error, $prefix): void
{
$this->assertEquals(
$expected,
JsonMatchesErrorMessageProvider::determineJsonError(
$error,
$prefix
)
);
}
}

View File

@@ -1,94 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Util\Json;
class JsonMatchesTest extends ConstraintTestCase
{
public static function evaluateDataprovider()
{
return [
'valid JSON' => [true, \json_encode(['Mascott' => 'Tux']), \json_encode(['Mascott' => 'Tux'])],
'error syntax' => [false, '{"Mascott"::}', \json_encode(['Mascott' => 'Tux'])],
'error UTF-8' => [false, \json_encode('\xB1\x31'), \json_encode(['Mascott' => 'Tux'])],
'invalid JSON in class instantiation' => [false, \json_encode(['Mascott' => 'Tux']), '{"Mascott"::}'],
'string type not equals number' => [false, '{"age": "5"}', '{"age": 5}'],
'string type not equals boolean' => [false, '{"age": "true"}', '{"age": true}'],
'string type not equals null' => [false, '{"age": "null"}', '{"age": null}'],
'object fields are unordered' => [true, '{"first":1, "second":"2"}', '{"second":"2", "first":1}'],
'child object fields are unordered' => [true, '{"Mascott": {"name":"Tux", "age":5}}', '{"Mascott": {"age":5, "name":"Tux"}}'],
'null field different from missing field' => [false, '{"present": true, "missing": null}', '{"present": true}'],
'array elements are ordered' => [false, '["first", "second"]', '["second", "first"]'],
'single boolean valid json' => [true, 'true', 'true'],
'single number valid json' => [true, '5.3', '5.3'],
'single null valid json' => [true, 'null', 'null'],
'objects are not arrays' => [false, '{}', '[]']
];
}
public static function evaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatchDataprovider()
{
return [
'error UTF-8' => [\json_encode('\xB1\x31'), \json_encode(['Mascott' => 'Tux'])],
'string type not equals number' => ['{"age": "5"}', '{"age": 5}'],
'string type not equals boolean' => ['{"age": "true"}', '{"age": true}'],
'string type not equals null' => ['{"age": "null"}', '{"age": null}'],
'null field different from missing field' => ['{"present": true, "missing": null}', '{"present": true}'],
'array elements are ordered' => ['["first", "second"]', '["second", "first"]']
];
}
/**
* @dataProvider evaluateDataprovider
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testEvaluate($expected, $jsonOther, $jsonValue): void
{
$constraint = new JsonMatches($jsonValue);
$this->assertEquals($expected, $constraint->evaluate($jsonOther, '', true));
}
/**
* @dataProvider evaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatchDataprovider
*
* @throws ExpectationFailedException
* @throws \PHPUnit\Framework\AssertionFailedError
* @throws \PHPUnit\Framework\Exception
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testEvaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatch($jsonOther, $jsonValue): void
{
$constraint = new JsonMatches($jsonValue);
try {
$constraint->evaluate($jsonOther, '', false);
$this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class));
} catch (ExpectationFailedException $expectedException) {
$comparisonFailure = $expectedException->getComparisonFailure();
$this->assertNotNull($comparisonFailure);
$this->assertSame(Json::prettify($jsonOther), $comparisonFailure->getActualAsString());
$this->assertSame(Json::prettify($jsonValue), $comparisonFailure->getExpectedAsString());
$this->assertSame('Failed asserting that two json values are equal.', $comparisonFailure->getMessage());
}
}
public function testToString(): void
{
$jsonValue = \json_encode(['Mascott' => 'Tux']);
$constraint = new JsonMatches($jsonValue);
$this->assertEquals('matches JSON string "' . $jsonValue . '"', $constraint->toString());
}
}

View File

@@ -1,66 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class LessThanTest extends ConstraintTestCase
{
public function testConstraintLessThan(): void
{
$constraint = new LessThan(1);
$this->assertTrue($constraint->evaluate(0, '', true));
$this->assertFalse($constraint->evaluate(1, '', true));
$this->assertEquals('is less than 1', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(1);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that 1 is less than 1.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintLessThan2(): void
{
$constraint = new LessThan(1);
try {
$constraint->evaluate(1, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that 1 is less than 1.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,237 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
final class LogicalAndTest extends ConstraintTestCase
{
public function testSetConstraintsRejectsInvalidConstraint(): void
{
$constraints = [
new \TruthyConstraint(),
new \FalsyConstraint(),
new \stdClass(),
];
$constraint = new LogicalAnd();
$this->expectException(Exception::class);
$this->expectExceptionMessage(\sprintf(
'All parameters to %s must be a constraint object.',
LogicalAnd::class
));
$constraint->setConstraints($constraints);
}
public function testCountReturnsCountOfComposedConstraints(): void
{
$counts = [
3,
5,
8,
];
$constraints = \array_map(function (int $count) {
return \CountConstraint::fromCount($count);
}, $counts);
$constraint = new LogicalAnd();
$constraint->setConstraints($constraints);
$expected = \array_sum($counts);
$this->assertSame($expected, $constraint->count());
}
public function testToStringReturnsImplodedStringRepresentationOfComposedConstraintsGluedWithAnd(): void
{
$names = [
'is healthy',
'is rich in amino acids',
'is rich in unsaturated fats',
];
$constraints = \array_map(function (string $name) {
return \NamedConstraint::fromName($name);
}, $names);
$constraint = new LogicalAnd();
$constraint->setConstraints($constraints);
$expected = \implode(' and ', $names);
$this->assertSame($expected, $constraint->toString());
}
/**
* @dataProvider providerFailingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateReturnsFalseIfAnyOfTheComposedConstraintsEvaluateToFalse(array $constraints): void
{
$constraint = new LogicalAnd();
$constraint->setConstraints($constraints);
$this->assertFalse($constraint->evaluate('whatever', '', true));
}
/**
* @dataProvider providerSucceedingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateReturnsTrueIfAllOfTheComposedConstraintsEvaluateToTrue(array $constraints): void
{
$constraint = new LogicalAnd();
$constraint->setConstraints($constraints);
$this->assertTrue($constraint->evaluate('whatever', '', true));
}
/**
* @dataProvider providerFailingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateThrowsExceptionIfAnyOfTheComposedConstraintsEvaluateToFalse(array $constraints): void
{
$other = 'whatever';
$constraint = new LogicalAnd();
$constraint->setConstraints($constraints);
try {
$constraint->evaluate($other);
} catch (ExpectationFailedException $exception) {
$toString = $this->stringify($constraints);
$expectedDescription = <<<EOF
Failed asserting that '$other' $toString.
EOF;
$this->assertEquals($expectedDescription, TestFailure::exceptionToString($exception));
return;
}
$this->fail();
}
/**
* @dataProvider providerFailingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateThrowsExceptionWithCustomMessageIfAnyOfTheComposedConstraintsEvaluateToFalse(array $constraints): void
{
$other = 'whatever';
$customDescription = 'Not very happy about the results at this point in time, I have to admit!';
$constraint = new LogicalAnd();
$constraint->setConstraints($constraints);
try {
$constraint->evaluate(
$other,
$customDescription
);
} catch (ExpectationFailedException $exception) {
$toString = $this->stringify($constraints);
$expectedDescription = <<<EOF
$customDescription
Failed asserting that '$other' $toString.
EOF;
$this->assertEquals($expectedDescription, TestFailure::exceptionToString($exception));
return;
}
$this->fail();
}
/**
* @dataProvider providerSucceedingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateReturnsNothingIfAllOfTheComposedConstraintsEvaluateToTrue(array $constraints): void
{
$constraint = new LogicalAnd();
$constraint->setConstraints($constraints);
$this->assertNull($constraint->evaluate('whatever'));
}
public function providerFailingConstraints(): \Generator
{
$values = [
'single' => [
new \FalsyConstraint(),
],
'multiple' => [
new \TruthyConstraint(),
new \FalsyConstraint(),
new \TruthyConstraint(),
],
];
foreach ($values as $key => $constraints) {
yield $key => [
$constraints,
];
}
}
public function providerSucceedingConstraints(): \Generator
{
$values = [
'single' => [
new \TruthyConstraint(),
],
'multiple' => [
new \TruthyConstraint(),
new \TruthyConstraint(),
new \TruthyConstraint(),
],
];
foreach ($values as $key => $constraints) {
yield $key => [
$constraints,
];
}
}
private function stringify(array $constraints): string
{
return \implode(
' and ',
\array_map(function (Constraint $constraint) {
return $constraint->toString();
}, $constraints)
);
}
}

View File

@@ -1,232 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
final class LogicalOrTest extends ConstraintTestCase
{
public function testSetConstraintsDecoratesNonConstraintWithIsEqual(): void
{
$constraints = [
new \stdClass(),
];
$constraint = new LogicalOr();
$constraint->setConstraints($constraints);
$this->assertTrue($constraint->evaluate(new \stdClass(), '', true));
}
public function testCountReturnsCountOfComposedConstraints(): void
{
$counts = [
3,
5,
8,
];
$constraints = \array_map(function (int $count) {
return \CountConstraint::fromCount($count);
}, $counts);
$constraint = new LogicalOr();
$constraint->setConstraints($constraints);
$expected = \array_sum($counts);
$this->assertSame($expected, $constraint->count());
}
public function testToStringReturnsImplodedStringRepresentationOfComposedConstraintsGluedWithOr(): void
{
$names = [
'is healthy',
'is rich in amino acids',
'is rich in unsaturated fats',
];
$constraints = \array_map(function (string $name) {
return \NamedConstraint::fromName($name);
}, $names);
$constraint = new LogicalOr();
$constraint->setConstraints($constraints);
$expected = \implode(' or ', $names);
$this->assertSame($expected, $constraint->toString());
}
/**
* @dataProvider providerFailingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateReturnsFalseIfAllOfTheComposedConstraintsEvaluateToFalse(array $constraints): void
{
$constraint = new LogicalOr();
$constraint->setConstraints($constraints);
$this->assertFalse($constraint->evaluate('whatever', '', true));
}
/**
* @dataProvider providerSucceedingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateReturnsTrueIfAnyOfTheComposedConstraintsEvaluateToTrue(array $constraints): void
{
$constraint = new LogicalOr();
$constraint->setConstraints($constraints);
$this->assertTrue($constraint->evaluate('whatever', '', true));
}
/**
* @dataProvider providerFailingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateThrowsExceptionIfAllOfTheComposedConstraintsEvaluateToFalse(array $constraints): void
{
$other = 'whatever';
$constraint = new LogicalOr();
$constraint->setConstraints($constraints);
try {
$constraint->evaluate($other);
} catch (ExpectationFailedException $exception) {
$toString = $this->stringify($constraints);
$expectedDescription = <<<EOF
Failed asserting that '$other' $toString.
EOF;
$this->assertEquals($expectedDescription, TestFailure::exceptionToString($exception));
return;
}
$this->fail();
}
/**
* @dataProvider providerFailingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateThrowsExceptionWithCustomMessageIfAllOfTheComposedConstraintsEvaluateToFalse(array $constraints): void
{
$other = 'whatever';
$customDescription = 'Not very happy about the results at this point in time, I have to admit!';
$constraint = new LogicalOr();
$constraint->setConstraints($constraints);
try {
$constraint->evaluate(
$other,
$customDescription
);
} catch (ExpectationFailedException $exception) {
$toString = $this->stringify($constraints);
$expectedDescription = <<<EOF
$customDescription
Failed asserting that '$other' $toString.
EOF;
$this->assertEquals($expectedDescription, TestFailure::exceptionToString($exception));
return;
}
$this->fail();
}
/**
* @dataProvider providerSucceedingConstraints
*
* @param Constraint[] $constraints
*/
public function testEvaluateReturnsNothingIfAnyOfTheComposedConstraintsEvaluateToTrue(array $constraints): void
{
$constraint = new LogicalOr();
$constraint->setConstraints($constraints);
$this->assertNull($constraint->evaluate('whatever'));
}
public function providerFailingConstraints(): \Generator
{
$values = [
'single' => [
new \FalsyConstraint(),
new \FalsyConstraint(),
new \FalsyConstraint(),
],
'multiple' => [
new \FalsyConstraint(),
new \FalsyConstraint(),
new \FalsyConstraint(),
],
];
foreach ($values as $key => $constraints) {
yield $key => [
$constraints,
];
}
}
public function providerSucceedingConstraints(): \Generator
{
$values = [
'single' => [
new \TruthyConstraint(),
],
'multiple' => [
new \FalsyConstraint(),
new \TruthyConstraint(),
new \FalsyConstraint(),
],
];
foreach ($values as $key => $constraints) {
yield $key => [
$constraints,
];
}
}
private function stringify(array $constraints): string
{
return \implode(
' or ',
\array_map(function (Constraint $constraint) {
return $constraint->toString();
}, $constraints)
);
}
}

View File

@@ -1,44 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Framework\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\LogicalXor;
use PHPUnit\Framework\TestCase;
final class LogicalXorTest extends TestCase
{
public function testFromConstraintsReturnsConstraint(): void
{
$other = 'Foo';
$count = 5;
$constraints = \array_map(function () use ($other) {
static $count = 0;
$constraint = $this->getMockBuilder(Constraint::class)->getMock();
$constraint
->expects($this->once())
->method('evaluate')
->with($this->identicalTo($other))
->willReturn($count % 2 === 1);
++$count;
return $constraint;
}, \array_fill(0, $count, null));
$constraint = LogicalXor::fromConstraints(...$constraints);
$this->assertInstanceOf(LogicalXor::class, $constraint);
$this->assertTrue($constraint->evaluate($other, '', true));
}
}

View File

@@ -1,66 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class ObjectHasAttributeTest extends ConstraintTestCase
{
public function testConstraintObjectHasAttribute(): void
{
$constraint = new ObjectHasAttribute('privateAttribute');
$this->assertTrue($constraint->evaluate(new \ClassWithNonPublicAttributes, '', true));
$this->assertFalse($constraint->evaluate(new \stdClass, '', true));
$this->assertEquals('has attribute "privateAttribute"', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate(new \stdClass);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that object of class "stdClass" has attribute "privateAttribute".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintObjectHasAttribute2(): void
{
$constraint = new ObjectHasAttribute('privateAttribute');
try {
$constraint->evaluate(new \stdClass, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that object of class "stdClass" has attribute "privateAttribute".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,66 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class RegularExpressionTest extends ConstraintTestCase
{
public function testConstraintRegularExpression(): void
{
$constraint = new RegularExpression('/foo/');
$this->assertFalse($constraint->evaluate('barbazbar', '', true));
$this->assertTrue($constraint->evaluate('barfoobar', '', true));
$this->assertEquals('matches PCRE pattern "/foo/"', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate('barbazbar');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that 'barbazbar' matches PCRE pattern "/foo/".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintRegularExpression2(): void
{
$constraint = new RegularExpression('/foo/');
try {
$constraint->evaluate('barbazbar', 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that 'barbazbar' matches PCRE pattern "/foo/".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,62 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class SameSizeTest extends ConstraintTestCase
{
public function testConstraintSameSizeWithAnArray(): void
{
$constraint = new SameSize([1, 2, 3, 4, 5]);
$this->assertTrue($constraint->evaluate([6, 7, 8, 9, 10], '', true));
$this->assertFalse($constraint->evaluate([1, 2, 3, 4], '', true));
}
public function testConstraintSameSizeWithAnIteratorWhichDoesNotImplementCountable(): void
{
$constraint = new SameSize(new \TestIterator([1, 2, 3, 4, 5]));
$this->assertTrue($constraint->evaluate(new \TestIterator([6, 7, 8, 9, 10]), '', true));
$this->assertFalse($constraint->evaluate(new \TestIterator([1, 2, 3, 4]), '', true));
}
public function testConstraintSameSizeWithAnObjectImplementingCountable(): void
{
$constraint = new SameSize(new \ArrayObject([1, 2, 3, 4, 5]));
$this->assertTrue($constraint->evaluate(new \ArrayObject([6, 7, 8, 9, 10]), '', true));
$this->assertFalse($constraint->evaluate(new \ArrayObject([1, 2, 3, 4]), '', true));
}
public function testConstraintSameSizeFailing(): void
{
$constraint = new SameSize([1, 2, 3, 4, 5]);
try {
$constraint->evaluate([1, 2]);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that actual size 2 matches expected size 5.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,96 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class StringContainsTest extends ConstraintTestCase
{
public function testConstraintStringContains(): void
{
$constraint = new StringContains('foo');
$this->assertFalse($constraint->evaluate('barbazbar', '', true));
$this->assertTrue($constraint->evaluate('barfoobar', '', true));
$this->assertEquals('contains "foo"', $constraint->toString());
$this->assertCount(1, $constraint);
try {
$constraint->evaluate('barbazbar');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that 'barbazbar' contains "foo".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintStringContainsWhenIgnoreCase(): void
{
$constraint = new StringContains('oryginał', true);
$this->assertFalse($constraint->evaluate('oryginal', '', true));
$this->assertTrue($constraint->evaluate('ORYGINAŁ', '', true));
$this->assertTrue($constraint->evaluate('oryginał', '', true));
$this->assertEquals('contains "oryginał"', $constraint->toString());
$this->assertEquals(1, \count($constraint));
$this->expectException(ExpectationFailedException::class);
$constraint->evaluate('oryginal');
}
public function testConstraintStringContainsForUtf8StringWhenNotIgnoreCase(): void
{
$constraint = new StringContains('oryginał', false);
$this->assertFalse($constraint->evaluate('oryginal', '', true));
$this->assertFalse($constraint->evaluate('ORYGINAŁ', '', true));
$this->assertTrue($constraint->evaluate('oryginał', '', true));
$this->assertEquals('contains "oryginał"', $constraint->toString());
$this->assertEquals(1, \count($constraint));
$this->expectException(ExpectationFailedException::class);
$constraint->evaluate('oryginal');
}
public function testConstraintStringContains2(): void
{
$constraint = new StringContains('foo');
try {
$constraint->evaluate('barbazbar', 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that 'barbazbar' contains "foo".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,87 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class StringEndsWithTest extends ConstraintTestCase
{
public function testConstraintStringEndsWithCorrectValueAndReturnResult(): void
{
$constraint = new StringEndsWith('suffix');
$this->assertTrue($constraint->evaluate('foosuffix', '', true));
}
public function testConstraintStringEndsWithNotCorrectValueAndReturnResult(): void
{
$constraint = new StringEndsWith('suffix');
$this->assertFalse($constraint->evaluate('suffixerror', '', true));
}
public function testConstraintStringEndsWithToStringMethod(): void
{
$constraint = new StringEndsWith('suffix');
$this->assertEquals('ends with "suffix"', $constraint->toString());
}
public function testConstraintStringEndsWithCountMethod(): void
{
$constraint = new StringEndsWith('suffix');
$this->assertCount(1, $constraint);
}
public function testConstraintStringEndsWithNotCorrectValueAndExpectation(): void
{
$constraint = new StringEndsWith('suffix');
try {
$constraint->evaluate('error');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that 'error' ends with "suffix".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintStringEndsWithNotCorrectValueExceptionAndCustomMessage(): void
{
$constraint = new StringEndsWith('suffix');
try {
$constraint->evaluate('error', 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that 'error' ends with "suffix".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,108 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
class StringMatchesFormatDescriptionTest extends ConstraintTestCase
{
public function testConstraintStringMatchesCharacter(): void
{
$constraint = new StringMatchesFormatDescription('*%c*');
$this->assertFalse($constraint->evaluate('**', '', true));
$this->assertTrue($constraint->evaluate('***', '', true));
$this->assertEquals('matches PCRE pattern "/^\*.\*$/s"', $constraint->toString());
$this->assertCount(1, $constraint);
}
public function testConstraintStringMatchesString(): void
{
$constraint = new StringMatchesFormatDescription('*%s*');
$this->assertFalse($constraint->evaluate('**', '', true));
$this->assertTrue($constraint->evaluate('***', '', true));
$this->assertEquals('matches PCRE pattern "/^\*[^\r\n]+\*$/s"', $constraint->toString());
$this->assertCount(1, $constraint);
}
public function testConstraintStringMatchesInteger(): void
{
$constraint = new StringMatchesFormatDescription('*%i*');
$this->assertFalse($constraint->evaluate('**', '', true));
$this->assertTrue($constraint->evaluate('*0*', '', true));
$this->assertEquals('matches PCRE pattern "/^\*[+-]?\d+\*$/s"', $constraint->toString());
$this->assertCount(1, $constraint);
}
public function testConstraintStringMatchesUnsignedInt(): void
{
$constraint = new StringMatchesFormatDescription('*%d*');
$this->assertFalse($constraint->evaluate('**', '', true));
$this->assertTrue($constraint->evaluate('*0*', '', true));
$this->assertEquals('matches PCRE pattern "/^\*\d+\*$/s"', $constraint->toString());
$this->assertCount(1, $constraint);
}
public function testConstraintStringMatchesHexadecimal(): void
{
$constraint = new StringMatchesFormatDescription('*%x*');
$this->assertFalse($constraint->evaluate('**', '', true));
$this->assertTrue($constraint->evaluate('*0f0f0f*', '', true));
$this->assertEquals('matches PCRE pattern "/^\*[0-9a-fA-F]+\*$/s"', $constraint->toString());
$this->assertCount(1, $constraint);
}
public function testConstraintStringMatchesFloat(): void
{
$constraint = new StringMatchesFormatDescription('*%f*');
$this->assertFalse($constraint->evaluate('**', '', true));
$this->assertTrue($constraint->evaluate('*1.0*', '', true));
$this->assertEquals('matches PCRE pattern "/^\*[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?\*$/s"', $constraint->toString());
$this->assertCount(1, $constraint);
}
public function testConstraintStringMatchesNewline(): void
{
$constraint = new StringMatchesFormatDescription("\r\n");
$this->assertFalse($constraint->evaluate("*\r\n", '', true));
$this->assertTrue($constraint->evaluate("\r\n", '', true));
$this->assertEquals("matches PCRE pattern \"/^\n$/s\"", $constraint->toString());
$this->assertCount(1, $constraint);
}
public function testFailureMessageWithNewlines(): void
{
$constraint = new StringMatchesFormatDescription("%c\nfoo\n%c");
try {
$constraint->evaluate("*\nbar\n*");
$this->fail('Expected ExpectationFailedException, but it was not thrown.');
} catch (ExpectationFailedException $e) {
$expected = <<<EOD
Failed asserting that string matches format description.
--- Expected
+++ Actual
@@ @@
*
-foo
+bar
*
EOD;
$this->assertEquals($expected, $e->getMessage());
}
}
}

View File

@@ -1,88 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class StringStartsWithTest extends ConstraintTestCase
{
public function testConstraintStringStartsWithCorrectValueAndReturnResult(): void
{
$constraint = new StringStartsWith('prefix');
$this->assertTrue($constraint->evaluate('prefixfoo', '', true));
}
public function testConstraintStringStartsWithNotCorrectValueAndReturnResult(): void
{
$constraint = new StringStartsWith('prefix');
$this->assertFalse($constraint->evaluate('error', '', true));
}
public function testConstraintStringStartsWithToStringMethod(): void
{
$constraint = new StringStartsWith('prefix');
$this->assertEquals('starts with "prefix"', $constraint->toString());
}
public function testConstraintStringStartsWitCountMethod(): void
{
$constraint = new StringStartsWith('prefix');
$this->assertCount(1, $constraint);
}
public function testConstraintStringStartsWithNotCorrectValueAndExpectation(): void
{
$constraint = new StringStartsWith('prefix');
try {
$constraint->evaluate('error');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that 'error' starts with "prefix".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintStringStartsWithNotCorrectValueExceptionAndCustomMessage(): void
{
$constraint = new StringStartsWith('prefix');
try {
$constraint->evaluate('error', 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message\nFailed asserting that 'error' starts with "prefix".
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

View File

@@ -1,170 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestFailure;
class TraversableContainsTest extends ConstraintTestCase
{
public function testConstraintTraversableCheckForObjectIdentityForDefaultCase(): void
{
$constraint = new TraversableContains('foo');
$this->assertTrue($constraint->evaluate([0], '', true));
$this->assertTrue($constraint->evaluate([true], '', true));
}
public function testConstraintTraversableCheckForObjectIdentityForPrimitiveType(): void
{
$constraint = new TraversableContains('foo', true, true);
$this->assertFalse($constraint->evaluate([0], '', true));
$this->assertFalse($constraint->evaluate([true], '', true));
}
public function testConstraintTraversableWithRightValue(): void
{
$constraint = new TraversableContains('foo');
$this->assertTrue($constraint->evaluate(['foo'], '', true));
}
public function testConstraintTraversableWithFailValue(): void
{
$constraint = new TraversableContains('foo');
$this->assertFalse($constraint->evaluate(['bar'], '', true));
}
public function testConstraintTraversableCountMethods(): void
{
$constraint = new TraversableContains('foo');
$this->assertCount(1, $constraint);
}
public function testConstraintTraversableEvaluateMethodWithFailExample(): void
{
$constraint = new TraversableContains('foo');
try {
$constraint->evaluate(['bar']);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that an array contains 'foo'.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintTraversableEvaluateMethodWithFailExampleWithCustomMessage(): void
{
$constraint = new TraversableContains('foo');
try {
$constraint->evaluate(['bar'], 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
custom message
Failed asserting that an array contains 'foo'.
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintTraversableToStringMethodsWithStdClass(): void
{
$object = new \stdClass;
$constraint = new TraversableContains($object);
$this->assertStringMatchesFormat('contains stdClass Object &%s ()', $constraint->toString());
}
public function testConstraintTraversableToStringMethods(): void
{
$constraint = new TraversableContains('foo');
$this->assertEquals("contains 'foo'", $constraint->toString());
}
public function testConstraintTraversableToStringMethodsWithSplObjectStorage(): void
{
$object = new \stdClass;
$constraint = new TraversableContains($object);
$storage = new \SplObjectStorage;
$this->assertFalse($constraint->evaluate($storage, '', true));
$storage->attach($object);
$this->assertTrue($constraint->evaluate($storage, '', true));
}
public function testConstraintTraversableStdClassForFailSplObjectStorage(): void
{
$object = new \stdClass;
$constraint = new TraversableContains($object);
try {
$constraint->evaluate(new \SplObjectStorage);
} catch (ExpectationFailedException $e) {
$this->assertStringMatchesFormat(
<<<EOF
Failed asserting that a traversable contains stdClass Object &%x ().
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
public function testConstraintTraversableStdClassForFailSplObjectStorageWithCustomMessage(): void
{
$object = new \stdClass;
$constraint = new TraversableContains($object);
try {
$constraint->evaluate(new \SplObjectStorage, 'custom message');
} catch (ExpectationFailedException $e) {
$this->assertStringMatchesFormat(
<<<EOF
custom message
Failed asserting that a traversable contains stdClass Object &%x ().
EOF
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,55 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework;
class ExceptionWrapperTest extends TestCase
{
/**
* @runInSeparateProcess
*/
public function testGetOriginalException(): void
{
$e = new \BadFunctionCallException('custom class exception');
$wrapper = new ExceptionWrapper($e);
$this->assertInstanceOf(\BadFunctionCallException::class, $wrapper->getOriginalException());
}
/**
* @runInSeparateProcess
*/
public function testGetOriginalExceptionWithPrevious(): void
{
$e = new \BadFunctionCallException('custom class exception', 0, new \Exception('previous'));
$wrapper = new ExceptionWrapper($e);
$this->assertInstanceOf(\BadFunctionCallException::class, $wrapper->getOriginalException());
}
/**
* @runInSeparateProcess
*/
public function testNoOriginalExceptionInStacktrace(): void
{
$e = new \BadFunctionCallException('custom class exception');
$wrapper = new ExceptionWrapper($e);
// Replace the only mention of "BadFunctionCallException" in wrapper
$wrapper->setClassName('MyException');
$data = \print_r($wrapper, 1);
$this->assertNotContains(
'BadFunctionCallException',
$data,
'Assert there is s no other BadFunctionCallException mention in stacktrace'
);
}
}

View File

@@ -1,74 +0,0 @@
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use PHPUnit\Framework\TestCase;
class InvocationMockerTest extends TestCase
{
public function testWillReturnWithOneValue(): void
{
$mock = $this->getMockBuilder(stdClass::class)
->setMethods(['foo'])
->getMock();
$mock->expects($this->any())
->method('foo')
->willReturn(1);
$this->assertEquals(1, $mock->foo());
}
public function testWillReturnWithMultipleValues(): void
{
$mock = $this->getMockBuilder(stdClass::class)
->setMethods(['foo'])
->getMock();
$mock->expects($this->any())
->method('foo')
->willReturn(1, 2, 3);
$this->assertEquals(1, $mock->foo());
$this->assertEquals(2, $mock->foo());
$this->assertEquals(3, $mock->foo());
}
public function testWillReturnOnConsecutiveCalls(): void
{
$mock = $this->getMockBuilder(stdClass::class)
->setMethods(['foo'])
->getMock();
$mock->expects($this->any())
->method('foo')
->willReturnOnConsecutiveCalls(1, 2, 3);
$this->assertEquals(1, $mock->foo());
$this->assertEquals(2, $mock->foo());
$this->assertEquals(3, $mock->foo());
}
public function testWillReturnByReference(): void
{
$mock = $this->getMockBuilder(stdClass::class)
->setMethods(['foo'])
->getMock();
$mock->expects($this->any())
->method('foo')
->willReturnReference($value);
$this->assertNull($mock->foo());
$value = 'foo';
$this->assertSame('foo', $mock->foo());
$value = 'bar';
$this->assertSame('bar', $mock->foo());
}
}

View File

@@ -1,135 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true, true)
--FILE--
<?php
trait BaseTrait
{
protected function hello()
{
return 'hello';
}
}
trait ChildTrait
{
use BaseTrait
{
hello as private hi;
}
protected function hello()
{
return 'hi';
}
protected function world()
{
return $this->hi();
}
}
class Foo
{
use ChildTrait;
public function speak()
{
return $this->world();
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['speak'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function speak()
{
$__phpunit_arguments = [];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 0) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'speak', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,105 +0,0 @@
--TEST--
https://github.com/sebastianbergmann/phpunit-mock-objects/issues/397
--FILE--
<?php
class C
{
public function m(?self $other): self
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
C::class,
[],
'MockC',
true,
true
);
print $mock['code'];
--EXPECT--
class MockC extends C implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['m'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function m(?C $other): C
{
$__phpunit_arguments = [$other];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 1) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 1; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'C', 'm', $__phpunit_arguments, 'C', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,154 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true, true)
--FILE--
<?php
abstract class Foo
{
public function one()
{
}
abstract public function two();
abstract protected function three();
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['one', 'two', 'three'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function one()
{
$__phpunit_arguments = [];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 0) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'one', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function two()
{
$__phpunit_arguments = [];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 0) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'two', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
protected function three()
{
$__phpunit_arguments = [];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 0) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'three', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,132 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true, true)
--FILE--
<?php
class Foo
{
public function bar(Foo $foo)
{
}
public function baz(Foo $foo)
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['bar', 'baz'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function bar(Foo $foo)
{
$__phpunit_arguments = [$foo];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 1) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 1; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'bar', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function baz(Foo $foo)
{
$__phpunit_arguments = [$foo];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 1) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 1; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'baz', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,84 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true)
--FILE--
<?php
class Foo
{
public function __clone()
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = [];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
parent::__clone();
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,83 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true)
--FILE--
<?php
class Foo
{
public function __construct()
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = [];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,83 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', false)
--FILE--
<?php
class Foo
{
public function __clone()
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
false
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = [];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,83 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true)
--FILE--
<?php
class Foo
{
public function __construct()
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = [];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,88 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true)
--FILE--
<?php
interface IFoo
{
public function __construct($bar);
}
class Foo implements IFoo
{
public function __construct($bar)
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = [];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,88 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true)
--FILE--
<?php
interface IFoo
{
public function __construct($bar);
}
class Foo implements IFoo
{
public function __construct($bar)
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = [];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,110 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', array('bar'), 'MockFoo', true, true)
--FILE--
<?php
class Foo
{
public function bar(Foo $foo)
{
}
public function baz(Foo $foo)
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
array('bar'),
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['bar'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function bar(Foo $foo)
{
$__phpunit_arguments = [$foo];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 1) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 1; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'bar', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,112 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('ClassWithDeprecatedMethod', [], 'MockFoo', TRUE, TRUE)
--FILE--
<?php
class ClassWithDeprecatedMethod
{
/**
* @deprecated this method
* is deprecated
*/
public function deprecatedMethod()
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'ClassWithDeprecatedMethod',
[],
'MockFoo',
TRUE,
TRUE
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends ClassWithDeprecatedMethod implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['deprecatedmethod'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function deprecatedMethod()
{
@trigger_error('The ClassWithDeprecatedMethod::deprecatedMethod method is deprecated (this method is deprecated).', E_USER_DEPRECATED);
$__phpunit_arguments = [];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 0) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'ClassWithDeprecatedMethod', 'deprecatedMethod', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,98 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true, true)
--FILE--
<?php
class Foo
{
public function method()
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['method'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function method()
{
$__phpunit_arguments = [];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 0) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'method', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,106 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('ClassWithMethodWithVariadicArguments', [], 'MockFoo', true, true)
--FILE--
<?php
class ClassWithMethodWithNullableTypehintedVariadicArguments
{
public function methodWithNullableTypehintedVariadicArguments($a, ?string ...$parameters)
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'ClassWithMethodWithNullableTypehintedVariadicArguments',
[],
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends ClassWithMethodWithNullableTypehintedVariadicArguments implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['methodwithnullabletypehintedvariadicarguments'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function methodWithNullableTypehintedVariadicArguments($a, ?string ...$parameters)
{
$__phpunit_arguments = [$a];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 1) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 1; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'ClassWithMethodWithNullableTypehintedVariadicArguments', 'methodWithNullableTypehintedVariadicArguments', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,106 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('ClassWithMethodWithVariadicArguments', [], 'MockFoo', true, true)
--FILE--
<?php
class ClassWithMethodWithTypehintedVariadicArguments
{
public function methodWithTypehintedVariadicArguments($a, string ...$parameters)
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'ClassWithMethodWithTypehintedVariadicArguments',
[],
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends ClassWithMethodWithTypehintedVariadicArguments implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['methodwithtypehintedvariadicarguments'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function methodWithTypehintedVariadicArguments($a, string ...$parameters)
{
$__phpunit_arguments = [$a];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 1) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 1; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'ClassWithMethodWithTypehintedVariadicArguments', 'methodWithTypehintedVariadicArguments', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,106 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('ClassWithMethodWithVariadicArguments', [], 'MockFoo', true, true)
--FILE--
<?php
class ClassWithMethodWithVariadicArguments
{
public function methodWithVariadicArguments($a, ...$parameters)
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'ClassWithMethodWithVariadicArguments',
[],
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends ClassWithMethodWithVariadicArguments implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['methodwithvariadicarguments'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function methodWithVariadicArguments($a, ...$parameters)
{
$__phpunit_arguments = [$a];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 1) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 1; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'ClassWithMethodWithVariadicArguments', 'methodWithVariadicArguments', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

View File

@@ -1,106 +0,0 @@
--TEST--
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true, true)
--FILE--
<?php
class Foo
{
public function bar(int $baz = PHP_INT_MIN)
{
}
}
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
$mock = $generator->generate(
'Foo',
[],
'MockFoo',
true,
true
);
print $mock['code'];
?>
--EXPECT--
class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject
{
private $__phpunit_invocationMocker;
private $__phpunit_originalObject;
private $__phpunit_configurable = ['bar'];
private $__phpunit_returnValueGeneration = true;
public function __clone()
{
$this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
}
public function bar(int $baz = PHP_INT_MIN)
{
$__phpunit_arguments = [$baz];
$__phpunit_count = func_num_args();
if ($__phpunit_count > 1) {
$__phpunit_arguments_tmp = func_get_args();
for ($__phpunit_i = 1; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
$__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
}
}
$__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
'Foo', 'bar', $__phpunit_arguments, '', $this, true
)
);
return $__phpunit_result;
}
public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
{
return $this->__phpunit_getInvocationMocker()->expects($matcher);
}
public function method()
{
$any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
$expects = $this->expects($any);
return call_user_func_array([$expects, 'method'], func_get_args());
}
public function __phpunit_setOriginalObject($originalObject)
{
$this->__phpunit_originalObject = $originalObject;
}
public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
{
$this->__phpunit_returnValueGeneration = $returnValueGeneration;
}
public function __phpunit_getInvocationMocker()
{
if ($this->__phpunit_invocationMocker === null) {
$this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
}
return $this->__phpunit_invocationMocker;
}
public function __phpunit_hasMatchers()
{
return $this->__phpunit_getInvocationMocker()->hasMatchers();
}
public function __phpunit_verify($unsetInvocationMocker = true)
{
$this->__phpunit_getInvocationMocker()->verify();
if ($unsetInvocationMocker) {
$this->__phpunit_invocationMocker = null;
}
}
}

Some files were not shown because too many files have changed in this diff Show More