Implements: PHPUnit\Framework\SelfDescribing | PHPUnit\Framework\Test | Countable
Transparent extension for Kohana_Unittest_Database_TestCase
Provides some unittest helpers and allows a kohana database connection to be used to connect to the database
Class declared in MODPATH/unittest/classes/Unittest/Database/TestCase.php on line 14.
string $_database_connectionThe kohana database connection that PHPUnit should use for this test
string(7) "default"Kohana_Unittest_Helpers $_helpersA set of unittest helpers that are shared between normal / database testcases
NULL
bool $backupGlobalsMake sure PHPUnit backs up globals
bool FALSE
array $backupGlobalsBlacklistarray(0) bool $backupStaticAttributesNULL
array $backupStaticAttributesBlacklistarray(0) array $environmentDefaultA default set of environment to be applied before each test
array(0) bool $preserveGlobalStatebool TRUE
bool $runTestInSeparateProcessNULL
Removes all kohana related cache files in the cache directory
voidpublic function cleanCacheDir()
{
Kohana_Unittest_Helpers::clean_cache_dir();
}
Helper function that replaces all occurrences of '/' with the OS-specific directory separator
string
$path
required - The path to act on stringpublic function dirSeparator(string $path): string
{
return Kohana_Unittest_Helpers::dir_separator($path);
}
Creates a connection to the unittesting database
PDOpublic function getConnection(): PDO
{
// Get the unittesting db connection
$config = Kohana::$config->load('database.' . $this->_database_connection);
if (strtolower($config['type']) !== 'pdo') {
$config['connection']['dsn'] = strtolower($config['type']) . ':' .
'host=' . $config['connection']['hostname'] . ';' .
'dbname=' . $config['connection']['database'];
}
$pdo = new PDO(
$config['connection']['dsn'],
$config['connection']['username'],
$config['connection']['password']
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
Gets a connection to the unittest database
Kohana_Database - The database connectionpublic function getKohanaConnection(): Kohana_Database
{
return Database::instance(Kohana::$config->load('unittest')->db_connection);
}
Check for internet connectivity
bool - Whether an internet connection is availablepublic function hasInternet(): bool
{
return Kohana_Unittest_Helpers::has_internet();
}
Allows easy setting & backing up of environment config
Option types are checked in the following order:
array
$environment
required - List of environment to set false|nullpublic function setEnvironment(array $environment): ?bool
{
return $this->_helpers->set_environment($environment);
}
Creates a predefined environment using the default environment
Extending classes that have their own setUp() should call parent::setUp()
voidpublic function setUp()
{
$this->_helpers = new Kohana_Unittest_Helpers;
$this->setEnvironment($this->environmentDefault);
parent::setUp();
}
Restores the original environment overridden with setEnvironment()
Extending classes that have their own tearDown() should call parent::tearDown()
voidpublic function tearDown()
{
$this->_helpers->restore_environment();
parent::tearDown();
}
string
$name
= NULL - $name string
$data
= array(0) - Name unknown
$dataName
= string(0) "" public function __construct($name = null, array $data = [], $dataName = '')
{
if ($name !== null) {
$this->setName($name);
}
$this->data = $data;
$this->dataName = $dataName;
}
public function addToAssertionCount(int $count): void
{
$this->numAssertions += $count;
}
public function addWarning(string $warning): void
{
$this->warnings[] = $warning;
}
Returns a matcher that matches when the method is executed zero or more times.
public static function any(): AnyInvokedCountMatcher
{
return new AnyInvokedCountMatcher;
}
Returns a matcher that matches when the method is executed at the given index.
public static function at(int $index): InvokedAtIndexMatcher
{
return new InvokedAtIndexMatcher($index);
}
Returns a matcher that matches when the method is executed at least N times.
public static function atLeast(int $requiredInvocations): InvokedAtLeastCountMatcher
{
return new InvokedAtLeastCountMatcher(
$requiredInvocations
);
}
Returns a matcher that matches when the method is executed at least once.
public static function atLeastOnce(): InvokedAtLeastOnceMatcher
{
return new InvokedAtLeastOnceMatcher;
}
Returns a matcher that matches when the method is executed at most N times.
public static function atMost(int $allowedInvocations): InvokedAtMostCountMatcher
{
return new InvokedAtMostCountMatcher($allowedInvocations);
}
public function count(): int
{
return 1;
}
public function dataDescription(): string
{
return \is_string($this->dataName) ? $this->dataName : '';
}
int|stringpublic function dataName()
{
return $this->dataName;
}
public function doesNotPerformAssertions(): bool
{
return $this->doesNotPerformAssertions;
}
Returns a matcher that matches when the method is executed exactly $count times.
public static function exactly(int $count): InvokedCountMatcher
{
return new InvokedCountMatcher($count);
}
public function expectException(string $exception): void
{
$this->expectedException = $exception;
}
int|string
$code
required - $code public function expectExceptionCode($code): void
{
$this->expectedExceptionCode = $code;
}
public function expectExceptionMessage(string $message): void
{
$this->expectedExceptionMessage = $message;
}
public function expectExceptionMessageRegExp(string $messageRegExp): void
{
$this->expectedExceptionMessageRegExp = $messageRegExp;
}
Sets up an expectation for an exception to be raised by the code under test. Information for expected exception class, expected exception message, and expected exception code are retrieved from a given Exception object.
public function expectExceptionObject(\Exception $exception): void
{
$this->expectException(\get_class($exception));
$this->expectExceptionMessage($exception->getMessage());
$this->expectExceptionCode($exception->getCode());
}
public function expectNotToPerformAssertions()
{
$this->doesNotPerformAssertions = true;
}
public function expectOutputRegex(string $expectedRegex): void
{
$this->outputExpectedRegex = $expectedRegex;
}
public function expectOutputString(string $expectedString): void
{
$this->outputExpectedString = $expectedString;
}
public function getActualOutput(): string
{
if (!$this->outputBufferingActive) {
return $this->output;
}
return \ob_get_contents();
}
public function getAnnotations(): array
{
return \PHPUnit\Util\Test::parseTestMethodAnnotations(
\get_class($this),
$this->name
);
}
public function getDataSetAsString(bool $includeData = true): string
{
$buffer = '';
if (!empty($this->data)) {
if (\is_int($this->dataName)) {
$buffer .= \sprintf(' with data set #%d', $this->dataName);
} else {
$buffer .= \sprintf(' with data set "%s"', $this->dataName);
}
$exporter = new Exporter;
if ($includeData) {
$buffer .= \sprintf(' (%s)', $exporter->shortenedRecursiveExport($this->data));
}
}
return $buffer;
}
public function getDependencies(): array
{
return $this->dependencies;
}
public function getExpectedException(): ?string
{
return $this->expectedException;
}
null|int|stringpublic function getExpectedExceptionCode()
{
return $this->expectedExceptionCode;
}
public function getExpectedExceptionMessage(): ?string
{
return $this->expectedExceptionMessage;
}
public function getExpectedExceptionMessageRegExp(): ?string
{
return $this->expectedExceptionMessageRegExp;
}
public function getGroups(): array
{
return $this->groups;
}
Returns a builder object to create mock objects using a fluent interface.
string|string[]
$className
required - $className public function getMockBuilder($className): MockBuilder
{
return new MockBuilder($this, $className);
}
public function getName(bool $withDataSet = true): ?string
{
if ($withDataSet) {
return $this->name . $this->getDataSetAsString(false);
}
return $this->name;
}
Returns the number of assertions performed by this test.
public function getNumAssertions(): int
{
return $this->numAssertions;
}
Gets the data set of a TestCase.
public function getProvidedData(): array
{
return $this->data;
}
public function getResult()
{
return $this->testResult;
}
Returns the size of the test.
public function getSize(): int
{
return \PHPUnit\Util\Test::getSize(
\get_class($this),
$this->getName(false)
);
}
public function getStatus(): int
{
return $this->status;
}
public function getStatusMessage(): string
{
return $this->statusMessage;
}
public function getTestResultObject(): ?TestResult
{
return $this->result;
}
public function hasDependencies(): bool
{
return \count($this->dependencies) > 0;
}
public function hasExpectationOnOutput(): bool
{
return \is_string($this->outputExpectedString) || \is_string($this->outputExpectedRegex);
}
public function hasFailed(): bool
{
$status = $this->getStatus();
return $status === BaseTestRunner::STATUS_FAILURE || $status === BaseTestRunner::STATUS_ERROR;
}
public function hasOutput(): bool
{
if ($this->output === '') {
return false;
}
if ($this->hasExpectationOnOutput()) {
return false;
}
return true;
}
public function hasSize(): bool
{
return $this->getSize() !== \PHPUnit\Util\Test::UNKNOWN;
}
public function isInIsolation(): bool
{
return $this->inIsolation;
}
public function isLarge(): bool
{
return $this->getSize() === \PHPUnit\Util\Test::LARGE;
}
public function isMedium(): bool
{
return $this->getSize() === \PHPUnit\Util\Test::MEDIUM;
}
public function isSmall(): bool
{
return $this->getSize() === \PHPUnit\Util\Test::SMALL;
}
public function markAsRisky(): void
{
$this->status = BaseTestRunner::STATUS_RISKY;
}
Returns a matcher that matches when the method is never executed.
public static function never(): InvokedCountMatcher
{
return new InvokedCountMatcher(0);
}
public static function onConsecutiveCalls(...$args): ConsecutiveCallsStub
{
return new ConsecutiveCallsStub($args);
}
Returns a matcher that matches when the method is executed exactly once.
public static function once(): InvokedCountMatcher
{
return new InvokedCountMatcher(1);
}
public function registerComparator(Comparator $comparator): void
{
ComparatorFactory::getInstance()->register($comparator);
$this->customComparators[] = $comparator;
}
public function registerMockObject(MockObject $mockObject): void
{
$this->mockObjects[] = $mockObject;
}
public static function returnArgument(int $argumentIndex): ReturnArgumentStub
{
return new ReturnArgumentStub($argumentIndex);
}
public static function returnCallback($callback): ReturnCallbackStub
{
return new ReturnCallbackStub($callback);
}
Returns the current object.
This method is useful when mocking a fluent interface.
public static function returnSelf(): ReturnSelfStub
{
return new ReturnSelfStub;
}
public static function returnValue($value): ReturnStub
{
return new ReturnStub($value);
}
public static function returnValueMap(array $valueMap): ReturnValueMapStub
{
return new ReturnValueMapStub($valueMap);
}
Runs the test case and collects the results in a TestResult object. If no TestResult object is passed a new one will be created.
public function run(TestResult $result = null): TestResult
{
if ($result === null) {
$result = $this->createResult();
}
if (!$this instanceof WarningTestCase) {
$this->setTestResultObject($result);
$this->setUseErrorHandlerFromAnnotation();
}
if ($this->useErrorHandler !== null) {
$oldErrorHandlerSetting = $result->getConvertErrorsToExceptions();
$result->convertErrorsToExceptions($this->useErrorHandler);
}
if (!$this instanceof WarningTestCase &&
!$this instanceof SkippedTestCase &&
!$this->handleDependencies()) {
return $result;
}
if ($this->runInSeparateProcess()) {
$runEntireClass = $this->runClassInSeparateProcess && !$this->runTestInSeparateProcess;
$class = new ReflectionClass($this);
if ($runEntireClass) {
$template = new Text_Template(
__DIR__ . '/../Util/PHP/Template/TestCaseClass.tpl'
);
} else {
$template = new Text_Template(
__DIR__ . '/../Util/PHP/Template/TestCaseMethod.tpl'
);
}
if ($this->preserveGlobalState) {
$constants = GlobalState::getConstantsAsString();
$globals = GlobalState::getGlobalsAsString();
$includedFiles = GlobalState::getIncludedFilesAsString();
$iniSettings = GlobalState::getIniSettingsAsString();
} else {
$constants = '';
if (!empty($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
$globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . \var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], true) . ";\n";
} else {
$globals = '';
}
$includedFiles = '';
$iniSettings = '';
}
$coverage = $result->getCollectCodeCoverageInformation() ? 'true' : 'false';
$isStrictAboutTestsThatDoNotTestAnything = $result->isStrictAboutTestsThatDoNotTestAnything() ? 'true' : 'false';
$isStrictAboutOutputDuringTests = $result->isStrictAboutOutputDuringTests() ? 'true' : 'false';
$enforcesTimeLimit = $result->enforcesTimeLimit() ? 'true' : 'false';
$isStrictAboutTodoAnnotatedTests = $result->isStrictAboutTodoAnnotatedTests() ? 'true' : 'false';
$isStrictAboutResourceUsageDuringSmallTests = $result->isStrictAboutResourceUsageDuringSmallTests() ? 'true' : 'false';
if (\defined('PHPUNIT_COMPOSER_INSTALL')) {
$composerAutoload = \var_export(PHPUNIT_COMPOSER_INSTALL, true);
} else {
$composerAutoload = '\'\'';
}
if (\defined('__PHPUNIT_PHAR__')) {
$phar = \var_export(__PHPUNIT_PHAR__, true);
} else {
$phar = '\'\'';
}
if ($result->getCodeCoverage()) {
$codeCoverageFilter = $result->getCodeCoverage()->filter();
} else {
$codeCoverageFilter = null;
}
$data = \var_export(\serialize($this->data), true);
$dataName = \var_export($this->dataName, true);
$dependencyInput = \var_export(\serialize($this->dependencyInput), true);
$includePath = \var_export(\get_include_path(), true);
$codeCoverageFilter = \var_export(\serialize($codeCoverageFilter), true);
// must do these fixes because TestCaseMethod.tpl has unserialize('{data}') in it, and we can't break BC
// the lines above used to use addcslashes() rather than var_export(), which breaks null byte escape sequences
$data = "'." . $data . ".'";
$dataName = "'.(" . $dataName . ").'";
$dependencyInput = "'." . $dependencyInput . ".'";
$includePath = "'." . $includePath . ".'";
$codeCoverageFilter = "'." . $codeCoverageFilter . ".'";
$configurationFilePath = $GLOBALS['__PHPUNIT_CONFIGURATION_FILE'] ?? '';
$var = [
'composerAutoload' => $composerAutoload,
'phar' => $phar,
'filename' => $class->getFileName(),
'className' => $class->getName(),
'collectCodeCoverageInformation' => $coverage,
'data' => $data,
'dataName' => $dataName,
'dependencyInput' => $dependencyInput,
'constants' => $constants,
'globals' => $globals,
'include_path' => $includePath,
'included_files' => $includedFiles,
'iniSettings' => $iniSettings,
'isStrictAboutTestsThatDoNotTestAnything' => $isStrictAboutTestsThatDoNotTestAnything,
'isStrictAboutOutputDuringTests' => $isStrictAboutOutputDuringTests,
'enforcesTimeLimit' => $enforcesTimeLimit,
'isStrictAboutTodoAnnotatedTests' => $isStrictAboutTodoAnnotatedTests,
'isStrictAboutResourceUsageDuringSmallTests' => $isStrictAboutResourceUsageDuringSmallTests,
'codeCoverageFilter' => $codeCoverageFilter,
'configurationFilePath' => $configurationFilePath,
'name' => $this->getName(false),
];
if (!$runEntireClass) {
$var['methodName'] = $this->name;
}
$template->setVar(
$var
);
$php = AbstractPhpProcess::factory();
$php->runTestJob($template->render(), $this, $result);
} else {
$result->run($this);
}
if (isset($oldErrorHandlerSetting)) {
$result->convertErrorsToExceptions($oldErrorHandlerSetting);
}
$this->result = null;
return $result;
}
public function runBare(): void
{
$this->numAssertions = 0;
$this->snapshotGlobalState();
$this->startOutputBuffering();
\clearstatcache();
$currentWorkingDirectory = \getcwd();
$hookMethods = \PHPUnit\Util\Test::getHookMethods(\get_class($this));
$hasMetRequirements = false;
try {
$this->checkRequirements();
$hasMetRequirements = true;
if ($this->inIsolation) {
foreach ($hookMethods['beforeClass'] as $method) {
$this->$method();
}
}
$this->setExpectedExceptionFromAnnotation();
$this->setDoesNotPerformAssertionsFromAnnotation();
foreach ($hookMethods['before'] as $method) {
$this->$method();
}
$this->assertPreConditions();
$this->testResult = $this->runTest();
$this->verifyMockObjects();
$this->assertPostConditions();
if (!empty($this->warnings)) {
throw new Warning(
\implode(
"\n",
\array_unique($this->warnings)
)
);
}
$this->status = BaseTestRunner::STATUS_PASSED;
} catch (IncompleteTest $e) {
$this->status = BaseTestRunner::STATUS_INCOMPLETE;
$this->statusMessage = $e->getMessage();
} catch (SkippedTest $e) {
$this->status = BaseTestRunner::STATUS_SKIPPED;
$this->statusMessage = $e->getMessage();
} catch (Warning $e) {
$this->status = BaseTestRunner::STATUS_WARNING;
$this->statusMessage = $e->getMessage();
} catch (AssertionFailedError $e) {
$this->status = BaseTestRunner::STATUS_FAILURE;
$this->statusMessage = $e->getMessage();
} catch (PredictionException $e) {
$this->status = BaseTestRunner::STATUS_FAILURE;
$this->statusMessage = $e->getMessage();
} catch (Throwable $_e) {
$e = $_e;
$this->status = BaseTestRunner::STATUS_ERROR;
$this->statusMessage = $_e->getMessage();
}
$this->mockObjects = [];
$this->prophet = null;
// Tear down the fixture. An exception raised in tearDown() will be
// caught and passed on when no exception was raised before.
try {
if ($hasMetRequirements) {
foreach ($hookMethods['after'] as $method) {
$this->$method();
}
if ($this->inIsolation) {
foreach ($hookMethods['afterClass'] as $method) {
$this->$method();
}
}
}
} catch (Throwable $_e) {
$e = $e ?? $_e;
}
try {
$this->stopOutputBuffering();
} catch (RiskyTestError $_e) {
$e = $e ?? $_e;
}
if (isset($_e)) {
$this->status = BaseTestRunner::STATUS_ERROR;
$this->statusMessage = $_e->getMessage();
}
\clearstatcache();
if ($currentWorkingDirectory != \getcwd()) {
\chdir($currentWorkingDirectory);
}
$this->restoreGlobalState();
$this->unregisterCustomComparators();
$this->cleanupIniSettings();
$this->cleanupLocaleSettings();
\libxml_clear_errors();
// Perform assertion on output.
if (!isset($e)) {
try {
if ($this->outputExpectedRegex !== null) {
$this->assertRegExp($this->outputExpectedRegex, $this->output);
} elseif ($this->outputExpectedString !== null) {
$this->assertEquals($this->outputExpectedString, $this->output);
}
} catch (Throwable $_e) {
$e = $_e;
}
}
// Workaround for missing "finally".
if (isset($e)) {
if ($e instanceof PredictionException) {
$e = new AssertionFailedError($e->getMessage());
}
$this->onNotSuccessfulTest($e);
}
}
public function setBackupGlobals(?bool $backupGlobals): void
{
if ($this->backupGlobals === null && $backupGlobals !== null) {
$this->backupGlobals = $backupGlobals;
}
}
public function setBackupStaticAttributes(?bool $backupStaticAttributes): void
{
if ($this->backupStaticAttributes === null && $backupStaticAttributes !== null) {
$this->backupStaticAttributes = $backupStaticAttributes;
}
}
public function setBeStrictAboutChangesToGlobalState(?bool $beStrictAboutChangesToGlobalState): void
{
$this->beStrictAboutChangesToGlobalState = $beStrictAboutChangesToGlobalState;
}
string[]
$dependencies
required - $dependencies public function setDependencies(array $dependencies): void
{
$this->dependencies = $dependencies;
}
public function setDependencyInput(array $dependencyInput): void
{
$this->dependencyInput = $dependencyInput;
}
public function setGroups(array $groups): void
{
$this->groups = $groups;
}
public function setInIsolation(bool $inIsolation): void
{
$this->inIsolation = $inIsolation;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function setOutputCallback(callable $callback): void
{
$this->outputCallback = $callback;
}
public function setPreserveGlobalState(bool $preserveGlobalState): void
{
$this->preserveGlobalState = $preserveGlobalState;
}
public function setRegisterMockObjectsFromTestArgumentsRecursively(bool $flag): void
{
$this->registerMockObjectsFromTestArgumentsRecursively = $flag;
}
public function setResult($result): void
{
$this->testResult = $result;
}
public function setRunClassInSeparateProcess(bool $runClassInSeparateProcess): void
{
if ($this->runClassInSeparateProcess === null) {
$this->runClassInSeparateProcess = $runClassInSeparateProcess;
}
}
public function setRunTestInSeparateProcess(bool $runTestInSeparateProcess): void
{
if ($this->runTestInSeparateProcess === null) {
$this->runTestInSeparateProcess = $runTestInSeparateProcess;
}
}
public function setTestResultObject(TestResult $result): void
{
$this->result = $result;
}
This method is called before the first test of this test class is run.
public static function setUpBeforeClass()/* The :void return type declaration that should be here would cause a BC issue */
{
}
public function setUseErrorHandler(bool $useErrorHandler): void
{
$this->useErrorHandler = $useErrorHandler;
}
This method is called after the last test of this test class is run.
public static function tearDownAfterClass()/* The :void return type declaration that should be here would cause a BC issue */
{
}
public static function throwException(Throwable $exception): ExceptionStub
{
return new ExceptionStub($exception);
}
Returns a string representation of the test case.
public function toString(): string
{
$class = new ReflectionClass($this);
$buffer = \sprintf(
'%s::%s',
$class->name,
$this->getName(false)
);
return $buffer . $this->getDataSetAsString();
}
public function usesDataProvider(): bool
{
return !empty($this->data);
}
public static function anything(): IsAnything
{
return new IsAnything;
}
int|string
$key
required - $key public static function arrayHasKey($key): ArrayHasKey
{
return new ArrayHasKey($key);
}
Asserts that an array has a specified key.
int|string
$key
required - $key array|ArrayAccess
$array
required -
unknown
$message
= string(0) "" public static function assertArrayHasKey($key, $array, string $message = ''): void
{
if (!(\is_int($key) || \is_string($key))) {
throw InvalidArgumentHelper::factory(
1,
'integer or string'
);
}
if (!(\is_array($array) || $array instanceof ArrayAccess)) {
throw InvalidArgumentHelper::factory(
2,
'array or ArrayAccess'
);
}
$constraint = new ArrayHasKey($key);
static::assertThat($array, $constraint, $message);
}
Asserts that an array does not have a specified key.
int|string
$key
required - $key array|ArrayAccess
$array
required -
unknown
$message
= string(0) "" public static function assertArrayNotHasKey($key, $array, string $message = ''): void
{
if (!(\is_int($key) || \is_string($key))) {
throw InvalidArgumentHelper::factory(
1,
'integer or string'
);
}
if (!(\is_array($array) || $array instanceof ArrayAccess)) {
throw InvalidArgumentHelper::factory(
2,
'array or ArrayAccess'
);
}
$constraint = new LogicalNot(
new ArrayHasKey($key)
);
static::assertThat($array, $constraint, $message);
}
Asserts that an array has a specified subset.
array|ArrayAccess
$subset
required - $subset array|ArrayAccess
$array
required -
unknown
$checkForObjectIdentity
= bool FALSE unknown
$message
= string(0) "" public static function assertArraySubset($subset, $array, bool $checkForObjectIdentity = false, string $message = ''): void
{
if (!(\is_array($subset) || $subset instanceof ArrayAccess)) {
throw InvalidArgumentHelper::factory(
1,
'array or ArrayAccess'
);
}
if (!(\is_array($array) || $array instanceof ArrayAccess)) {
throw InvalidArgumentHelper::factory(
2,
'array or ArrayAccess'
);
}
$constraint = new ArraySubset($subset, $checkForObjectIdentity);
static::assertThat($array, $constraint, $message);
}
Asserts that a haystack that is stored in a static attribute of a class or an attribute of an object contains a needle.
object|string
$needle
required - $haystackClassOrObject
unknown
$haystackAttributeName
required unknown
$haystackClassOrObject
required unknown
$message
= string(0) "" unknown
$ignoreCase
= bool FALSE unknown
$checkForObjectIdentity
= bool TRUE unknown
$checkForNonObjectIdentity
= bool FALSE public static function assertAttributeContains($needle, string $haystackAttributeName, $haystackClassOrObject, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
{
static::assertContains(
$needle,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message,
$ignoreCase,
$checkForObjectIdentity,
$checkForNonObjectIdentity
);
}
Asserts that a haystack that is stored in a static attribute of a class or an attribute of an object contains only values of a given type.
object|string
$type
required - $haystackClassOrObject bool
$haystackAttributeName
required - $isNativeType
unknown
$haystackClassOrObject
required unknown
$isNativeType
= NULL unknown
$message
= string(0) "" public static function assertAttributeContainsOnly(string $type, string $haystackAttributeName, $haystackClassOrObject, ?bool $isNativeType = null, string $message = ''): void
{
static::assertContainsOnly(
$type,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$isNativeType,
$message
);
}
Asserts the number of elements of an array, Countable or Traversable that is stored in an attribute.
object|string
$expectedCount
required - $haystackClassOrObject
unknown
$haystackAttributeName
required unknown
$haystackClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeCount(int $expectedCount, string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
{
static::assertCount(
$expectedCount,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message
);
}
Asserts that a static attribute of a class or an attribute of an object is empty.
object|string
$haystackAttributeName
required - $haystackClassOrObject
unknown
$haystackClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeEmpty(string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
{
static::assertEmpty(
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message
);
}
Asserts that a variable is equal to an attribute of an object.
object|string
$expected
required - $actualClassOrObject
unknown
$actualAttributeName
required unknown
$actualClassOrObject
required unknown
$message
= string(0) "" unknown
$delta
= float 0 unknown
$maxDepth
= integer 10 unknown
$canonicalize
= bool FALSE unknown
$ignoreCase
= bool FALSE public static function assertAttributeEquals($expected, string $actualAttributeName, $actualClassOrObject, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
{
static::assertEquals(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
);
}
Asserts that an attribute is greater than another value.
object|string
$expected
required - $actualClassOrObject
unknown
$actualAttributeName
required unknown
$actualClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeGreaterThan($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
{
static::assertGreaterThan(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
Asserts that an attribute is greater than or equal to another value.
object|string
$expected
required - $actualClassOrObject
unknown
$actualAttributeName
required unknown
$actualClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeGreaterThanOrEqual($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
{
static::assertGreaterThanOrEqual(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
Asserts that an attribute is of a given type.
object|string
$expected
required - $classOrObject
unknown
$attributeName
required unknown
$classOrObject
required unknown
$message
= string(0) "" public static function assertAttributeInstanceOf(string $expected, string $attributeName, $classOrObject, string $message = ''): void
{
static::assertInstanceOf(
$expected,
static::readAttribute($classOrObject, $attributeName),
$message
);
}
Asserts that an attribute is of a given type.
object|string
$expected
required - $classOrObject
unknown
$attributeName
required unknown
$classOrObject
required unknown
$message
= string(0) "" public static function assertAttributeInternalType(string $expected, string $attributeName, $classOrObject, string $message = ''): void
{
static::assertInternalType(
$expected,
static::readAttribute($classOrObject, $attributeName),
$message
);
}
Asserts that an attribute is smaller than another value.
object|string
$expected
required - $actualClassOrObject
unknown
$actualAttributeName
required unknown
$actualClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeLessThan($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
{
static::assertLessThan(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
Asserts that an attribute is smaller than or equal to another value.
object|string
$expected
required - $actualClassOrObject
unknown
$actualAttributeName
required unknown
$actualClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeLessThanOrEqual($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
{
static::assertLessThanOrEqual(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
Asserts that a haystack that is stored in a static attribute of a class or an attribute of an object does not contain a needle.
object|string
$needle
required - $haystackClassOrObject
unknown
$haystackAttributeName
required unknown
$haystackClassOrObject
required unknown
$message
= string(0) "" unknown
$ignoreCase
= bool FALSE unknown
$checkForObjectIdentity
= bool TRUE unknown
$checkForNonObjectIdentity
= bool FALSE public static function assertAttributeNotContains($needle, string $haystackAttributeName, $haystackClassOrObject, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
{
static::assertNotContains(
$needle,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message,
$ignoreCase,
$checkForObjectIdentity,
$checkForNonObjectIdentity
);
}
Asserts that a haystack that is stored in a static attribute of a class or an attribute of an object does not contain only values of a given type.
object|string
$type
required - $haystackClassOrObject bool
$haystackAttributeName
required - $isNativeType
unknown
$haystackClassOrObject
required unknown
$isNativeType
= NULL unknown
$message
= string(0) "" public static function assertAttributeNotContainsOnly(string $type, string $haystackAttributeName, $haystackClassOrObject, ?bool $isNativeType = null, string $message = ''): void
{
static::assertNotContainsOnly(
$type,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$isNativeType,
$message
);
}
Asserts the number of elements of an array, Countable or Traversable that is stored in an attribute.
object|string
$expectedCount
required - $haystackClassOrObject
unknown
$haystackAttributeName
required unknown
$haystackClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeNotCount(int $expectedCount, string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
{
static::assertNotCount(
$expectedCount,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message
);
}
Asserts that a static attribute of a class or an attribute of an object is not empty.
object|string
$haystackAttributeName
required - $haystackClassOrObject
unknown
$haystackClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeNotEmpty(string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
{
static::assertNotEmpty(
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message
);
}
Asserts that a variable is not equal to an attribute of an object.
object|string
$expected
required - $actualClassOrObject
unknown
$actualAttributeName
required unknown
$actualClassOrObject
required unknown
$message
= string(0) "" unknown
$delta
= float 0 unknown
$maxDepth
= integer 10 unknown
$canonicalize
= bool FALSE unknown
$ignoreCase
= bool FALSE public static function assertAttributeNotEquals($expected, string $actualAttributeName, $actualClassOrObject, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
{
static::assertNotEquals(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
);
}
Asserts that an attribute is of a given type.
object|string
$expected
required - $classOrObject
unknown
$attributeName
required unknown
$classOrObject
required unknown
$message
= string(0) "" public static function assertAttributeNotInstanceOf(string $expected, string $attributeName, $classOrObject, string $message = ''): void
{
static::assertNotInstanceOf(
$expected,
static::readAttribute($classOrObject, $attributeName),
$message
);
}
Asserts that an attribute is of a given type.
object|string
$expected
required - $classOrObject
unknown
$attributeName
required unknown
$classOrObject
required unknown
$message
= string(0) "" public static function assertAttributeNotInternalType(string $expected, string $attributeName, $classOrObject, string $message = ''): void
{
static::assertNotInternalType(
$expected,
static::readAttribute($classOrObject, $attributeName),
$message
);
}
Asserts that a variable and an attribute of an object do not have the same type and value.
object|string
$expected
required - $actualClassOrObject
unknown
$actualAttributeName
required unknown
$actualClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeNotSame($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
{
static::assertNotSame(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
Asserts that a variable and an attribute of an object have the same type and value.
object|string
$expected
required - $actualClassOrObject
unknown
$actualAttributeName
required unknown
$actualClassOrObject
required unknown
$message
= string(0) "" public static function assertAttributeSame($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
{
static::assertSame(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
Asserts that a class has a specified attribute.
public static function assertClassHasAttribute(string $attributeName, string $className, string $message = ''): void
{
if (!self::isValidClassAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!\class_exists($className)) {
throw InvalidArgumentHelper::factory(2, 'class name', $className);
}
static::assertThat($className, new ClassHasAttribute($attributeName), $message);
}
Asserts that a class has a specified static attribute.
public static function assertClassHasStaticAttribute(string $attributeName, string $className, string $message = ''): void
{
if (!self::isValidClassAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!\class_exists($className)) {
throw InvalidArgumentHelper::factory(2, 'class name', $className);
}
static::assertThat(
$className,
new ClassHasStaticAttribute($attributeName),
$message
);
}
Asserts that a class does not have a specified attribute.
public static function assertClassNotHasAttribute(string $attributeName, string $className, string $message = ''): void
{
if (!self::isValidClassAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!\class_exists($className)) {
throw InvalidArgumentHelper::factory(2, 'class name', $className);
}
static::assertThat(
$className,
new LogicalNot(
new ClassHasAttribute($attributeName)
),
$message
);
}
Asserts that a class does not have a specified static attribute.
public static function assertClassNotHasStaticAttribute(string $attributeName, string $className, string $message = ''): void
{
if (!self::isValidClassAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!\class_exists($className)) {
throw InvalidArgumentHelper::factory(2, 'class name', $className);
}
static::assertThat(
$className,
new LogicalNot(
new ClassHasStaticAttribute($attributeName)
),
$message
);
}
Asserts that a haystack contains a needle.
public static function assertContains($needle, $haystack, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
{
if (\is_array($haystack) ||
(\is_object($haystack) && $haystack instanceof Traversable)) {
$constraint = new TraversableContains(
$needle,
$checkForObjectIdentity,
$checkForNonObjectIdentity
);
} elseif (\is_string($haystack)) {
if (!\is_string($needle)) {
throw InvalidArgumentHelper::factory(
1,
'string'
);
}
$constraint = new StringContains(
$needle,
$ignoreCase
);
} else {
throw InvalidArgumentHelper::factory(
2,
'array, traversable or string'
);
}
static::assertThat($haystack, $constraint, $message);
}
Asserts that a haystack contains only values of a given type.
public static function assertContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void
{
if ($isNativeType === null) {
$isNativeType = Type::isType($type);
}
static::assertThat(
$haystack,
new TraversableContainsOnly(
$type,
$isNativeType
),
$message
);
}
Asserts that a haystack contains only instances of a given class name.
public static function assertContainsOnlyInstancesOf(string $className, iterable $haystack, string $message = ''): void
{
static::assertThat(
$haystack,
new TraversableContainsOnly(
$className,
false
),
$message
);
}
Asserts the number of elements of an array, Countable or Traversable.
Countable|iterable
$expectedCount
required - $haystack
unknown
$haystack
required unknown
$message
= string(0) "" public static function assertCount(int $expectedCount, $haystack, string $message = ''): void
{
if (!$haystack instanceof Countable && !\is_iterable($haystack)) {
throw InvalidArgumentHelper::factory(2, 'countable or iterable');
}
static::assertThat(
$haystack,
new Count($expectedCount),
$message
);
}
Asserts that a directory exists.
public static function assertDirectoryExists(string $directory, string $message = ''): void
{
static::assertThat($directory, new DirectoryExists, $message);
}
Asserts that a directory exists and is readable.
public static function assertDirectoryIsReadable(string $directory, string $message = ''): void
{
self::assertDirectoryExists($directory, $message);
self::assertIsReadable($directory, $message);
}
Asserts that a directory exists and is writable.
public static function assertDirectoryIsWritable(string $directory, string $message = ''): void
{
self::assertDirectoryExists($directory, $message);
self::assertIsWritable($directory, $message);
}
Asserts that a directory does not exist.
public static function assertDirectoryNotExists(string $directory, string $message = ''): void
{
static::assertThat($directory, new LogicalNot(new DirectoryExists), $message);
}
Asserts that a directory exists and is not readable.
public static function assertDirectoryNotIsReadable(string $directory, string $message = ''): void
{
self::assertDirectoryExists($directory, $message);
self::assertNotIsReadable($directory, $message);
}
Asserts that a directory exists and is not writable.
public static function assertDirectoryNotIsWritable(string $directory, string $message = ''): void
{
self::assertDirectoryExists($directory, $message);
self::assertNotIsWritable($directory, $message);
}
Asserts that a variable is empty.
public static function assertEmpty($actual, string $message = ''): void
{
static::assertThat($actual, static::isEmpty(), $message);
}
Asserts that a hierarchy of DOMElements matches.
public static function assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement, bool $checkAttributes = false, string $message = ''): void
{
$expectedElement = Xml::import($expectedElement);
$actualElement = Xml::import($actualElement);
static::assertSame(
$expectedElement->tagName,
$actualElement->tagName,
$message
);
if ($checkAttributes) {
static::assertSame(
$expectedElement->attributes->length,
$actualElement->attributes->length,
\sprintf(
'%s%sNumber of attributes on node "%s" does not match',
$message,
!empty($message) ? "\n" : '',
$expectedElement->tagName
)
);
for ($i = 0; $i < $expectedElement->attributes->length; $i++) {
/** @var \DOMAttr $expectedAttribute */
$expectedAttribute = $expectedElement->attributes->item($i);
/** @var \DOMAttr $actualAttribute */
$actualAttribute = $actualElement->attributes->getNamedItem(
$expectedAttribute->name
);
if (!$actualAttribute) {
static::fail(
\sprintf(
'%s%sCould not find attribute "%s" on node "%s"',
$message,
!empty($message) ? "\n" : '',
$expectedAttribute->name,
$expectedElement->tagName
)
);
}
}
}
Xml::removeCharacterDataNodes($expectedElement);
Xml::removeCharacterDataNodes($actualElement);
static::assertSame(
$expectedElement->childNodes->length,
$actualElement->childNodes->length,
\sprintf(
'%s%sNumber of child nodes of "%s" differs',
$message,
!empty($message) ? "\n" : '',
$expectedElement->tagName
)
);
for ($i = 0; $i < $expectedElement->childNodes->length; $i++) {
static::assertEqualXMLStructure(
$expectedElement->childNodes->item($i),
$actualElement->childNodes->item($i),
$checkAttributes,
$message
);
}
}
Asserts that two variables are equal.
public static function assertEquals($expected, $actual, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
{
$constraint = new IsEqual(
$expected,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
);
static::assertThat($actual, $constraint, $message);
}
Asserts that two variables are equal (canonicalizing).
public static function assertEqualsCanonicalizing($expected, $actual, string $message = ''): void
{
$constraint = new IsEqual(
$expected,
0.0,
10,
true,
false
);
static::assertThat($actual, $constraint, $message);
}
Asserts that two variables are equal (ignoring case).
public static function assertEqualsIgnoringCase($expected, $actual, string $message = ''): void
{
$constraint = new IsEqual(
$expected,
0.0,
10,
false,
true
);
static::assertThat($actual, $constraint, $message);
}
Asserts that two variables are equal (with delta).
public static function assertEqualsWithDelta($expected, $actual, float $delta, string $message = ''): void
{
$constraint = new IsEqual(
$expected,
$delta
);
static::assertThat($actual, $constraint, $message);
}
Asserts that a condition is false.
public static function assertFalse($condition, string $message = ''): void
{
static::assertThat($condition, static::isFalse(), $message);
}
Asserts that the contents of one file is equal to the contents of another file.
public static function assertFileEquals(string $expected, string $actual, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
{
static::assertFileExists($expected, $message);
static::assertFileExists($actual, $message);
static::assertEquals(
\file_get_contents($expected),
\file_get_contents($actual),
$message,
0,
10,
$canonicalize,
$ignoreCase
);
}
Asserts that a file exists.
public static function assertFileExists(string $filename, string $message = ''): void
{
static::assertThat($filename, new FileExists, $message);
}
Asserts that a file exists and is readable.
public static function assertFileIsReadable(string $file, string $message = ''): void
{
self::assertFileExists($file, $message);
self::assertIsReadable($file, $message);
}
Asserts that a file exists and is writable.
public static function assertFileIsWritable(string $file, string $message = ''): void
{
self::assertFileExists($file, $message);
self::assertIsWritable($file, $message);
}
Asserts that the contents of one file is not equal to the contents of another file.
public static function assertFileNotEquals(string $expected, string $actual, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
{
static::assertFileExists($expected, $message);
static::assertFileExists($actual, $message);
static::assertNotEquals(
\file_get_contents($expected),
\file_get_contents($actual),
$message,
0,
10,
$canonicalize,
$ignoreCase
);
}
Asserts that a file does not exist.
public static function assertFileNotExists(string $filename, string $message = ''): void
{
static::assertThat($filename, new LogicalNot(new FileExists), $message);
}
Asserts that a file exists and is not readable.
public static function assertFileNotIsReadable(string $file, string $message = ''): void
{
self::assertFileExists($file, $message);
self::assertNotIsReadable($file, $message);
}
Asserts that a file exists and is not writable.
public static function assertFileNotIsWritable(string $file, string $message = ''): void
{
self::assertFileExists($file, $message);
self::assertNotIsWritable($file, $message);
}
Asserts that a variable is finite.
public static function assertFinite($actual, string $message = ''): void
{
static::assertThat($actual, static::isFinite(), $message);
}
Asserts that a value is greater than another value.
public static function assertGreaterThan($expected, $actual, string $message = ''): void
{
static::assertThat($actual, static::greaterThan($expected), $message);
}
Asserts that a value is greater than or equal to another value.
public static function assertGreaterThanOrEqual($expected, $actual, string $message = ''): void
{
static::assertThat(
$actual,
static::greaterThanOrEqual($expected),
$message
);
}
Asserts that a variable is infinite.
public static function assertInfinite($actual, string $message = ''): void
{
static::assertThat($actual, static::isInfinite(), $message);
}
Asserts that a variable is of a given type.
public static function assertInstanceOf(string $expected, $actual, string $message = ''): void
{
if (!\class_exists($expected) && !\interface_exists($expected)) {
throw InvalidArgumentHelper::factory(1, 'class or interface name');
}
static::assertThat(
$actual,
new IsInstanceOf($expected),
$message
);
}
Asserts that a variable is of a given type.
public static function assertInternalType(string $expected, $actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType($expected),
$message
);
}
Asserts that a variable is of type array.
public static function assertIsArray($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_ARRAY),
$message
);
}
Asserts that a variable is of type bool.
public static function assertIsBool($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_BOOL),
$message
);
}
Asserts that a variable is of type callable.
public static function assertIsCallable($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_CALLABLE),
$message
);
}
Asserts that a variable is of type float.
public static function assertIsFloat($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_FLOAT),
$message
);
}
Asserts that a variable is of type int.
public static function assertIsInt($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_INT),
$message
);
}
Asserts that a variable is of type iterable.
public static function assertIsIterable($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_ITERABLE),
$message
);
}
Asserts that a variable is not of type array.
public static function assertIsNotArray($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_ARRAY)),
$message
);
}
Asserts that a variable is not of type bool.
public static function assertIsNotBool($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_BOOL)),
$message
);
}
Asserts that a variable is not of type callable.
public static function assertIsNotCallable($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_CALLABLE)),
$message
);
}
Asserts that a variable is not of type float.
public static function assertIsNotFloat($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_FLOAT)),
$message
);
}
Asserts that a variable is not of type int.
public static function assertIsNotInt($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_INT)),
$message
);
}
Asserts that a variable is not of type iterable.
public static function assertIsNotIterable($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_ITERABLE)),
$message
);
}
Asserts that a variable is not of type numeric.
public static function assertIsNotNumeric($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_NUMERIC)),
$message
);
}
Asserts that a variable is not of type object.
public static function assertIsNotObject($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_OBJECT)),
$message
);
}
Asserts that a variable is not of type resource.
public static function assertIsNotResource($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_RESOURCE)),
$message
);
}
Asserts that a variable is not of type scalar.
public static function assertIsNotScalar($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_SCALAR)),
$message
);
}
Asserts that a variable is not of type string.
public static function assertIsNotString($actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(new IsType(IsType::TYPE_STRING)),
$message
);
}
Asserts that a variable is of type numeric.
public static function assertIsNumeric($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_NUMERIC),
$message
);
}
Asserts that a variable is of type object.
public static function assertIsObject($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_OBJECT),
$message
);
}
Asserts that a file/dir is readable.
public static function assertIsReadable(string $filename, string $message = ''): void
{
static::assertThat($filename, new IsReadable, $message);
}
Asserts that a variable is of type resource.
public static function assertIsResource($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_RESOURCE),
$message
);
}
Asserts that a variable is of type scalar.
public static function assertIsScalar($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_SCALAR),
$message
);
}
Asserts that a variable is of type string.
public static function assertIsString($actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsType(IsType::TYPE_STRING),
$message
);
}
Asserts that a file/dir exists and is writable.
public static function assertIsWritable(string $filename, string $message = ''): void
{
static::assertThat($filename, new IsWritable, $message);
}
Asserts that a string is a valid JSON string.
public static function assertJson(string $actualJson, string $message = ''): void
{
static::assertThat($actualJson, static::isJson(), $message);
}
Asserts that two JSON files are equal.
public static function assertJsonFileEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void
{
static::assertFileExists($expectedFile, $message);
static::assertFileExists($actualFile, $message);
$actualJson = \file_get_contents($actualFile);
$expectedJson = \file_get_contents($expectedFile);
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
$constraintExpected = new JsonMatches(
$expectedJson
);
$constraintActual = new JsonMatches($actualJson);
static::assertThat($expectedJson, $constraintActual, $message);
static::assertThat($actualJson, $constraintExpected, $message);
}
Asserts that two JSON files are not equal.
public static function assertJsonFileNotEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void
{
static::assertFileExists($expectedFile, $message);
static::assertFileExists($actualFile, $message);
$actualJson = \file_get_contents($actualFile);
$expectedJson = \file_get_contents($expectedFile);
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
$constraintExpected = new JsonMatches(
$expectedJson
);
$constraintActual = new JsonMatches($actualJson);
static::assertThat($expectedJson, new LogicalNot($constraintActual), $message);
static::assertThat($actualJson, new LogicalNot($constraintExpected), $message);
}
Asserts that the generated JSON encoded object and the content of the given file are equal.
public static function assertJsonStringEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void
{
static::assertFileExists($expectedFile, $message);
$expectedJson = \file_get_contents($expectedFile);
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
static::assertThat($actualJson, new JsonMatches($expectedJson), $message);
}
Asserts that two given JSON encoded objects or arrays are equal.
public static function assertJsonStringEqualsJsonString(string $expectedJson, string $actualJson, string $message = ''): void
{
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
static::assertThat($actualJson, new JsonMatches($expectedJson), $message);
}
Asserts that the generated JSON encoded object and the content of the given file are not equal.
public static function assertJsonStringNotEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void
{
static::assertFileExists($expectedFile, $message);
$expectedJson = \file_get_contents($expectedFile);
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
static::assertThat(
$actualJson,
new LogicalNot(
new JsonMatches($expectedJson)
),
$message
);
}
Asserts that two given JSON encoded objects or arrays are not equal.
string
$expectedJson
required - $expectedJson string
$actualJson
required -
unknown
$message
= string(0) "" public static function assertJsonStringNotEqualsJsonString($expectedJson, $actualJson, string $message = ''): void
{
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
static::assertThat(
$actualJson,
new LogicalNot(
new JsonMatches($expectedJson)
),
$message
);
}
Asserts that a value is smaller than another value.
public static function assertLessThan($expected, $actual, string $message = ''): void
{
static::assertThat($actual, static::lessThan($expected), $message);
}
Asserts that a value is smaller than or equal to another value.
public static function assertLessThanOrEqual($expected, $actual, string $message = ''): void
{
static::assertThat($actual, static::lessThanOrEqual($expected), $message);
}
Asserts that a variable is nan.
public static function assertNan($actual, string $message = ''): void
{
static::assertThat($actual, static::isNan(), $message);
}
Asserts that a haystack does not contain a needle.
public static function assertNotContains($needle, $haystack, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
{
if (\is_array($haystack) ||
(\is_object($haystack) && $haystack instanceof Traversable)) {
$constraint = new LogicalNot(
new TraversableContains(
$needle,
$checkForObjectIdentity,
$checkForNonObjectIdentity
)
);
} elseif (\is_string($haystack)) {
if (!\is_string($needle)) {
throw InvalidArgumentHelper::factory(
1,
'string'
);
}
$constraint = new LogicalNot(
new StringContains(
$needle,
$ignoreCase
)
);
} else {
throw InvalidArgumentHelper::factory(
2,
'array, traversable or string'
);
}
static::assertThat($haystack, $constraint, $message);
}
Asserts that a haystack does not contain only values of a given type.
public static function assertNotContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void
{
if ($isNativeType === null) {
$isNativeType = Type::isType($type);
}
static::assertThat(
$haystack,
new LogicalNot(
new TraversableContainsOnly(
$type,
$isNativeType
)
),
$message
);
}
Asserts the number of elements of an array, Countable or Traversable.
Countable|iterable
$expectedCount
required - $haystack
unknown
$haystack
required unknown
$message
= string(0) "" public static function assertNotCount(int $expectedCount, $haystack, string $message = ''): void
{
if (!$haystack instanceof Countable && !\is_iterable($haystack)) {
throw InvalidArgumentHelper::factory(2, 'countable or iterable');
}
$constraint = new LogicalNot(
new Count($expectedCount)
);
static::assertThat($haystack, $constraint, $message);
}
Asserts that a variable is not empty.
public static function assertNotEmpty($actual, string $message = ''): void
{
static::assertThat($actual, static::logicalNot(static::isEmpty()), $message);
}
Asserts that two variables are not equal.
float
$expected
required - $delta int
$actual
required - $maxDepth bool
$message
= string(0) "" - $canonicalize bool
$delta
= float 0 - $ignoreCase
unknown
$maxDepth
= integer 10 unknown
$canonicalize
= bool FALSE unknown
$ignoreCase
= bool FALSE public static function assertNotEquals($expected, $actual, string $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false): void
{
$constraint = new LogicalNot(
new IsEqual(
$expected,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
)
);
static::assertThat($actual, $constraint, $message);
}
Asserts that two variables are not equal (canonicalizing).
public static function assertNotEqualsCanonicalizing($expected, $actual, string $message = ''): void
{
$constraint = new LogicalNot(
new IsEqual(
$expected,
0.0,
10,
true,
false
)
);
static::assertThat($actual, $constraint, $message);
}
Asserts that two variables are not equal (ignoring case).
public static function assertNotEqualsIgnoringCase($expected, $actual, string $message = ''): void
{
$constraint = new LogicalNot(
new IsEqual(
$expected,
0.0,
10,
false,
true
)
);
static::assertThat($actual, $constraint, $message);
}
Asserts that two variables are not equal (with delta).
public static function assertNotEqualsWithDelta($expected, $actual, float $delta, string $message = ''): void
{
$constraint = new LogicalNot(
new IsEqual(
$expected,
$delta
)
);
static::assertThat($actual, $constraint, $message);
}
Asserts that a condition is not false.
public static function assertNotFalse($condition, string $message = ''): void
{
static::assertThat($condition, static::logicalNot(static::isFalse()), $message);
}
Asserts that a variable is not of a given type.
public static function assertNotInstanceOf(string $expected, $actual, string $message = ''): void
{
if (!\class_exists($expected) && !\interface_exists($expected)) {
throw InvalidArgumentHelper::factory(1, 'class or interface name');
}
static::assertThat(
$actual,
new LogicalNot(
new IsInstanceOf($expected)
),
$message
);
}
Asserts that a variable is not of a given type.
public static function assertNotInternalType(string $expected, $actual, string $message = ''): void
{
static::assertThat(
$actual,
new LogicalNot(
new IsType($expected)
),
$message
);
}
Asserts that a file/dir exists and is not readable.
public static function assertNotIsReadable(string $filename, string $message = ''): void
{
static::assertThat($filename, new LogicalNot(new IsReadable), $message);
}
Asserts that a file/dir exists and is not writable.
public static function assertNotIsWritable(string $filename, string $message = ''): void
{
static::assertThat($filename, new LogicalNot(new IsWritable), $message);
}
Asserts that a variable is not null.
public static function assertNotNull($actual, string $message = ''): void
{
static::assertThat($actual, static::logicalNot(static::isNull()), $message);
}
Asserts that a string does not match a given regular expression.
public static function assertNotRegExp(string $pattern, string $string, string $message = ''): void
{
static::assertThat(
$string,
new LogicalNot(
new RegularExpression($pattern)
),
$message
);
}
Asserts that two variables do not have the same type and value. Used on objects, it asserts that two variables do not reference the same object.
public static function assertNotSame($expected, $actual, string $message = ''): void
{
if (\is_bool($expected) && \is_bool($actual)) {
static::assertNotEquals($expected, $actual, $message);
}
static::assertThat(
$actual,
new LogicalNot(
new IsIdentical($expected)
),
$message
);
}
Assert that the size of two arrays (or Countable or Traversable objects)
is not the same.
Countable|iterable
$expected
required - $expected Countable|iterable
$actual
required -
unknown
$message
= string(0) "" public static function assertNotSameSize($expected, $actual, string $message = ''): void
{
if (!$expected instanceof Countable && !\is_iterable($expected)) {
throw InvalidArgumentHelper::factory(1, 'countable or iterable');
}
if (!$actual instanceof Countable && !\is_iterable($actual)) {
throw InvalidArgumentHelper::factory(2, 'countable or iterable');
}
static::assertThat(
$actual,
new LogicalNot(
new SameSize($expected)
),
$message
);
}
Asserts that a condition is not true.
public static function assertNotTrue($condition, string $message = ''): void
{
static::assertThat($condition, static::logicalNot(static::isTrue()), $message);
}
Asserts that a variable is null.
public static function assertNull($actual, string $message = ''): void
{
static::assertThat($actual, static::isNull(), $message);
}
Asserts that an object has a specified attribute.
object
$attributeName
required - $object
unknown
$object
required unknown
$message
= string(0) "" public static function assertObjectHasAttribute(string $attributeName, $object, string $message = ''): void
{
if (!self::isValidObjectAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!\is_object($object)) {
throw InvalidArgumentHelper::factory(2, 'object');
}
static::assertThat(
$object,
new ObjectHasAttribute($attributeName),
$message
);
}
Asserts that an object does not have a specified attribute.
object
$attributeName
required - $object
unknown
$object
required unknown
$message
= string(0) "" public static function assertObjectNotHasAttribute(string $attributeName, $object, string $message = ''): void
{
if (!self::isValidObjectAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!\is_object($object)) {
throw InvalidArgumentHelper::factory(2, 'object');
}
static::assertThat(
$object,
new LogicalNot(
new ObjectHasAttribute($attributeName)
),
$message
);
}
Asserts that a string matches a given regular expression.
public static function assertRegExp(string $pattern, string $string, string $message = ''): void
{
static::assertThat($string, new RegularExpression($pattern), $message);
}
Asserts that two variables have the same type and value. Used on objects, it asserts that two variables reference the same object.
public static function assertSame($expected, $actual, string $message = ''): void
{
static::assertThat(
$actual,
new IsIdentical($expected),
$message
);
}
Assert that the size of two arrays (or Countable or Traversable objects)
is the same.
Countable|iterable
$expected
required - $expected Countable|iterable
$actual
required -
unknown
$message
= string(0) "" public static function assertSameSize($expected, $actual, string $message = ''): void
{
if (!$expected instanceof Countable && !\is_iterable($expected)) {
throw InvalidArgumentHelper::factory(1, 'countable or iterable');
}
if (!$actual instanceof Countable && !\is_iterable($actual)) {
throw InvalidArgumentHelper::factory(2, 'countable or iterable');
}
static::assertThat(
$actual,
new SameSize($expected),
$message
);
}
public static function assertStringContainsString(string $needle, string $haystack, string $message = ''): void
{
$constraint = new StringContains($needle, false);
static::assertThat($haystack, $constraint, $message);
}
public static function assertStringContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void
{
$constraint = new StringContains($needle, true);
static::assertThat($haystack, $constraint, $message);
}
Asserts that a string ends not with a given suffix.
public static function assertStringEndsNotWith(string $suffix, string $string, string $message = ''): void
{
static::assertThat(
$string,
new LogicalNot(
new StringEndsWith($suffix)
),
$message
);
}
Asserts that a string ends with a given suffix.
public static function assertStringEndsWith(string $suffix, string $string, string $message = ''): void
{
static::assertThat($string, new StringEndsWith($suffix), $message);
}
Asserts that the contents of a string is equal to the contents of a file.
public static function assertStringEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
{
static::assertFileExists($expectedFile, $message);
/** @noinspection PhpUnitTestsInspection */
static::assertEquals(
\file_get_contents($expectedFile),
$actualString,
$message,
0,
10,
$canonicalize,
$ignoreCase
);
}
Asserts that a string matches a given format string.
public static function assertStringMatchesFormat(string $format, string $string, string $message = ''): void
{
static::assertThat($string, new StringMatchesFormatDescription($format), $message);
}
Asserts that a string matches a given format file.
public static function assertStringMatchesFormatFile(string $formatFile, string $string, string $message = ''): void
{
static::assertFileExists($formatFile, $message);
static::assertThat(
$string,
new StringMatchesFormatDescription(
\file_get_contents($formatFile)
),
$message
);
}
public static function assertStringNotContainsString(string $needle, string $haystack, string $message = ''): void
{
$constraint = new LogicalNot(new StringContains($needle));
static::assertThat($haystack, $constraint, $message);
}
public static function assertStringNotContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void
{
$constraint = new LogicalNot(new StringContains($needle, true));
static::assertThat($haystack, $constraint, $message);
}
Asserts that the contents of a string is not equal to the contents of a file.
public static function assertStringNotEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
{
static::assertFileExists($expectedFile, $message);
static::assertNotEquals(
\file_get_contents($expectedFile),
$actualString,
$message,
0,
10,
$canonicalize,
$ignoreCase
);
}
Asserts that a string does not match a given format string.
public static function assertStringNotMatchesFormat(string $format, string $string, string $message = ''): void
{
static::assertThat(
$string,
new LogicalNot(
new StringMatchesFormatDescription($format)
),
$message
);
}
Asserts that a string does not match a given format string.
public static function assertStringNotMatchesFormatFile(string $formatFile, string $string, string $message = ''): void
{
static::assertFileExists($formatFile, $message);
static::assertThat(
$string,
new LogicalNot(
new StringMatchesFormatDescription(
\file_get_contents($formatFile)
)
),
$message
);
}
Asserts that a string starts not with a given prefix.
string
$prefix
required - $prefix string
$string
required -
unknown
$message
= string(0) "" public static function assertStringStartsNotWith($prefix, $string, string $message = ''): void
{
static::assertThat(
$string,
new LogicalNot(
new StringStartsWith($prefix)
),
$message
);
}
Asserts that a string starts with a given prefix.
public static function assertStringStartsWith(string $prefix, string $string, string $message = ''): void
{
static::assertThat($string, new StringStartsWith($prefix), $message);
}
Evaluates a PHPUnit\Framework\Constraint matcher object.
public static function assertThat($value, Constraint $constraint, string $message = ''): void
{
self::$count += \count($constraint);
$constraint->evaluate($value, $message);
}
Asserts that a condition is true.
public static function assertTrue($condition, string $message = ''): void
{
static::assertThat($condition, static::isTrue(), $message);
}
Asserts that two XML files are equal.
public static function assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void
{
$expected = Xml::loadFile($expectedFile);
$actual = Xml::loadFile($actualFile);
static::assertEquals($expected, $actual, $message);
}
Asserts that two XML files are not equal.
public static function assertXmlFileNotEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void
{
$expected = Xml::loadFile($expectedFile);
$actual = Xml::loadFile($actualFile);
static::assertNotEquals($expected, $actual, $message);
}
Asserts that two XML documents are equal.
DOMDocument|string
$expectedFile
required - $actualXml
unknown
$actualXml
required unknown
$message
= string(0) "" public static function assertXmlStringEqualsXmlFile(string $expectedFile, $actualXml, string $message = ''): void
{
$expected = Xml::loadFile($expectedFile);
$actual = Xml::load($actualXml);
static::assertEquals($expected, $actual, $message);
}
Asserts that two XML documents are equal.
DOMDocument|string
$expectedXml
required - $expectedXml DOMDocument|string
$actualXml
required -
unknown
$message
= string(0) "" public static function assertXmlStringEqualsXmlString($expectedXml, $actualXml, string $message = ''): void
{
$expected = Xml::load($expectedXml);
$actual = Xml::load($actualXml);
static::assertEquals($expected, $actual, $message);
}
Asserts that two XML documents are not equal.
DOMDocument|string
$expectedFile
required - $actualXml
unknown
$actualXml
required unknown
$message
= string(0) "" public static function assertXmlStringNotEqualsXmlFile(string $expectedFile, $actualXml, string $message = ''): void
{
$expected = Xml::loadFile($expectedFile);
$actual = Xml::load($actualXml);
static::assertNotEquals($expected, $actual, $message);
}
Asserts that two XML documents are not equal.
DOMDocument|string
$expectedXml
required - $expectedXml DOMDocument|string
$actualXml
required -
unknown
$message
= string(0) "" public static function assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, string $message = ''): void
{
$expected = Xml::load($expectedXml);
$actual = Xml::load($actualXml);
static::assertNotEquals($expected, $actual, $message);
}
public static function attribute(Constraint $constraint, string $attributeName): Attribute
{
return new Attribute($constraint, $attributeName);
}
public static function attributeEqualTo(string $attributeName, $value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): Attribute
{
return static::attribute(
static::equalTo(
$value,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
),
$attributeName
);
}
public static function callback(callable $callback): Callback
{
return new Callback($callback);
}
public static function classHasAttribute(string $attributeName): ClassHasAttribute
{
return new ClassHasAttribute($attributeName);
}
public static function classHasStaticAttribute(string $attributeName): ClassHasStaticAttribute
{
return new ClassHasStaticAttribute($attributeName);
}
public static function contains($value, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): TraversableContains
{
return new TraversableContains($value, $checkForObjectIdentity, $checkForNonObjectIdentity);
}
public static function containsOnly(string $type): TraversableContainsOnly
{
return new TraversableContainsOnly($type);
}
public static function containsOnlyInstancesOf(string $className): TraversableContainsOnly
{
return new TraversableContainsOnly($className, false);
}
public static function countOf(int $count): Count
{
return new Count($count);
}
public static function directoryExists(): DirectoryExists
{
return new DirectoryExists;
}
public static function equalTo($value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): IsEqual
{
return new IsEqual($value, $delta, $maxDepth, $canonicalize, $ignoreCase);
}
Fails a test with the given message.
public static function fail(string $message = ''): void
{
self::$count++;
throw new AssertionFailedError($message);
}
public static function fileExists(): FileExists
{
return new FileExists;
}
Return the current assertion count.
public static function getCount(): int
{
return self::$count;
}
Returns the value of an object's attribute. This also works for attributes that are declared protected or private.
object
$object
required -
unknown
$attributeName
required public static function getObjectAttribute($object, string $attributeName)
{
if (!\is_object($object)) {
throw InvalidArgumentHelper::factory(1, 'object');
}
if (!self::isValidClassAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(2, 'valid attribute name');
}
try {
$reflector = new ReflectionObject($object);
do {
try {
$attribute = $reflector->getProperty($attributeName);
if (!$attribute || $attribute->isPublic()) {
return $object->$attributeName;
}
$attribute->setAccessible(true);
$value = $attribute->getValue($object);
$attribute->setAccessible(false);
return $value;
} catch (ReflectionException $e) {
}
} while ($reflector = $reflector->getParentClass());
} catch (ReflectionException $e) {
}
throw new Exception(
\sprintf(
'Attribute "%s" not found in object.',
$attributeName
)
);
}
Returns the value of a static attribute. This also works for attributes that are declared protected or private.
public static function getStaticAttribute(string $className, string $attributeName)
{
if (!\class_exists($className)) {
throw InvalidArgumentHelper::factory(1, 'class name');
}
if (!self::isValidClassAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(2, 'valid attribute name');
}
$class = new ReflectionClass($className);
while ($class) {
$attributes = $class->getStaticProperties();
if (\array_key_exists($attributeName, $attributes)) {
return $attributes[$attributeName];
}
$class = $class->getParentClass();
}
throw new Exception(
\sprintf(
'Attribute "%s" not found in class.',
$attributeName
)
);
}
public static function greaterThan($value): GreaterThan
{
return new GreaterThan($value);
}
public static function greaterThanOrEqual($value): LogicalOr
{
return static::logicalOr(
new IsEqual($value),
new GreaterThan($value)
);
}
public static function identicalTo($value): IsIdentical
{
return new IsIdentical($value);
}
public static function isEmpty(): IsEmpty
{
return new IsEmpty;
}
public static function isFalse(): IsFalse
{
return new IsFalse;
}
public static function isFinite(): IsFinite
{
return new IsFinite;
}
public static function isInfinite(): IsInfinite
{
return new IsInfinite;
}
public static function isInstanceOf(string $className): IsInstanceOf
{
return new IsInstanceOf($className);
}
public static function isJson(): IsJson
{
return new IsJson;
}
public static function isNan(): IsNan
{
return new IsNan;
}
public static function isNull(): IsNull
{
return new IsNull;
}
public static function isReadable(): IsReadable
{
return new IsReadable;
}
public static function isTrue(): IsTrue
{
return new IsTrue;
}
public static function isType(string $type): IsType
{
return new IsType($type);
}
public static function isWritable(): IsWritable
{
return new IsWritable;
}
public static function lessThan($value): LessThan
{
return new LessThan($value);
}
public static function lessThanOrEqual($value): LogicalOr
{
return static::logicalOr(
new IsEqual($value),
new LessThan($value)
);
}
public static function logicalAnd(): LogicalAnd
{
$constraints = \func_get_args();
$constraint = new LogicalAnd;
$constraint->setConstraints($constraints);
return $constraint;
}
public static function logicalNot(Constraint $constraint): LogicalNot
{
return new LogicalNot($constraint);
}
public static function logicalOr(): LogicalOr
{
$constraints = \func_get_args();
$constraint = new LogicalOr;
$constraint->setConstraints($constraints);
return $constraint;
}
public static function logicalXor(): LogicalXor
{
$constraints = \func_get_args();
$constraint = new LogicalXor;
$constraint->setConstraints($constraints);
return $constraint;
}
Mark the test as incomplete.
public static function markTestIncomplete(string $message = ''): void
{
throw new IncompleteTestError($message);
}
Mark the test as skipped.
public static function markTestSkipped(string $message = ''): void
{
throw new SkippedTestError($message);
}
public static function matches(string $string): StringMatchesFormatDescription
{
return new StringMatchesFormatDescription($string);
}
public static function matchesRegularExpression(string $pattern): RegularExpression
{
return new RegularExpression($pattern);
}
public static function objectHasAttribute($attributeName): ObjectHasAttribute
{
return new ObjectHasAttribute($attributeName);
}
Returns the value of an attribute of a class or an object. This also works for attributes that are declared protected or private.
object|string
$classOrObject
required -
unknown
$attributeName
required public static function readAttribute($classOrObject, string $attributeName)
{
if (!self::isValidClassAttributeName($attributeName)) {
throw InvalidArgumentHelper::factory(2, 'valid attribute name');
}
if (\is_string($classOrObject)) {
if (!\class_exists($classOrObject)) {
throw InvalidArgumentHelper::factory(
1,
'class name'
);
}
return static::getStaticAttribute(
$classOrObject,
$attributeName
);
}
if (\is_object($classOrObject)) {
return static::getObjectAttribute(
$classOrObject,
$attributeName
);
}
throw InvalidArgumentHelper::factory(
1,
'class name or object'
);
}
Reset the assertion counter.
public static function resetCount(): void
{
self::$count = 0;
}
public static function stringContains(string $string, bool $case = true): StringContains
{
return new StringContains($string, $case);
}
public static function stringEndsWith(string $suffix): StringEndsWith
{
return new StringEndsWith($suffix);
}
public static function stringStartsWith($prefix): StringStartsWith
{
return new StringStartsWith($prefix);
}
Performs assertions shared by all tests of a test case.
This method is called between test and tearDown().
protected function assertPostConditions()/* The :void return type declaration that should be here would cause a BC issue */
{
}
Performs assertions shared by all tests of a test case.
This method is called between setUp() and test.
protected function assertPreConditions()/* The :void return type declaration that should be here would cause a BC issue */
{
}
Returns a configured test double for the specified class.
string|string[]
$originalClassName
required -
unknown
$configuration
required protected function createConfiguredMock($originalClassName, array $configuration): MockObject
{
$o = $this->createMock($originalClassName);
foreach ($configuration as $method => $return) {
$o->method($method)->willReturn($return);
}
return $o;
}
Returns a test double for the specified class.
string|string[]
$originalClassName
required -
protected function createMock($originalClassName): MockObject
{
return $this->getMockBuilder($originalClassName)
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->getMock();
}
Returns a partial test double for the specified class.
string|string[]
$originalClassName
required - $originalClassName string[]
$methods
required -
protected function createPartialMock($originalClassName, array $methods): MockObject
{
return $this->getMockBuilder($originalClassName)
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->setMethods(empty($methods) ? null : $methods)
->getMock();
}
Creates a default TestResult object.
protected function createResult(): TestResult
{
return new TestResult;
}
Returns a test proxy for the specified class.
protected function createTestProxy(string $originalClassName, array $constructorArguments = []): MockObject
{
return $this->getMockBuilder($originalClassName)
->setConstructorArgs($constructorArguments)
->enableProxyingToOriginalMethods()
->getMock();
}
Mocks the specified class and returns the name of the mocked class.
string
$originalClassName
required - $originalClassName array
$methods
= array(0) - $methods string
$arguments
= array(0) - $mockClassName bool
$mockClassName
= string(0) "" - $callOriginalConstructor bool
$callOriginalConstructor
= bool FALSE - $callOriginalClone bool
$callOriginalClone
= bool TRUE - $callAutoload bool
$callAutoload
= bool TRUE - $cloneArguments
unknown
$cloneArguments
= bool FALSE protected function getMockClass($originalClassName, $methods = [], array $arguments = [], $mockClassName = '', $callOriginalConstructor = false, $callOriginalClone = true, $callAutoload = true, $cloneArguments = false): string
{
$mock = $this->getMockObjectGenerator()->getMock(
$originalClassName,
$methods,
$arguments,
$mockClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$cloneArguments
);
return \get_class($mock);
}
Returns a mock object for the specified abstract class with all abstract methods of the class mocked. Concrete methods are not mocked by default. To mock concrete methods, use the 7th parameter ($mockedMethods).
string
$originalClassName
required - $originalClassName string
$arguments
= array(0) - $mockClassName bool
$mockClassName
= string(0) "" - $callOriginalConstructor bool
$callOriginalConstructor
= bool TRUE - $callOriginalClone bool
$callOriginalClone
= bool TRUE - $callAutoload array
$callAutoload
= bool TRUE - $mockedMethods bool
$mockedMethods
= array(0) - $cloneArguments
unknown
$cloneArguments
= bool FALSE protected function getMockForAbstractClass($originalClassName, array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $mockedMethods = [], $cloneArguments = false): MockObject
{
$mockObject = $this->getMockObjectGenerator()->getMockForAbstractClass(
$originalClassName,
$arguments,
$mockClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$mockedMethods,
$cloneArguments
);
$this->registerMockObject($mockObject);
return $mockObject;
}
Returns a mock object for the specified trait with all abstract methods
of the trait mocked. Concrete methods to mock can be specified with the
$mockedMethods parameter.
string
$traitName
required - $traitName string
$arguments
= array(0) - $mockClassName bool
$mockClassName
= string(0) "" - $callOriginalConstructor bool
$callOriginalConstructor
= bool TRUE - $callOriginalClone bool
$callOriginalClone
= bool TRUE - $callAutoload array
$callAutoload
= bool TRUE - $mockedMethods bool
$mockedMethods
= array(0) - $cloneArguments
unknown
$cloneArguments
= bool FALSE protected function getMockForTrait($traitName, array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $mockedMethods = [], $cloneArguments = false): MockObject
{
$mockObject = $this->getMockObjectGenerator()->getMockForTrait(
$traitName,
$arguments,
$mockClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$mockedMethods,
$cloneArguments
);
$this->registerMockObject($mockObject);
return $mockObject;
}
Returns a mock object based on the given WSDL file.
string
$wsdlFile
required - $wsdlFile string
$originalClassName
= string(0) "" - $originalClassName string
$mockClassName
= string(0) "" - $mockClassName bool
$methods
= array(0) - $callOriginalConstructor array
$callOriginalConstructor
= bool TRUE - $options An array of options passed to SOAPClient::_construct
unknown
$options
= array(0) protected function getMockFromWsdl($wsdlFile, $originalClassName = '', $mockClassName = '', array $methods = [], $callOriginalConstructor = true, array $options = []): MockObject
{
if ($originalClassName === '') {
$fileName = \pathinfo(\basename(\parse_url($wsdlFile)['path']), \PATHINFO_FILENAME);
$originalClassName = \preg_replace('/[^a-zA-Z0-9_]/', '', $fileName);
}
if (!\class_exists($originalClassName)) {
eval(
$this->getMockObjectGenerator()->generateClassFromWsdl(
$wsdlFile,
$originalClassName,
$methods,
$options
)
);
}
$mockObject = $this->getMockObjectGenerator()->getMock(
$originalClassName,
$methods,
['', $options],
$mockClassName,
$callOriginalConstructor,
false,
false
);
$this->registerMockObject($mockObject);
return $mockObject;
}
Returns an object for the specified trait.
string
$traitName
required - $traitName string
$arguments
= array(0) - $traitClassName bool
$traitClassName
= string(0) "" - $callOriginalConstructor bool
$callOriginalConstructor
= bool TRUE - $callOriginalClone bool
$callOriginalClone
= bool TRUE - $callAutoload
unknown
$callAutoload
= bool TRUE objectprotected function getObjectForTrait($traitName, array $arguments = [], $traitClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true)/*: object*/
{
return $this->getMockObjectGenerator()->getObjectForTrait(
$traitName,
$arguments,
$traitClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload
);
}
This method is a wrapper for the ini_set() function that automatically resets the modified php.ini setting to its original value after the test is run.
protected function iniSet(string $varName, $newValue): void
{
$currentValue = \ini_set($varName, $newValue);
if ($currentValue !== false) {
$this->iniSettings[$varName] = $currentValue;
} else {
throw new Exception(
\sprintf(
'INI setting "%s" could not be set to "%s".',
$varName,
$newValue
)
);
}
}
This method is called when a test method did not execute successfully.
protected function onNotSuccessfulTest(Throwable $t)/* The :void return type declaration that should be here would cause a BC issue */
{
throw $t;
}
null|string
$classOrInterface
= NULL -
protected function prophesize($classOrInterface = null): ObjectProphecy
{
return $this->getProphet()->prophesize($classOrInterface);
}
Override to run the test and assert its state.
protected function runTest()
{
if ($this->name === null) {
throw new Exception(
'PHPUnit\Framework\TestCase::$name must not be null.'
);
}
$testArguments = \array_merge($this->data, $this->dependencyInput);
$this->registerMockObjectsFromTestArguments($testArguments);
try {
$testResult = $this->{$this->name}(...\array_values($testArguments));
} catch (Throwable $exception) {
if (!$this->checkExceptionExpectations($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) {
$this->assertThat(
null,
new ExceptionConstraint(
$this->expectedException
)
);
} elseif ($this->expectedExceptionMessage !== null) {
$this->numAssertions++;
throw new AssertionFailedError(
\sprintf(
'Failed asserting that exception with message "%s" is thrown',
$this->expectedExceptionMessage
)
);
} elseif ($this->expectedExceptionMessageRegExp !== null) {
$this->numAssertions++;
throw new AssertionFailedError(
\sprintf(
'Failed asserting that exception with message matching "%s" is thrown',
$this->expectedExceptionMessageRegExp
)
);
} elseif ($this->expectedExceptionCode !== null) {
$this->numAssertions++;
throw new AssertionFailedError(
\sprintf(
'Failed asserting that exception with code "%s" is thrown',
$this->expectedExceptionCode
)
);
}
return $testResult;
}
This method is a wrapper for the setlocale() function that automatically resets the locale to its original value after the test is run.
protected function setLocale(...$args): void
{
if (\count($args) < 2) {
throw new Exception;
}
[$category, $locale] = $args;
if (\defined('LC_MESSAGES')) {
$categories[] = \LC_MESSAGES;
}
if (!\in_array($category, self::LOCALE_CATEGORIES, true)) {
throw new Exception;
}
if (!\is_array($locale) && !\is_string($locale)) {
throw new Exception;
}
$this->locale[$category] = \setlocale($category, 0);
$result = \setlocale(...$args);
if ($result === false) {
throw new Exception(
'The locale functionality is not implemented on your platform, ' .
'the specified locale does not exist or the category name is ' .
'invalid.'
);
}
}
private function checkExceptionExpectations(Throwable $throwable): bool
{
$result = false;
if ($this->expectedException !== null || $this->expectedExceptionCode !== null || $this->expectedExceptionMessage !== null || $this->expectedExceptionMessageRegExp !== null) {
$result = true;
}
if ($throwable instanceof Exception) {
$result = false;
}
if (\is_string($this->expectedException)) {
$reflector = new ReflectionClass($this->expectedException);
if ($this->expectedException === 'PHPUnit\Framework\Exception' ||
$this->expectedException === '\PHPUnit\Framework\Exception' ||
$reflector->isSubclassOf(Exception::class)) {
$result = true;
}
}
return $result;
}
private function checkRequirements(): void
{
if (!$this->name || !\method_exists($this, $this->name)) {
return;
}
$missingRequirements = \PHPUnit\Util\Test::getMissingRequirements(
\get_class($this),
$this->name
);
if (!empty($missingRequirements)) {
$this->markTestSkipped(\implode(\PHP_EOL, $missingRequirements));
}
}
private function cleanupIniSettings(): void
{
foreach ($this->iniSettings as $varName => $oldValue) {
\ini_set($varName, $oldValue);
}
$this->iniSettings = [];
}
private function cleanupLocaleSettings(): void
{
foreach ($this->locale as $category => $locale) {
\setlocale($category, $locale);
}
$this->locale = [];
}
private function compareGlobalStateSnapshotPart(array $before, array $after, string $header): void
{
if ($before != $after) {
$differ = new Differ($header);
$exporter = new Exporter;
$diff = $differ->diff(
$exporter->export($before),
$exporter->export($after)
);
throw new RiskyTestError(
$diff
);
}
}
private function compareGlobalStateSnapshots(Snapshot $before, Snapshot $after): void
{
$backupGlobals = $this->backupGlobals === null || $this->backupGlobals === true;
if ($backupGlobals) {
$this->compareGlobalStateSnapshotPart(
$before->globalVariables(),
$after->globalVariables(),
"--- Global variables before the test\n+++ Global variables after the test\n"
);
$this->compareGlobalStateSnapshotPart(
$before->superGlobalVariables(),
$after->superGlobalVariables(),
"--- Super-global variables before the test\n+++ Super-global variables after the test\n"
);
}
if ($this->backupStaticAttributes) {
$this->compareGlobalStateSnapshotPart(
$before->staticAttributes(),
$after->staticAttributes(),
"--- Static attributes before the test\n+++ Static attributes after the test\n"
);
}
}
private function createGlobalStateSnapshot(bool $backupGlobals): Snapshot
{
$blacklist = new Blacklist;
foreach ($this->backupGlobalsBlacklist as $globalVariable) {
$blacklist->addGlobalVariable($globalVariable);
}
if (!\defined('PHPUNIT_TESTSUITE')) {
$blacklist->addClassNamePrefix('PHPUnit');
$blacklist->addClassNamePrefix('SebastianBergmann\CodeCoverage');
$blacklist->addClassNamePrefix('SebastianBergmann\FileIterator');
$blacklist->addClassNamePrefix('SebastianBergmann\Invoker');
$blacklist->addClassNamePrefix('SebastianBergmann\Timer');
$blacklist->addClassNamePrefix('PHP_Token');
$blacklist->addClassNamePrefix('Symfony');
$blacklist->addClassNamePrefix('Text_Template');
$blacklist->addClassNamePrefix('Doctrine\Instantiator');
$blacklist->addClassNamePrefix('Prophecy');
foreach ($this->backupStaticAttributesBlacklist as $class => $attributes) {
foreach ($attributes as $attribute) {
$blacklist->addStaticAttribute($class, $attribute);
}
}
}
return new Snapshot(
$blacklist,
$backupGlobals,
(bool) $this->backupStaticAttributes,
false,
false,
false,
false,
false,
false,
false
);
}
Get the mock object generator, creating it if it doesn't exist.
private function getMockObjectGenerator(): MockGenerator
{
if ($this->mockObjectGenerator === null) {
$this->mockObjectGenerator = new MockGenerator;
}
return $this->mockObjectGenerator;
}
private function getProphet(): Prophet
{
if ($this->prophet === null) {
$this->prophet = new Prophet;
}
return $this->prophet;
}
private function handleDependencies(): bool
{
if (!empty($this->dependencies) && !$this->inIsolation) {
$className = \get_class($this);
$passed = $this->result->passed();
$passedKeys = \array_keys($passed);
$numKeys = \count($passedKeys);
for ($i = 0; $i < $numKeys; $i++) {
$pos = \strpos($passedKeys[$i], ' with data set');
if ($pos !== false) {
$passedKeys[$i] = \substr($passedKeys[$i], 0, $pos);
}
}
$passedKeys = \array_flip(\array_unique($passedKeys));
foreach ($this->dependencies as $dependency) {
$deepClone = false;
$shallowClone = false;
if (\strpos($dependency, 'clone ') === 0) {
$deepClone = true;
$dependency = \substr($dependency, \strlen('clone '));
} elseif (\strpos($dependency, '!clone ') === 0) {
$deepClone = false;
$dependency = \substr($dependency, \strlen('!clone '));
}
if (\strpos($dependency, 'shallowClone ') === 0) {
$shallowClone = true;
$dependency = \substr($dependency, \strlen('shallowClone '));
} elseif (\strpos($dependency, '!shallowClone ') === 0) {
$shallowClone = false;
$dependency = \substr($dependency, \strlen('!shallowClone '));
}
if (\strpos($dependency, '::') === false) {
$dependency = $className . '::' . $dependency;
}
if (!isset($passedKeys[$dependency])) {
if (!\is_callable($dependency, false, $callableName) || $dependency !== $callableName) {
$this->markWarningForUncallableDependency($dependency);
} else {
$this->markSkippedForMissingDependecy($dependency);
}
return false;
}
if (isset($passed[$dependency])) {
if ($passed[$dependency]['size'] != \PHPUnit\Util\Test::UNKNOWN &&
$this->getSize() != \PHPUnit\Util\Test::UNKNOWN &&
$passed[$dependency]['size'] > $this->getSize()) {
$this->result->addError(
$this,
new SkippedTestError(
'This test depends on a test that is larger than itself.'
),
0
);
return false;
}
if ($deepClone) {
$deepCopy = new DeepCopy;
$deepCopy->skipUncloneable(false);
$this->dependencyInput[$dependency] = $deepCopy->copy($passed[$dependency]['result']);
} elseif ($shallowClone) {
$this->dependencyInput[$dependency] = clone $passed[$dependency]['result'];
} else {
$this->dependencyInput[$dependency] = $passed[$dependency]['result'];
}
} else {
$this->dependencyInput[$dependency] = null;
}
}
}
return true;
}
private function isCloneable(MockObject $testArgument): bool
{
$reflector = new ReflectionObject($testArgument);
if (!$reflector->isCloneable()) {
return false;
}
if ($reflector->hasMethod('__clone') &&
$reflector->getMethod('__clone')->isPublic()) {
return true;
}
return false;
}
private function markSkippedForMissingDependecy(string $dependency): void
{
$this->status = BaseTestRunner::STATUS_SKIPPED;
$this->result->startTest($this);
$this->result->addError(
$this,
new SkippedTestError(
\sprintf(
'This test depends on "%s" to pass.',
$dependency
)
),
0
);
$this->result->endTest($this, 0);
}
private function markWarningForUncallableDependency(string $dependency): void
{
$this->status = BaseTestRunner::STATUS_WARNING;
$this->result->startTest($this);
$this->result->addWarning(
$this,
new Warning(
\sprintf(
'This test depends on "%s" which does not exist.',
$dependency
)
),
0
);
$this->result->endTest($this, 0);
}
private function registerMockObjectsFromTestArguments(array $testArguments, array &$visited = []): void
{
if ($this->registerMockObjectsFromTestArgumentsRecursively) {
$enumerator = new Enumerator;
foreach ($enumerator->enumerate($testArguments) as $object) {
if ($object instanceof MockObject) {
$this->registerMockObject($object);
}
}
} else {
foreach ($testArguments as $testArgument) {
if ($testArgument instanceof MockObject) {
if ($this->isCloneable($testArgument)) {
$testArgument = clone $testArgument;
}
$this->registerMockObject($testArgument);
} elseif (\is_array($testArgument) && !\in_array($testArgument, $visited, true)) {
$visited[] = $testArgument;
$this->registerMockObjectsFromTestArguments(
$testArgument,
$visited
);
}
}
}
}
private function restoreGlobalState(): void
{
if (!$this->snapshot instanceof Snapshot) {
return;
}
if ($this->beStrictAboutChangesToGlobalState) {
try {
$this->compareGlobalStateSnapshots(
$this->snapshot,
$this->createGlobalStateSnapshot($this->backupGlobals === true)
);
} catch (RiskyTestError $rte) {
// Intentionally left empty
}
}
$restorer = new Restorer;
if ($this->backupGlobals === true) {
$restorer->restoreGlobalVariables($this->snapshot);
}
if ($this->backupStaticAttributes) {
$restorer->restoreStaticAttributes($this->snapshot);
}
$this->snapshot = null;
if (isset($rte)) {
throw $rte;
}
}
private function runInSeparateProcess(): bool
{
return ($this->runTestInSeparateProcess === true || $this->runClassInSeparateProcess === true) &&
$this->inIsolation !== true && !$this instanceof PhptTestCase;
}
private function setDoesNotPerformAssertionsFromAnnotation(): void
{
$annotations = $this->getAnnotations();
if (isset($annotations['method']['doesNotPerformAssertions'])) {
$this->doesNotPerformAssertions = true;
}
}
private function setExpectedExceptionFromAnnotation(): void
{
try {
$expectedException = \PHPUnit\Util\Test::getExpectedException(
\get_class($this),
$this->name
);
if ($expectedException !== false) {
$this->expectException($expectedException['class']);
if ($expectedException['code'] !== null) {
$this->expectExceptionCode($expectedException['code']);
}
if ($expectedException['message'] !== '') {
$this->expectExceptionMessage($expectedException['message']);
} elseif ($expectedException['message_regex'] !== '') {
$this->expectExceptionMessageRegExp($expectedException['message_regex']);
}
}
} catch (ReflectionException $e) {
}
}
private function setUseErrorHandlerFromAnnotation(): void
{
try {
$useErrorHandler = \PHPUnit\Util\Test::getErrorHandlerSettings(
\get_class($this),
$this->name
);
if ($useErrorHandler !== null) {
$this->setUseErrorHandler($useErrorHandler);
}
} catch (ReflectionException $e) {
}
}
private function shouldInvocationMockerBeReset(MockObject $mock): bool
{
$enumerator = new Enumerator;
foreach ($enumerator->enumerate($this->dependencyInput) as $object) {
if ($mock === $object) {
return false;
}
}
if (!\is_array($this->testResult) && !\is_object($this->testResult)) {
return true;
}
return !\in_array($mock, $enumerator->enumerate($this->testResult), true);
}
private function snapshotGlobalState(): void
{
if ($this->runTestInSeparateProcess || $this->inIsolation ||
(!$this->backupGlobals === true && !$this->backupStaticAttributes)) {
return;
}
$this->snapshot = $this->createGlobalStateSnapshot($this->backupGlobals === true);
}
private function startOutputBuffering(): void
{
\ob_start();
$this->outputBufferingActive = true;
$this->outputBufferingLevel = \ob_get_level();
}
private function stopOutputBuffering(): void
{
if (\ob_get_level() !== $this->outputBufferingLevel) {
while (\ob_get_level() >= $this->outputBufferingLevel) {
\ob_end_clean();
}
throw new RiskyTestError(
'Test code or tested code did not (only) close its own output buffers'
);
}
$this->output = \ob_get_contents();
if ($this->outputCallback !== false) {
$this->output = (string) \call_user_func($this->outputCallback, $this->output);
}
\ob_end_clean();
$this->outputBufferingActive = false;
$this->outputBufferingLevel = \ob_get_level();
}
private function unregisterCustomComparators(): void
{
$factory = ComparatorFactory::getInstance();
foreach ($this->customComparators as $comparator) {
$factory->unregister($comparator);
}
$this->customComparators = [];
}
private function verifyMockObjects(): void
{
foreach ($this->mockObjects as $mockObject) {
if ($mockObject->__phpunit_hasMatchers()) {
$this->numAssertions++;
}
$mockObject->__phpunit_verify(
$this->shouldInvocationMockerBeReset($mockObject)
);
}
if ($this->prophet !== null) {
try {
$this->prophet->checkPredictions();
} finally {
foreach ($this->prophet->getProphecies() as $objectProphecy) {
foreach ($objectProphecy->getMethodProphecies() as $methodProphecies) {
/** @var MethodProphecy[] $methodProphecies */
foreach ($methodProphecies as $methodProphecy) {
$this->numAssertions += \count($methodProphecy->getCheckedPredictions());
}
}
}
}
}
}
private static function createWarning(string $warning): void
{
foreach (\debug_backtrace() as $step) {
if (isset($step['object']) && $step['object'] instanceof TestCase) {
$step['object']->addWarning($warning);
break;
}
}
}
private static function isValidClassAttributeName(string $attributeName): bool
{
return \preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName);
}
private static function isValidObjectAttributeName(string $attributeName): bool
{
return \preg_match('/[^\x00-\x1f\x7f-\x9f]+/', $attributeName);
}