From f686b50824a75eb17677987adfcc4366dc9f8f65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Werner=20M=2E=20Krau=C3=9F?= Date: Wed, 27 Sep 2017 09:25:37 +0200 Subject: [PATCH] API Rename assert dos to assert list --- src/Dev/Constraint/SSListContains.php | 139 +++++++ src/Dev/Constraint/SSListContainsOnly.php | 80 ++++ .../SSListContainsOnlyMatchingItems.php | 89 ++++ src/Dev/Constraint/ViewableDataContains.php | 96 +++++ src/Dev/SSListExporter.php | 85 ++++ src/Dev/SapphireTest.php | 385 ++++++++++-------- tests/php/Control/ControllerTest.php | 5 +- .../SSListContainsOnlyMatchingItemsTest.php | 42 ++ tests/php/Dev/SSListContainsOnlyTest.php | 87 ++++ tests/php/Dev/SSListContainsTest.php | 91 +++++ tests/php/Dev/SSListExporterTest.php | 85 ++++ tests/php/Dev/SapphireTestTest.php | 201 ++++++++- .../php/Dev/SapphireTestTest/DataProvider.php | 187 +++++++++ tests/php/Dev/ViewableDataContainsTest.php | 103 +++++ .../GridFieldAddExistingAutocompleterTest.php | 2 +- .../GridField/GridFieldDataColumnsTest.php | 3 +- .../GridField/GridFieldDetailFormTest.php | 2 +- tests/php/Forms/GridField/GridFieldTest.php | 26 +- tests/php/ORM/CascadeDeleteTest.php | 20 +- tests/php/ORM/DBDateTest.php | 16 +- tests/php/ORM/DataExtensionTest.php | 3 +- tests/php/ORM/DataListTest.php | 75 ++-- tests/php/ORM/DataObjectDuplicationTest.php | 12 +- tests/php/ORM/DataObjectSchemaTest.php | 4 +- tests/php/ORM/DataObjectTest.php | 41 +- tests/php/ORM/ManyManyThroughListTest.php | 16 +- tests/php/ORM/PaginatedListTest.php | 31 +- tests/php/ORM/UnsavedRelationListTest.php | 26 +- tests/php/i18n/i18nTest.php | 4 +- tests/php/i18n/i18nTextCollectorTest.php | 21 +- 30 files changed, 1645 insertions(+), 332 deletions(-) create mode 100644 src/Dev/Constraint/SSListContains.php create mode 100644 src/Dev/Constraint/SSListContainsOnly.php create mode 100644 src/Dev/Constraint/SSListContainsOnlyMatchingItems.php create mode 100644 src/Dev/Constraint/ViewableDataContains.php create mode 100644 src/Dev/SSListExporter.php create mode 100644 tests/php/Dev/SSListContainsOnlyMatchingItemsTest.php create mode 100644 tests/php/Dev/SSListContainsOnlyTest.php create mode 100644 tests/php/Dev/SSListContainsTest.php create mode 100644 tests/php/Dev/SSListExporterTest.php create mode 100644 tests/php/Dev/SapphireTestTest/DataProvider.php create mode 100644 tests/php/Dev/ViewableDataContainsTest.php diff --git a/src/Dev/Constraint/SSListContains.php b/src/Dev/Constraint/SSListContains.php new file mode 100644 index 000000000..51eff1785 --- /dev/null +++ b/src/Dev/Constraint/SSListContains.php @@ -0,0 +1,139 @@ +exporter = new SSListExporter(); + + $this->matches = $matches; + } + + /** + * Evaluates the constraint for parameter $other + * + * If $returnResult is set to false (the default), an exception is thrown + * in case of a failure. null is returned otherwise. + * + * If $returnResult is true, the result of the evaluation is returned as + * a boolean value instead: true in case of success, false in case of a + * failure. + * + * @param SS_List $other Value or object to evaluate. + * @param string $description Additional information about the test + * @param bool $returnResult Whether to return a result or throw an exception + * + * @return null|bool + * + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function evaluate($other, $description = '', $returnResult = false) + { + $success = true; + + foreach ($other as $item) { + $this->checkIfItemEvaluatesRemainingMatches($item); + } + + //we have remaining matches? + if (count($this->matches) !== 0) { + $success = false; + $this->hasLeftoverItems = true; + } + + if ($returnResult) { + return $success; + } + + if (!$success) { + $this->fail($other, $description); + } + + return null; + } + + /** + * @param ViewableData $item + * @return bool + */ + protected function checkIfItemEvaluatesRemainingMatches(ViewableData $item) + { + $success = false; + foreach ($this->matches as $key => $match) { + $constraint = new ViewableDataContains($match); + + if ($constraint->evaluate($item, '', true)) { + $success = true; + unset($this->matches[$key]); + break; + } + } + + return $success; + } + + /** + * Returns a string representation of the object. + * + * @return string + */ + public function toString() + { + $matchToString = function ($key, $value) { + return ' "' . $key . '" is "' . $value . '"'; + }; + + $matchesToString = function ($matches) use ($matchToString) { + $matchesAsString = implode(' and ', array_map( + $matchToString, + array_keys($matches), + array_values($matches) + )); + + return '(' . $matchesAsString . ')'; + }; + + $allMatchesAsString = implode( + "\n or ", + array_map($matchesToString, $this->matches) + ); + + + return $this->getStubForToString() . $allMatchesAsString; + } + + protected function getStubForToString() + { + return ' contains an item matching '; + } +} diff --git a/src/Dev/Constraint/SSListContainsOnly.php b/src/Dev/Constraint/SSListContainsOnly.php new file mode 100644 index 000000000..0be563ac9 --- /dev/null +++ b/src/Dev/Constraint/SSListContainsOnly.php @@ -0,0 +1,80 @@ +checkIfItemEvaluatesRemainingMatches($item)) { + $this->itemNotMatching = true; + $success = false; + break; + } + } + + //we have remaining matches? + if (!$this->itemNotMatching && count($this->matches) !== 0) { + $success = false; + $this->hasLeftoverItems = true; + } + + if ($returnResult) { + return $success; + } + + if (!$success) { + $this->fail($other, $description); + } + + return null; + } + + protected function getStubForToString() + { + return $this->itemNotMatching + ? parent::getStubForToString() + : " contained only the given items, the following items were left over:\n"; + } +} diff --git a/src/Dev/Constraint/SSListContainsOnlyMatchingItems.php b/src/Dev/Constraint/SSListContainsOnlyMatchingItems.php new file mode 100644 index 000000000..d17ec07e0 --- /dev/null +++ b/src/Dev/Constraint/SSListContainsOnlyMatchingItems.php @@ -0,0 +1,89 @@ +exporter = new SSListExporter(); + + $this->constraint = new ViewableDataContains($match); + $this->match = $match; + } + + /** + * Evaluates the constraint for parameter $other + * + * If $returnResult is set to false (the default), an exception is thrown + * in case of a failure. null is returned otherwise. + * + * If $returnResult is true, the result of the evaluation is returned as + * a boolean value instead: true in case of success, false in case of a + * failure. + * + * @param SS_List $other Value or object to evaluate. + * @param string $description Additional information about the test + * @param bool $returnResult Whether to return a result or throw an exception + * + * @return null|bool + * + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function evaluate($other, $description = '', $returnResult = false) + { + $success = true; + + foreach ($other as $item) { + if (!$this->constraint->evaluate($item, '', true)) { + $success = false; + break; + } + } + + if ($returnResult) { + return $success; + } + + if (!$success) { + $this->fail($other, $description); + } + + return null; + } + + /** + * Returns a string representation of the object. + * + * @return string + */ + public function toString() + { + return 'contains only Objects where "' . key($this->match) . '" is "' . current($this->match) . '"'; + } +} diff --git a/src/Dev/Constraint/ViewableDataContains.php b/src/Dev/Constraint/ViewableDataContains.php new file mode 100644 index 000000000..c26084509 --- /dev/null +++ b/src/Dev/Constraint/ViewableDataContains.php @@ -0,0 +1,96 @@ +match = $match; + } + + /** + * Evaluates the constraint for parameter $other + * + * If $returnResult is set to false (the default), an exception is thrown + * in case of a failure. null is returned otherwise. + * + * If $returnResult is true, the result of the evaluation is returned as + * a boolean value instead: true in case of success, false in case of a + * failure. + * + * @param ViewableData $other Value or object to evaluate. + * @param string $description Additional information about the test + * @param bool $returnResult Whether to return a result or throw an exception + * + * @return null|bool + * + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function evaluate($other, $description = '', $returnResult = false) + { + $success = true; + + foreach ($this->match as $fieldName => $value) { + if ($other->getField($fieldName) != $value) { + $success = false; + break; + } + } + + if ($returnResult) { + return $success; + } + + if (!$success) { + $this->fail($other, $description); + } + + return null; + } + + + /** + * Returns a string representation of the object. + * + * @todo: add representation for more than one match + * + * @return string + */ + public function toString() + { + return 'contains only Objects where "' . key($this->match) . '" is "' . current($this->match) . '"'; + } +} diff --git a/src/Dev/SSListExporter.php b/src/Dev/SSListExporter.php new file mode 100644 index 000000000..96293162f --- /dev/null +++ b/src/Dev/SSListExporter.php @@ -0,0 +1,85 @@ +contains($value)) !== false) { + return $className . ' &' . $key; + } + + $list = $value; + $key = $processed->add($value); + $values = ''; + + if ($list->count() > 0) { + foreach ($list as $k => $v) { + $values .= sprintf( + '%s %s ' . "\n", + $whitespace, + $this->recursiveExport($v, $indentation) + ); + } + + $values = "\n" . $values . $whitespace; + } + + return sprintf($className . ' &%s (%s)', $key, $values); + } + + if ($value instanceof ViewableData) { + $className = get_class($value); + $data = $this->toMap($value); + + return sprintf( + '%s %s => %s' . "\n", + $whitespace, + $className, + $this->recursiveExport($data, $indentation + 2, $processed) + ); + } + + + return parent::recursiveExport($value, $indentation, $processed); + } + + /** + * @param ViewableData $object + * @return array + */ + public function toMap(ViewableData $object) + { + return $object->hasMethod('toMap') + ? $object->toMap() + : []; + } +} diff --git a/src/Dev/SapphireTest.php b/src/Dev/SapphireTest.php index ea3a7895f..0c3fec858 100644 --- a/src/Dev/SapphireTest.php +++ b/src/Dev/SapphireTest.php @@ -4,7 +4,9 @@ namespace SilverStripe\Dev; use Exception; use LogicException; +use PHPUnit_Framework_Constraint_Not; use PHPUnit_Framework_TestCase; +use PHPUnit_Util_InvalidArgumentHelper; use SilverStripe\CMS\Controllers\RootURLController; use SilverStripe\Control\CLIRequestBuilder; use SilverStripe\Control\Controller; @@ -12,12 +14,15 @@ use SilverStripe\Control\Cookie; use SilverStripe\Control\Director; use SilverStripe\Control\Email\Email; use SilverStripe\Control\Email\Mailer; +use SilverStripe\Control\HTTPApplication; use SilverStripe\Control\HTTPRequest; use SilverStripe\Core\Config\Config; -use SilverStripe\Control\HTTPApplication; use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\InjectorLoader; use SilverStripe\Core\Manifest\ClassLoader; +use SilverStripe\Dev\Constraint\SSListContains; +use SilverStripe\Dev\Constraint\SSListContainsOnly; +use SilverStripe\Dev\Constraint\SSListContainsOnlyMatchingItems; use SilverStripe\Dev\State\SapphireTestState; use SilverStripe\Dev\State\TestState; use SilverStripe\i18n\i18n; @@ -242,7 +247,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly $fixtureFiles = $this->getFixturePaths(); // Set up fixture - if ($fixtureFiles || $this->usesDatabase) { + if ($this->shouldSetupDatabaseForCurrentTest($fixtureFiles)) { if (!static::$tempDB->isUsed()) { static::$tempDB->build(); } @@ -266,7 +271,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly $fixture->writeInto($this->getFixtureFactory()); } - $this->logInWithPermission("ADMIN"); + $this->logInWithPermission('ADMIN'); } // turn off template debugging @@ -280,6 +285,50 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly Email::config()->remove('bcc_all_emails_to'); } + + + /** + * Helper method to determine if the current test should enable a test database + * + * @param $fixtureFiles + * @return bool + */ + protected function shouldSetupDatabaseForCurrentTest($fixtureFiles) + { + $databaseEnabledByDefault = $fixtureFiles || $this->usesDatabase; + + return ($databaseEnabledByDefault && !$this->currentTestDisablesDatabase()) + || $this->currentTestEnablesDatabase(); + } + + /** + * Helper method to check, if the current test uses the database. + * This can be switched on with the annotation "@useDatabase" + * + * @return bool + */ + protected function currentTestEnablesDatabase() + { + $annotations = $this->getAnnotations(); + + return array_key_exists('useDatabase', $annotations['method']) + && $annotations['method']['useDatabase'][0] !== 'false'; + } + + /** + * Helper method to check, if the current test uses the database. + * This can be switched on with the annotation "@useDatabase false" + * + * @return bool + */ + protected function currentTestDisablesDatabase() + { + $annotations = $this->getAnnotations(); + + return array_key_exists('useDatabase', $annotations['method']) + && $annotations['method']['useDatabase'][0] === 'false'; + } + /** * Called once per test case ({@link SapphireTest} subclass). * This is different to {@link setUp()}, which gets called once @@ -440,8 +489,8 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly { $filename = ClassLoader::inst()->getItemPath(static::class); if (!$filename) { - throw new LogicException("getItemPath returned null for " . static::class - . ". Try adding flush=1 to the test run."); + throw new LogicException('getItemPath returned null for ' . static::class + . '. Try adding flush=1 to the test run.'); } return dirname($filename); } @@ -540,7 +589,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * @return array|null Contains keys: 'Type', 'To', 'From', 'Subject', 'Content', 'PlainContent', 'AttachedFiles', * 'HtmlContent' */ - public function findEmail($to, $from = null, $subject = null, $content = null) + public static function findEmail($to, $from = null, $subject = null, $content = null) { /** @var Mailer $mailer */ $mailer = Injector::inst()->get(Mailer::class); @@ -559,11 +608,11 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * @param string $subject * @param string $content */ - public function assertEmailSent($to, $from = null, $subject = null, $content = null) + public static function assertEmailSent($to, $from = null, $subject = null, $content = null) { - $found = (bool)$this->findEmail($to, $from, $subject, $content); + $found = (bool)static::findEmail($to, $from, $subject, $content); - $infoParts = ""; + $infoParts = ''; $withParts = array(); if ($to) { $infoParts .= " to '$to'"; @@ -578,10 +627,10 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly $withParts[] = "content '$content'"; } if ($withParts) { - $infoParts .= " with " . implode(" and ", $withParts); + $infoParts .= ' with ' . implode(' and ', $withParts); } - $this->assertTrue( + static::assertTrue( $found, "Failed asserting that an email was sent$infoParts." ); @@ -594,91 +643,103 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * * @param SS_List|array $matches The patterns to match. Each pattern is a map of key-value pairs. You can * either pass a single pattern or an array of patterns. - * @param SS_List $dataObjectSet The {@link SS_List} to test. + * @param SS_List $list The {@link SS_List} to test. + * @param string $message * * Examples * -------- * Check that $members includes an entry with Email = sam@example.com: - * $this->assertDOSContains(array('Email' => '...@example.com'), $members); + * $this->assertListContains(['Email' => '...@example.com'], $members); * * Check that $members includes entries with Email = sam@example.com and with * Email = ingo@example.com: - * $this->assertDOSContains(array( - * array('Email' => '...@example.com'), - * array('Email' => 'i...@example.com'), - * ), $members); + * $this->assertListContains([ + * ['Email' => '...@example.com'], + * ['Email' => 'i...@example.com'], + * ], $members); + */ + public static function assertListContains($matches, SS_List $list, $message = '') + { + if (!is_array($matches)) { + throw PHPUnit_Util_InvalidArgumentHelper::factory( + 1, + 'array' + ); + } + + static::assertThat( + $list, + new SSListContains( + $matches + ), + $message + ); + } + + /** + * @deprecated 4.0.0:5.0.0 Use assertListContains() instead + * + * @param $matches + * @param $dataObjectSet */ public function assertDOSContains($matches, $dataObjectSet) { - $extracted = array(); - foreach ($dataObjectSet as $object) { - /** @var DataObject $object */ - $extracted[] = $object->toMap(); - } - - foreach ($matches as $match) { - $matched = false; - foreach ($extracted as $i => $item) { - if ($this->dataObjectArrayMatch($item, $match)) { - // Remove it from $extracted so that we don't get duplicate mapping. - unset($extracted[$i]); - $matched = true; - break; - } - } - - // We couldn't find a match - assertion failed - $this->assertTrue( - $matched, - "Failed asserting that the SS_List contains an item matching " - . var_export($match, true) . "\n\nIn the following SS_List:\n" - . $this->DOSSummaryForMatch($dataObjectSet, $match) - ); - } + Deprecation::notice('5.0', 'Use assertListContains() instead'); + return static::assertListContains($matches, $dataObjectSet); } + /** * Asserts that no items in a given list appear in the given dataobject list * * @param SS_List|array $matches The patterns to match. Each pattern is a map of key-value pairs. You can * either pass a single pattern or an array of patterns. - * @param SS_List $dataObjectSet The {@link SS_List} to test. + * @param SS_List $list The {@link SS_List} to test. + * @param string $message * * Examples * -------- * Check that $members doesn't have an entry with Email = sam@example.com: - * $this->assertNotDOSContains(array('Email' => '...@example.com'), $members); + * $this->assertListNotContains(['Email' => '...@example.com'], $members); * * Check that $members doesn't have entries with Email = sam@example.com and with * Email = ingo@example.com: - * $this->assertNotDOSContains(array( - * array('Email' => '...@example.com'), - * array('Email' => 'i...@example.com'), - * ), $members); + * $this->assertListNotContains([ + * ['Email' => '...@example.com'], + * ['Email' => 'i...@example.com'], + * ], $members); */ - public function assertNotDOSContains($matches, $dataObjectSet) + public static function assertListNotContains($matches, SS_List $list, $message = '') { - $extracted = array(); - foreach ($dataObjectSet as $object) { - /** @var DataObject $object */ - $extracted[] = $object->toMap(); - } - - $matched = []; - foreach ($matches as $match) { - foreach ($extracted as $i => $item) { - if ($this->dataObjectArrayMatch($item, $match)) { - $matched[] = $extracted[$i]; - break; - } - } - - // We couldn't find a match - assertion failed - $this->assertEmpty( - $matched, - "Failed asserting that the SS_List dosn't contain a set of objects. " - . "Found objects were: " . var_export($matched, true) + if (!is_array($matches)) { + throw PHPUnit_Util_InvalidArgumentHelper::factory( + 1, + 'array' ); } + + $constraint = new PHPUnit_Framework_Constraint_Not( + new SSListContains( + $matches + ) + ); + + static::assertThat( + $list, + $constraint, + $message + ); + } + + /** + * @deprecated 4.0.0:5.0.0 Use assertListNotContains() instead + * + * @param $matches + * @param $dataObjectSet + */ + public static function assertNotDOSContains($matches, $dataObjectSet) + { + Deprecation::notice('5.0', 'Use assertListNotContains() instead'); + return static::assertListNotContains($matches, $dataObjectSet); } /** @@ -689,58 +750,47 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * -------- * Check that *only* the entries Sam Minnee and Ingo Schommer exist in $members. Order doesn't * matter: - * $this->assertDOSEquals(array( - * array('FirstName' =>'Sam', 'Surname' => 'Minnee'), - * array('FirstName' => 'Ingo', 'Surname' => 'Schommer'), - * ), $members); + * $this->assertListEquals([ + * ['FirstName' =>'Sam', 'Surname' => 'Minnee'], + * ['FirstName' => 'Ingo', 'Surname' => 'Schommer'], + * ], $members); * * @param mixed $matches The patterns to match. Each pattern is a map of key-value pairs. You can * either pass a single pattern or an array of patterns. - * @param mixed $dataObjectSet The {@link SS_List} to test. + * @param mixed $list The {@link SS_List} to test. + * @param string $message + */ + public static function assertListEquals($matches, SS_List $list, $message = '') + { + if (!is_array($matches)) { + throw PHPUnit_Util_InvalidArgumentHelper::factory( + 1, + 'array' + ); + } + + static::assertThat( + $list, + new SSListContainsOnly( + $matches + ), + $message + ); + } + + /** + * @deprecated 4.0.0:5.0.0 Use assertListEquals() instead + * + * @param $matches + * @param SS_List $dataObjectSet */ public function assertDOSEquals($matches, $dataObjectSet) { - // Extract dataobjects - $extracted = array(); - if ($dataObjectSet) { - foreach ($dataObjectSet as $object) { - /** @var DataObject $object */ - $extracted[] = $object->toMap(); - } - } - - // Check all matches - if ($matches) { - foreach ($matches as $match) { - $matched = false; - foreach ($extracted as $i => $item) { - if ($this->dataObjectArrayMatch($item, $match)) { - // Remove it from $extracted so that we don't get duplicate mapping. - unset($extracted[$i]); - $matched = true; - break; - } - } - - // We couldn't find a match - assertion failed - $this->assertTrue( - $matched, - "Failed asserting that the SS_List contains an item matching " - . var_export($match, true) . "\n\nIn the following SS_List:\n" - . $this->DOSSummaryForMatch($dataObjectSet, $match) - ); - } - } - - // If we have leftovers than the DOS has extra data that shouldn't be there - $this->assertTrue( - (count($extracted) == 0), - // If we didn't break by this point then we couldn't find a match - "Failed asserting that the SS_List contained only the given items, the " - . "following items were left over:\n" . var_export($extracted, true) - ); + Deprecation::notice('5.0', 'Use assertListEquals() instead'); + return static::assertListEquals($matches, $dataObjectSet); } + /** * Assert that the every record in the given {@link SS_List} matches the given key-value * pairs. @@ -748,26 +798,40 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * Example * -------- * Check that every entry in $members has a Status of 'Active': - * $this->assertDOSAllMatch(array('Status' => 'Active'), $members); + * $this->assertListAllMatch(['Status' => 'Active'], $members); * * @param mixed $match The pattern to match. The pattern is a map of key-value pairs. - * @param mixed $dataObjectSet The {@link SS_List} to test. + * @param mixed $list The {@link SS_List} to test. + * @param string $message */ - public function assertDOSAllMatch($match, $dataObjectSet) + public static function assertListAllMatch($match, SS_List $list, $message = '') { - $extracted = array(); - foreach ($dataObjectSet as $object) { - /** @var DataObject $object */ - $extracted[] = $object->toMap(); - } - - foreach ($extracted as $i => $item) { - $this->assertTrue( - $this->dataObjectArrayMatch($item, $match), - "Failed asserting that the the following item matched " - . var_export($match, true) . ": " . var_export($item, true) + if (!is_array($match)) { + throw PHPUnit_Util_InvalidArgumentHelper::factory( + 1, + 'array' ); } + + static::assertThat( + $list, + new SSListContainsOnlyMatchingItems( + $match + ), + $message + ); + } + + /** + * @deprecated 4.0.0:5.0.0 Use assertListAllMatch() instead + * + * @param $match + * @param SS_List $dataObjectSet + */ + public function assertDOSAllMatch($match, SS_List $dataObjectSet) + { + Deprecation::notice('5.0', 'Use assertListAllMatch() instead'); + return static::assertListAllMatch($match, $dataObjectSet); } /** @@ -777,7 +841,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * @param string $sql * @return string The cleaned and normalised SQL string */ - protected function normaliseSQL($sql) + protected static function normaliseSQL($sql) { return trim(preg_replace('/\s+/m', ' ', $sql)); } @@ -793,7 +857,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * @param boolean $canonicalize * @param boolean $ignoreCase */ - public function assertSQLEquals( + public static function assertSQLEquals( $expectedSQL, $actualSQL, $message = '', @@ -803,10 +867,10 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly $ignoreCase = false ) { // Normalise SQL queries to remove patterns of repeating whitespace - $expectedSQL = $this->normaliseSQL($expectedSQL); - $actualSQL = $this->normaliseSQL($actualSQL); + $expectedSQL = static::normaliseSQL($expectedSQL); + $actualSQL = static::normaliseSQL($actualSQL); - $this->assertEquals($expectedSQL, $actualSQL, $message, $delta, $maxDepth, $canonicalize, $ignoreCase); + static::assertEquals($expectedSQL, $actualSQL, $message, $delta, $maxDepth, $canonicalize, $ignoreCase); } /** @@ -818,17 +882,17 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * @param boolean $ignoreCase * @param boolean $checkForObjectIdentity */ - public function assertSQLContains( + public static function assertSQLContains( $needleSQL, $haystackSQL, $message = '', $ignoreCase = false, $checkForObjectIdentity = true ) { - $needleSQL = $this->normaliseSQL($needleSQL); - $haystackSQL = $this->normaliseSQL($haystackSQL); + $needleSQL = static::normaliseSQL($needleSQL); + $haystackSQL = static::normaliseSQL($haystackSQL); - $this->assertContains($needleSQL, $haystackSQL, $message, $ignoreCase, $checkForObjectIdentity); + static::assertContains($needleSQL, $haystackSQL, $message, $ignoreCase, $checkForObjectIdentity); } /** @@ -840,50 +904,17 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * @param boolean $ignoreCase * @param boolean $checkForObjectIdentity */ - public function assertSQLNotContains( + public static function assertSQLNotContains( $needleSQL, $haystackSQL, $message = '', $ignoreCase = false, $checkForObjectIdentity = true ) { - $needleSQL = $this->normaliseSQL($needleSQL); - $haystackSQL = $this->normaliseSQL($haystackSQL); + $needleSQL = static::normaliseSQL($needleSQL); + $haystackSQL = static::normaliseSQL($haystackSQL); - $this->assertNotContains($needleSQL, $haystackSQL, $message, $ignoreCase, $checkForObjectIdentity); - } - - /** - * Helper function for the DOS matchers - * - * @param array $item - * @param array $match - * @return bool - */ - private function dataObjectArrayMatch($item, $match) - { - foreach ($match as $k => $v) { - if (!array_key_exists($k, $item) || $item[$k] != $v) { - return false; - } - } - return true; - } - - /** - * Helper function for the DOS matchers - * - * @param SS_List|array $dataObjectSet - * @param array $match - * @return string - */ - private function DOSSummaryForMatch($dataObjectSet, $match) - { - $extracted = array(); - foreach ($dataObjectSet as $item) { - $extracted[] = array_intersect_key($item->toMap(), $match); - } - return var_export($extracted, true); + static::assertNotContains($needleSQL, $haystackSQL, $message, $ignoreCase, $checkForObjectIdentity); } /** @@ -897,7 +928,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly // Health check if (InjectorLoader::inst()->countManifests()) { - throw new LogicException("SapphireTest::start() cannot be called within another application"); + throw new LogicException('SapphireTest::start() cannot be called within another application'); } static::set_is_running_test(true); @@ -1001,7 +1032,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly } $member->FirstName = $permCode; - $member->Surname = "User"; + $member->Surname = 'User'; $member->Email = "$permCode@example.org"; $member->write(); $group->Members()->add($member); @@ -1018,7 +1049,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly * @param string|array $permCode Either a permission, or list of permissions * @return int Member ID */ - public function logInWithPermission($permCode = "ADMIN") + public function logInWithPermission($permCode = 'ADMIN') { $member = $this->createMemberWithPermission($permCode); $this->logInAs($member); @@ -1091,7 +1122,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly return []; } - $fixtureFiles = (is_array($fixtureFile)) ? $fixtureFile : [$fixtureFile]; + $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : [$fixtureFile]; return array_map(function ($fixtureFilePath) { return $this->resolveFixturePath($fixtureFilePath); diff --git a/tests/php/Control/ControllerTest.php b/tests/php/Control/ControllerTest.php index 66bd13a89..daead0a31 100644 --- a/tests/php/Control/ControllerTest.php +++ b/tests/php/Control/ControllerTest.php @@ -292,9 +292,12 @@ class ControllerTest extends FunctionalTest Security::setCurrentUser(null); } + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid allowed_action '*' + */ public function testWildcardAllowedActions() { - $this->setExpectedException(InvalidArgumentException::class, "Invalid allowed_action '*'"); $this->get('AccessWildcardSecuredController'); } diff --git a/tests/php/Dev/SSListContainsOnlyMatchingItemsTest.php b/tests/php/Dev/SSListContainsOnlyMatchingItemsTest.php new file mode 100644 index 000000000..0bdf72821 --- /dev/null +++ b/tests/php/Dev/SSListContainsOnlyMatchingItemsTest.php @@ -0,0 +1,42 @@ + 1]); + + $this->assertTrue($constraint->evaluate($this->getListToMatch(), '', true)); + } + + /** + * @return ArrayList|Member[] + */ + private function getListToMatch() + { + $list = ArrayList::create(); + $list->push(Member::create(['FirstName' => 'Ingo', 'Surname' => 'Schommer', 'IsActive' => 1])); + $list->push(Member::create(['FirstName' => 'Sam', 'Surname' => 'Minnee', 'IsActive' => 1])); + + return $list; + } + + + public function testEvaluateListDoesNotMatchWrongMatches() + { + $constraint = new SSListContainsOnlyMatchingItems(['IsActive' => 1]); + + $failingList = $this->getListToMatch(); + $failingList->push(Member::create(['FirstName' => 'Foo', 'IsActive' => 0])); + + $this->assertFalse($constraint->evaluate($failingList, '', true)); + } +} diff --git a/tests/php/Dev/SSListContainsOnlyTest.php b/tests/php/Dev/SSListContainsOnlyTest.php new file mode 100644 index 000000000..e1943c629 --- /dev/null +++ b/tests/php/Dev/SSListContainsOnlyTest.php @@ -0,0 +1,87 @@ + 'Ingo'], + ['Surname' => 'Minnee'] + ] + ], + [ + [ + ['FirstName' => 'Sam', 'Surname' => 'Minnee'], //Sam Minee or Ingo + ['FirstName' => 'Ingo'] + ] + ], + ]; + } + + + public function provideInvalidMatchesForList() + { + return [ + [ + [['FirstName' => 'AnyoneNotInList']] + ], + [ + [['Surname' => 'NotInList']] + ], + [ + [['FirstName' => 'Ingo', 'Surname' => 'Minnee']] //more matches in List + ], + [ + [ + ['FirstName' => 'Ingo', 'Surname' => 'Minnee'], //mixed + ['FirstName' => 'NotInList'] + ] + ], + ]; + } + + /** + * @dataProvider provideMatchesForList() + * + * @param $matches + */ + public function testEvaluateListMatchesCorrectly($matches) + { + $constraint = new SSListContainsOnly($matches); + + $this->assertTrue($constraint->evaluate($this->getListToMatch(), '', true)); + } + + /** + * @return ArrayList|Member[] + */ + private function getListToMatch() + { + $list = ArrayList::create(); + $list->push(Member::create(['FirstName' => 'Ingo', 'Surname' => 'Schommer'])); + $list->push(Member::create(['FirstName' => 'Sam', 'Surname' => 'Minnee'])); + + return $list; + } + + /** + * @dataProvider provideInvalidMatchesForList() + * + * @param $matches + */ + public function testEvaluateListDoesNotMatchWrongMatches($matches) + { + $constraint = new SSListContainsOnly($matches); + + $this->assertFalse($constraint->evaluate($this->getListToMatch(), '', true)); + } +} diff --git a/tests/php/Dev/SSListContainsTest.php b/tests/php/Dev/SSListContainsTest.php new file mode 100644 index 000000000..6173e9c48 --- /dev/null +++ b/tests/php/Dev/SSListContainsTest.php @@ -0,0 +1,91 @@ + 'Ingo']] + ], + [ + [['Surname' => 'Minnee']] + ], + [ + [['FirstName' => 'Sam', 'Surname' => 'Minnee']] + ], + [ + [ + ['FirstName' => 'Sam', 'Surname' => 'Minnee'], //Sam Minee or Ingo + ['FirstName' => 'Ingo'] + ] + ], + ]; + } + + + public function provideInvalidMatchesForList() + { + return [ + [ + [['FirstName' => 'AnyoneNotInList']] + ], + [ + [['Surname' => 'NotInList']] + ], + [ + [['FirstName' => 'Ingo', 'Surname' => 'Minnee']] + ], + [ + [ + ['FirstName' => 'Ingo', 'Surname' => 'Minnee'], + ['FirstName' => 'NotInList'] + ] + ], + ]; + } + + /** + * @dataProvider provideMatchesForList() + * + * @param $matches + */ + public function testEvaluateListMatchesCorrectly($matches) + { + $constraint = new SSListContains($matches); + + $this->assertTrue($constraint->evaluate($this->getListToMatch(), '', true)); + } + + /** + * @dataProvider provideInvalidMatchesForList() + * + * @param $matches + */ + public function testEvaluateListDoesNotMatchWrongMatches($matches) + { + $constraint = new SSListContains($matches); + + $this->assertFalse($constraint->evaluate($this->getListToMatch(), '', true)); + } + + /** + * @return ArrayList|Member[] + */ + private function getListToMatch() + { + $list = ArrayList::create(); + $list->push(Member::create(['FirstName' => 'Ingo', 'Surname' => 'Schommer'])); + $list->push(Member::create(['FirstName' => 'Sam', 'Surname' => 'Minnee'])); + $list->push(Member::create(['FirstName' => 'Foo', 'Surname' => 'Bar'])); + + return $list; + } +} diff --git a/tests/php/Dev/SSListExporterTest.php b/tests/php/Dev/SSListExporterTest.php new file mode 100644 index 000000000..ecc47c0b9 --- /dev/null +++ b/tests/php/Dev/SSListExporterTest.php @@ -0,0 +1,85 @@ +exporter = new SSListExporter(); + } + + public function provideClassesForExport() + { + return [ + [ArrayList::class, false], + [DataObject::class, false], + [DataList::class, Member::class], + [ArrayData::class, false] + ]; + } + + /** + * @dataProvider provideClassesForExport() + * @param $className + * @param $constructorParam + */ + public function testExportStartsWithClassName($className, $constructorParam) + { + $obj = $constructorParam + ? $className::create($constructorParam) + : $className::create(); + + $export = ltrim($this->exporter->export($obj)); + + $this->assertStringStartsWith(get_class($obj), $export, 'Export should start with object\'s class name'); + } + + + /** + * @testdox toMap() returns DataObjects's data + */ + public function testToMapReturnsDataOfDataObjects() + { + $data = [ + 'Foo' => 'Bar', + 'Baz' => 'Boom', + 'One' => 'Two' + ]; + + $map = $this->exporter->toMap(DataObject::create($data)); + + $this->assertEquals($data, $map, 'Map should match data passed to DataObject'); + } + + /** + * @testdox toMap() returns ArrayData's data + */ + public function testToMapReturnsDataOfArrayData() + { + $data = [ + 'Foo' => 'Bar', + 'Baz' => 'Boom', + 'One' => 'Two' + ]; + + $map = $this->exporter->toMap(ArrayData::create($data)); + + $this->assertEquals($data, $map, 'Map should match data passed to ArrayData'); + } +} diff --git a/tests/php/Dev/SapphireTestTest.php b/tests/php/Dev/SapphireTestTest.php index 8e3d64a39..09043fa79 100644 --- a/tests/php/Dev/SapphireTestTest.php +++ b/tests/php/Dev/SapphireTestTest.php @@ -3,35 +3,44 @@ namespace SilverStripe\Dev\Tests; use SilverStripe\Dev\SapphireTest; +use SilverStripe\ORM\ArrayList; use SilverStripe\Security\Member; use SilverStripe\Security\Permission; class SapphireTestTest extends SapphireTest { - public function testResolveFixturePath() + + /** + * @return array + */ + public function provideResolveFixturePath() + { + return [ + [__DIR__ . '/CsvBulkLoaderTest.yml', './CsvBulkLoaderTest.yml'], + //same dir + [__DIR__ . '/CsvBulkLoaderTest.yml', 'CsvBulkLoaderTest.yml'], + // Filename only + [dirname(__DIR__) . '/ORM/DataObjectTest.yml', '../ORM/DataObjectTest.yml'], + // Parent path + [dirname(__DIR__) . '/ORM/DataObjectTest.yml', dirname(__DIR__) . '/ORM/DataObjectTest.yml'], + // Absolute path + ]; + } + + /** + * @dataProvider provideResolveFixturePath + */ + public function testResolveFixturePath($expected, $path) { - // Same directory $this->assertEquals( - __DIR__ . '/CsvBulkLoaderTest.yml', - $this->resolveFixturePath('./CsvBulkLoaderTest.yml') - ); - // Filename only - $this->assertEquals( - __DIR__ . '/CsvBulkLoaderTest.yml', - $this->resolveFixturePath('CsvBulkLoaderTest.yml') - ); - // Parent path - $this->assertEquals( - dirname(__DIR__) . '/ORM/DataObjectTest.yml', - $this->resolveFixturePath('../ORM/DataObjectTest.yml') - ); - // Absolute path - $this->assertEquals( - dirname(__DIR__) . '/ORM/DataObjectTest.yml', - $this->resolveFixturePath(dirname(__DIR__) .'/ORM/DataObjectTest.yml') + $expected, + $this->resolveFixturePath($path) ); } + /** + * @useDatabase + */ public function testActWithPermission() { $this->logOut(); @@ -45,10 +54,160 @@ class SapphireTestTest extends SapphireTest }); } + /** + * @useDatabase + */ public function testCreateMemberWithPermission() { - $this->assertCount(0, Member::get()->filter([ 'Email' => 'TESTPERM@example.org' ])); + $this->assertCount(0, Member::get()->filter(['Email' => 'TESTPERM@example.org'])); $this->createMemberWithPermission('TESTPERM'); - $this->assertCount(1, Member::get()->filter([ 'Email' => 'TESTPERM@example.org' ])); + $this->assertCount(1, Member::get()->filter(['Email' => 'TESTPERM@example.org'])); + } + + /** + * @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideAllMatchingList() + * + * @param $match + * @param $itemsForList + * @testdox Has assertion assertListAllMatch + */ + public function testAssertListAllMatch($match, $itemsForList) + { + $list = $this->generateArrayListFromItems($itemsForList); + + $this->assertListAllMatch($match, $list); + } + + /** + * @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideNotMatchingList() + * + * @param $match + * @param $itemsForList + * + * @testdox assertion assertListAllMatch fails when not all items are matching + * + * @expectedException \PHPUnit_Framework_ExpectationFailedException + */ + public function testAssertListAllMatchFailsWhenNotMatchingAllItems($match, $itemsForList) + { + $list = $this->generateArrayListFromItems($itemsForList); + + $this->assertListAllMatch($match, $list); + } + + /** + * @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideEqualListsWithEmptyList() + * + * @param $matches + * @param $itemsForList + * @testdox Has assertion assertListContains + */ + public function testAssertListContains($matches, $itemsForList) + { + $list = $this->generateArrayListFromItems($itemsForList); + $list->push(Member::create(['FirstName' => 'Foo', 'Surname' => 'Foo'])); + $list->push(Member::create(['FirstName' => 'Bar', 'Surname' => 'Bar'])); + $list->push(Member::create(['FirstName' => 'Baz', 'Surname' => 'Baz'])); + + $this->assertListContains($matches, $list); + } + + /** + * @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideNotContainingList + * @testdox assertion assertListEquals fails on non equal Lists + * + * @param $matches + * @param $itemsForList array + * + * @expectedException \PHPUnit_Framework_ExpectationFailedException + */ + public function testAssertListContainsFailsIfListDoesNotContainMatch($matches, $itemsForList) + { + $list = $this->generateArrayListFromItems($itemsForList); + $list->push(Member::create(['FirstName' => 'Foo', 'Surname' => 'Foo'])); + $list->push(Member::create(['FirstName' => 'Bar', 'Surname' => 'Bar'])); + $list->push(Member::create(['FirstName' => 'Baz', 'Surname' => 'Baz'])); + + $this->assertListContains($matches, $list); + } + + /** + * @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideNotContainingList + * + * @testdox Has assertion assertListNotContains + * + * @param $matches + * @param $itemsForList + */ + public function testAssertListNotContains($matches, $itemsForList) + { + $list = $this->generateArrayListFromItems($itemsForList); + + $this->assertListNotContains($matches, $list); + } + + /** + * @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideEqualLists + * + * @param $matches + * @param $itemsForList + * @testdox assertion assertListNotContains throws a exception when a matching item is found in the list + * + * @expectedException \PHPUnit_Framework_ExpectationFailedException + */ + public function testAssertListNotContainsFailsWhenListContainsAMatch($matches, $itemsForList) + { + $list = $this->generateArrayListFromItems($itemsForList); + $list->push(Member::create(['FirstName' => 'Foo', 'Surname' => 'Foo'])); + $list->push(Member::create(['FirstName' => 'Bar', 'Surname' => 'Bar'])); + $list->push(Member::create(['FirstName' => 'Baz', 'Surname' => 'Baz'])); + + $this->assertListNotContains($matches, $list); + } + + + /** + * @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideEqualListsWithEmptyList() + * @testdox Has assertion assertListEquals + * + * @param $matches + * @param $itemsForList + */ + public function testAssertListEquals($matches, $itemsForList) + { + $list = $this->generateArrayListFromItems($itemsForList); + + $this->assertListEquals($matches, $list); + } + + /** + * @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideNonEqualLists + * @testdox assertion assertListEquals fails on non equal Lists + * + * @param $matches + * @param $itemsForList + * + * @expectedException \PHPUnit_Framework_ExpectationFailedException + */ + public function testAssertListEqualsFailsOnNonEqualLists($matches, $itemsForList) + { + $list = $this->generateArrayListFromItems($itemsForList); + + $this->assertListEquals($matches, $list); + } + + /** + * generate SS_List as this is not possible in dataProvider + * + * @param $itemsForList array + * @return ArrayList + */ + private function generateArrayListFromItems($itemsForList) + { + $list = ArrayList::create(); + foreach ($itemsForList as $data) { + $list->push(Member::create($data)); + } + return $list; } } diff --git a/tests/php/Dev/SapphireTestTest/DataProvider.php b/tests/php/Dev/SapphireTestTest/DataProvider.php new file mode 100644 index 000000000..575808654 --- /dev/null +++ b/tests/php/Dev/SapphireTestTest/DataProvider.php @@ -0,0 +1,187 @@ + 'Ingo', 'Surname' => 'Schommer'] + ]; + + protected static $twoItemList = [ + ['FirstName' => 'Ingo', 'Surname' => 'Schommer'], + ['FirstName' => 'Sam', 'Surname' => 'Minnee'] + ]; + + /** + * @return array + */ + public static function provideEqualListsWithEmptyList() + { + return array_merge( + [ //empty list + [ + [], + [] + ] + ], + self::provideEqualLists() + ); + } + + /** + * @return array + */ + public static function provideEqualLists() + { + return [ + [ + [ //one param + ['FirstName' => 'Ingo'] + ], + self::$oneItemList + ], + [ + [ //two params + ['FirstName' => 'Ingo', 'Surname' => 'Schommer'] + ], + self::$oneItemList + ], + [ //only one param + [ + ['FirstName' => 'Ingo'], + ['FirstName' => 'Sam'] + ], + self::$twoItemList + ], + [ + [ //two params + ['FirstName' => 'Ingo', 'Surname' => 'Schommer'], + ['FirstName' => 'Sam', 'Surname' => 'Minnee'] + ], + self::$twoItemList + ], + [ + [ //mixed + ['FirstName' => 'Ingo', 'Surname' => 'Schommer'], + ['FirstName' => 'Sam'] + ], + self::$twoItemList + ], + ]; + } + + /** + * @return array + */ + public static function provideNonEqualLists() + { + + return [ + [ //empty list + [ + ['FirstName' => 'Ingo'] + ], + [] + ], + [ + [ //one item expected + ['FirstName' => 'Ingo'] + ] + , + self::$twoItemList + ], + [ //one item with wrong param + [ + ['FirstName' => 'IngoXX'], + ['FirstName' => 'Sam'] + ] + , + self::$twoItemList + ], + [ + [ //two params wrong + ['FirstName' => 'IngoXXX', 'Surname' => 'Schommer'], + ['FirstName' => 'Sam', 'Surname' => 'MinneeXXX'] + ], + self::$twoItemList + ], + [ + [ //mixed + ['FirstName' => 'Daniel', 'Surname' => 'Foo'], + ['FirstName' => 'Dan'] + ], + self::$twoItemList + ], + ]; + } + + /** + * @return array + */ + public static function provideNotContainingList() + { + return [ + [ //empty list + [ + ['FirstName' => 'Ingo'] + ], + [] + ], + [ + [ //one item expected + ['FirstName' => 'Sam'] + ] + , + self::$oneItemList + ], + [ + [ //two params wrong + ['FirstName' => 'IngoXXX', 'Surname' => 'Schommer'], + ['FirstName' => 'Sam', 'Surname' => 'MinneeXXX'] + ], + self::$twoItemList + ], + [ + [ //mixed + ['FirstName' => 'Daniel', 'Surname' => 'Foo'], + ['FirstName' => 'Dan'] + ], + self::$twoItemList + ], + ]; + } + + /** + * @return array + */ + public static function provideAllMatchingList() + { + $list = [ + ['FirstName' => 'Ingo', 'Surname' => 'Schommer', 'Locale' => 'en_US'], + ['FirstName' => 'Sam', 'Surname' => 'Minnee', 'Locale' => 'en_US'] + ]; + + return [ + [[], $list], //empty match + [['Locale' => 'en_US'], $list] //all items have this field set + ]; + } + + /** + * @return array + */ + public static function provideNotMatchingList() + { + $list = [ + ['FirstName' => 'Ingo', 'Surname' => 'Schommer', 'Locale' => 'en_US'], + ['FirstName' => 'Sam', 'Surname' => 'Minnee', 'Locale' => 'en_US'] + ]; + + return [ + [['FirstName' => 'Ingo'], $list] //not all items have this field set + ]; + } +} diff --git a/tests/php/Dev/ViewableDataContainsTest.php b/tests/php/Dev/ViewableDataContainsTest.php new file mode 100644 index 000000000..ad67051a8 --- /dev/null +++ b/tests/php/Dev/ViewableDataContainsTest.php @@ -0,0 +1,103 @@ + 'Ingo', + 'Surname' => 'Schommer' + ]; + + public function provideMatchesForList() + { + return [ + [ + ['FirstName' => 'Ingo'] + ], + [ + ['Surname' => 'Schommer'] + ], + [ + ['FirstName' => 'Ingo', 'Surname' => 'Schommer'] + ] + ]; + } + + + public function provideInvalidMatchesForList() + { + return [ + [ + ['FirstName' => 'AnyoneNotInList'] + ], + [ + ['Surname' => 'NotInList'] + ], + [ + ['FirstName' => 'Ingo', 'Surname' => 'Minnee'] + ] + ]; + } + + /** + * @dataProvider provideMatchesForList() + * + * @param $match + */ + public function testEvaluateMatchesCorrectlyArrayData($match) + { + $constraint = new ViewableDataContains($match); + + $item = ArrayData::create($this->test_data); + + $this->assertTrue($constraint->evaluate($item, '', true)); + } + + /** + * @dataProvider provideMatchesForList() + * + * @param $match + */ + public function testEvaluateMatchesCorrectlyDataObject($match) + { + $constraint = new ViewableDataContains($match); + + $item = Member::create($this->test_data); + + $this->assertTrue($constraint->evaluate($item, '', true)); + } + + /** + * @dataProvider provideInvalidMatchesForList() + * + * @param $matches + */ + public function testEvaluateDoesNotMatchWrongMatchInArrayData($match) + { + $constraint = new ViewableDataContains($match); + + $item = ArrayData::create($this->test_data); + + $this->assertFalse($constraint->evaluate($item, '', true)); + } + + /** + * @dataProvider provideInvalidMatchesForList() + * + * @param $matches + */ + public function testEvaluateDoesNotMatchWrongMatchInDataObject($match) + { + $constraint = new ViewableDataContains($match); + + $item = Member::create($this->test_data); + + $this->assertFalse($constraint->evaluate($item, '', true)); + } +} diff --git a/tests/php/Forms/GridField/GridFieldAddExistingAutocompleterTest.php b/tests/php/Forms/GridField/GridFieldAddExistingAutocompleterTest.php index 923bd00f4..b5a017845 100644 --- a/tests/php/Forms/GridField/GridFieldAddExistingAutocompleterTest.php +++ b/tests/php/Forms/GridField/GridFieldAddExistingAutocompleterTest.php @@ -119,7 +119,7 @@ class GridFieldAddExistingAutocompleterTest extends FunctionalTest $parser = new CSSContentParser($response->getBody()); $items = $parser->getBySelector('.grid-field .ss-gridfield-items .ss-gridfield-item'); $this->assertEquals(2, count($items)); - $this->assertDOSEquals( + $this->assertListEquals( array( array('ID' => (int)$items[0]['data-id']), array('ID' => (int)$items[1]['data-id']), diff --git a/tests/php/Forms/GridField/GridFieldDataColumnsTest.php b/tests/php/Forms/GridField/GridFieldDataColumnsTest.php index c8973ba9b..4fe4c94ec 100644 --- a/tests/php/Forms/GridField/GridFieldDataColumnsTest.php +++ b/tests/php/Forms/GridField/GridFieldDataColumnsTest.php @@ -41,10 +41,11 @@ class GridFieldDataColumnsTest extends SapphireTest /** * @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::setDisplayFields * @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::getDisplayFields + * + * @expectedException \InvalidArgumentException */ public function testGridFieldDisplayFieldsWithBadArguments() { - $this->setExpectedException('InvalidArgumentException'); $obj = new GridField('testfield', 'testfield', Member::get()); $columns = $obj->getConfig()->getComponentByType(GridFieldDataColumns::class); $columns->setDisplayFields(new stdClass()); diff --git a/tests/php/Forms/GridField/GridFieldDetailFormTest.php b/tests/php/Forms/GridField/GridFieldDetailFormTest.php index 7b430d429..81d425867 100644 --- a/tests/php/Forms/GridField/GridFieldDetailFormTest.php +++ b/tests/php/Forms/GridField/GridFieldDetailFormTest.php @@ -176,7 +176,7 @@ class GridFieldDetailFormTest extends FunctionalTest ->filter('Name', 'My Group') ->sort('Name') ->First(); - $this->assertDOSContains(array(array('Surname' => 'Baggins')), $group->People()); + $this->assertListContains(array(array('Surname' => 'Baggins')), $group->People()); } public function testEditFormWithManyMany() diff --git a/tests/php/Forms/GridField/GridFieldTest.php b/tests/php/Forms/GridField/GridFieldTest.php index df3717faf..ff946135f 100644 --- a/tests/php/Forms/GridField/GridFieldTest.php +++ b/tests/php/Forms/GridField/GridFieldTest.php @@ -2,6 +2,7 @@ namespace SilverStripe\Forms\Tests\GridField; +use Psr\Log\InvalidArgumentException; use SilverStripe\Dev\CSSContentParser; use SilverStripe\Dev\SapphireTest; use SilverStripe\Forms\FieldList; @@ -123,10 +124,11 @@ class GridFieldTest extends SapphireTest /** * @covers \SilverStripe\Forms\GridField\GridField::getModelClass + * + * @expectedException \LogicException */ public function testGridFieldModelClassThrowsException() { - $this->setExpectedException('LogicException'); $obj = new GridField('testfield', 'testfield', ArrayList::create()); $obj->getModelClass(); } @@ -247,10 +249,11 @@ class GridFieldTest extends SapphireTest /** * @skipUpgrade * @covers \SilverStripe\Forms\GridField\GridField::getColumnContent + * + * @expectedException \InvalidArgumentException */ public function testGetColumnContentBadArguments() { - $this->setExpectedException('InvalidArgumentException'); $list = new ArrayList( array( new Member(array("ID" => 1, "Email" => "test@example.org")) @@ -293,10 +296,11 @@ class GridFieldTest extends SapphireTest /** * @covers \SilverStripe\Forms\GridField\GridField::getColumnAttributes + * + * @expectedException \InvalidArgumentException */ public function testGetColumnAttributesBadArguments() { - $this->setExpectedException('InvalidArgumentException'); $list = new ArrayList( array( new Member(array("ID" => 1, "Email" => "test@example.org")) @@ -307,9 +311,11 @@ class GridFieldTest extends SapphireTest $obj->getColumnAttributes($list->first(), 'Non-existing'); } + /** + * @expectedException \LogicException + */ public function testGetColumnAttributesBadResponseFromComponent() { - $this->setExpectedException('LogicException'); $list = new ArrayList( array( new Member(array("ID" => 1, "Email" => "test@example.org")) @@ -338,10 +344,11 @@ class GridFieldTest extends SapphireTest /** * @covers \SilverStripe\Forms\GridField\GridField::getColumnMetadata + * + * @expectedException \LogicException */ public function testGetColumnMetadataBadResponseFromComponent() { - $this->setExpectedException('LogicException'); $list = new ArrayList( array( new Member(array("ID" => 1, "Email" => "test@example.org")) @@ -354,10 +361,11 @@ class GridFieldTest extends SapphireTest /** * @covers \SilverStripe\Forms\GridField\GridField::getColumnMetadata + * + * @expectedException \InvalidArgumentException */ public function testGetColumnMetadataBadArguments() { - $this->setExpectedException('InvalidArgumentException'); $list = ArrayList::create(); $config = GridFieldConfig::create()->addComponent(new Component); $obj = new GridField('testfield', 'testfield', $list, $config); @@ -366,10 +374,11 @@ class GridFieldTest extends SapphireTest /** * @covers \SilverStripe\Forms\GridField\GridField::handleAction + * + * @expectedException \InvalidArgumentException */ public function testHandleActionBadArgument() { - $this->setExpectedException('InvalidArgumentException'); $obj = new GridField('testfield', 'testfield'); $obj->handleAlterAction('prft', array(), array()); } @@ -506,6 +515,8 @@ class GridFieldTest extends SapphireTest /** * Test that circular dependencies throw an exception + * + * @expectedException \LogicException */ public function testGridFieldCustomFragmentsCircularDependencyThrowsException() { @@ -534,7 +545,6 @@ class GridFieldTest extends SapphireTest $field = new GridField('testfield', 'testfield', ArrayList::create(), $config); $form = new Form(null, 'testform', new FieldList(array($field)), new FieldList()); - $this->setExpectedException('LogicException'); $field->FieldHolder(); } diff --git a/tests/php/ORM/CascadeDeleteTest.php b/tests/php/ORM/CascadeDeleteTest.php index 303d74bb8..2d16411ad 100644 --- a/tests/php/ORM/CascadeDeleteTest.php +++ b/tests/php/ORM/CascadeDeleteTest.php @@ -22,14 +22,14 @@ class CascadeDeleteTest extends SapphireTest { /** @var CascadeDeleteTest\ChildObject $child1 */ $child1 = $this->objFromFixture(CascadeDeleteTest\ChildObject::class, 'child1'); - $this->assertDOSEquals( + $this->assertListEquals( [ [ 'Title' => 'Grandchild 1'], [ 'Title' => 'Grandchild 2'], ], $child1->findCascadeDeletes(true) ); - $this->assertDOSEquals( + $this->assertListEquals( [ [ 'Title' => 'Grandchild 1'], [ 'Title' => 'Grandchild 2'], @@ -39,7 +39,7 @@ class CascadeDeleteTest extends SapphireTest /** @var CascadeDeleteTest\ParentObject $parent1 */ $parent1 = $this->objFromFixture(CascadeDeleteTest\ParentObject::class, 'parent1'); - $this->assertDOSEquals( + $this->assertListEquals( [ [ 'Title' => 'Child 1'], [ 'Title' => 'Grandchild 1'], @@ -47,7 +47,7 @@ class CascadeDeleteTest extends SapphireTest ], $parent1->findCascadeDeletes(true) ); - $this->assertDOSEquals( + $this->assertListEquals( [ [ 'Title' => 'Child 1'], ], @@ -65,7 +65,7 @@ class CascadeDeleteTest extends SapphireTest $this->assertNotEmpty($this->objFromFixture(CascadeDeleteTest\ParentObject::class, 'parent1')); // Related objects never deleted - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'Related 1'], ['Title' => 'Related 2'], @@ -75,7 +75,7 @@ class CascadeDeleteTest extends SapphireTest ); // Ensure only remaining grandchild are those outside the relation - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'Grandchild 3'], ], @@ -90,13 +90,13 @@ class CascadeDeleteTest extends SapphireTest $parent1->delete(); // Ensure affected cascading tables have expected content - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'Child 2'], ], CascadeDeleteTest\ChildObject::get() ); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'Grandchild 3'], ], @@ -104,7 +104,7 @@ class CascadeDeleteTest extends SapphireTest ); // Related objects never deleted - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'Related 1'], ['Title' => 'Related 2'], @@ -116,7 +116,7 @@ class CascadeDeleteTest extends SapphireTest // Ensure that other parents which share cascade deleted objects have the correct result /** @var CascadeDeleteTest\ChildObject $child2 */ $child2 = $this->objFromFixture(CascadeDeleteTest\ChildObject::class, 'child2'); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'Grandchild 3'], ], diff --git a/tests/php/ORM/DBDateTest.php b/tests/php/ORM/DBDateTest.php index 18aa37a74..65cbc7bb9 100644 --- a/tests/php/ORM/DBDateTest.php +++ b/tests/php/ORM/DBDateTest.php @@ -92,21 +92,21 @@ class DBDateTest extends SapphireTest ); } + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid date: '3/16/2003'. Use y-MM-dd to prevent this error. + */ public function testMDYConversion() { - $this->setExpectedException( - \InvalidArgumentException::class, - "Invalid date: '3/16/2003'. Use " . DBDate::ISO_DATE . " to prevent this error." - ); DBField::create_field('Date', '3/16/2003'); } + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid date: '03-03-04'. Use y-MM-dd to prevent this error. + */ public function testY2kCorrection() { - $this->setExpectedException( - \InvalidArgumentException::class, - "Invalid date: '03-03-04'. Use " . DBDate::ISO_DATE . " to prevent this error." - ); DBField::create_field('Date', '03-03-04'); } diff --git a/tests/php/ORM/DataExtensionTest.php b/tests/php/ORM/DataExtensionTest.php index 2f935e7da..4111d6846 100644 --- a/tests/php/ORM/DataExtensionTest.php +++ b/tests/php/ORM/DataExtensionTest.php @@ -301,7 +301,8 @@ class DataExtensionTest extends SapphireTest $this->assertNull($extension->getOwner()); // Another clearOwner should error - $this->setExpectedException("BadMethodCallException", "clearOwner() called more than setOwner()"); + $this->expectExceptionMessage(\BadMethodCallException::class); + $this->expectExceptionMessage('clearOwner() called more than setOwner()'); $extension->clearOwner(); } } diff --git a/tests/php/ORM/DataListTest.php b/tests/php/ORM/DataListTest.php index 82057ae1f..cafaa8499 100755 --- a/tests/php/ORM/DataListTest.php +++ b/tests/php/ORM/DataListTest.php @@ -2,6 +2,7 @@ namespace SilverStripe\ORM\Tests; +use InvalidArgumentException; use SilverStripe\Core\Convert; use SilverStripe\Core\Injector\InjectorNotFoundException; use SilverStripe\ORM\DataList; @@ -88,9 +89,11 @@ class DataListTest extends SapphireTest $this->assertEquals(2, $newList->Count(), 'List should only contain two objects after subtraction'); } + /** + * @expectedException \InvalidArgumentException + */ public function testSubtractBadDataclassThrowsException() { - $this->setExpectedException('InvalidArgumentException'); $teamsComments = TeamComment::get(); $teams = Team::get(); $teamsComments->subtract($teams); @@ -579,12 +582,12 @@ class DataListTest extends SapphireTest $this->assertEquals('Phil', $list->last()->Name); } + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Fans is not a linear relation on model SilverStripe\ORM\Tests\DataObjectTest\Player + */ public function testSortInvalidParameters() { - $this->setExpectedException( - 'InvalidArgumentException', - 'Fans is not a linear relation on model '.Player::class - ); $list = Team::get(); $list->sort('Founder.Fans.Surname'); // Can't sort on has_many } @@ -747,23 +750,24 @@ class DataListTest extends SapphireTest $this->assertEquals('Bob', $list->first()->Name, 'First comment should be from Bob'); } + /** + * @expectedException \SilverStripe\Core\Injector\InjectorNotFoundException + * @expectedExceptionMessage Class DataListFilter.Bogus does not exist + */ public function testSimpleFilterWithNonExistingComparisator() { - $this->setExpectedException( - InjectorNotFoundException::class, - 'Class DataListFilter.Bogus does not exist' - ); $list = TeamComment::get(); $list->filter('Comment:Bogus', 'team comment'); } + /** + * Invalid modifiers are treated as failed filter construction + * + * @expectedException \SilverStripe\Core\Injector\InjectorNotFoundException + * @expectedExceptionMessage Class DataListFilter.invalidmodifier does not exist + */ public function testInvalidModifier() { - // Invalid modifiers are treated as failed filter construction - $this->setExpectedException( - InjectorNotFoundException::class, - 'Class DataListFilter.invalidmodifier does not exist' - ); $list = TeamComment::get(); $list->filter('Comment:invalidmodifier', 'team comment'); } @@ -870,21 +874,21 @@ class DataListTest extends SapphireTest // grand child can be found from parent $found = Bracket::get()->filter('Next.Next.Title', $final1->Title); - $this->assertDOSEquals( + $this->assertListEquals( [['Title' => $semifinal1->Title]], $found ); // grand child can be found from child $found = Bracket::get()->filter('Next.Title', $prefinal1->Title); - $this->assertDOSEquals( + $this->assertListEquals( [['Title' => $semifinal1->Title]], $found ); // child can be found from parent $found = Bracket::get()->filter('Next.Title', $final1->Title); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => $prefinal1->Title], ['Title' => $prefinal2->Title] @@ -895,7 +899,7 @@ class DataListTest extends SapphireTest // Complex filter, get brackets where the following bracket was won by team 1 // Note: Includes results from multiple levels $found = Bracket::get()->filter('Next.Winner.Title', $team2->Title); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => $prefinal1->Title], ['Title' => $prefinal2->Title], @@ -1058,12 +1062,12 @@ class DataListTest extends SapphireTest $this->assertEquals('007', $list->first()->ShirtNumber); } + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage MascotAnimal is not a relation on model SilverStripe\ORM\Tests\DataObjectTest\Team + */ public function testFilterOnInvalidRelation() { - $this->setExpectedException( - 'InvalidArgumentException', - "MascotAnimal is not a relation on model ".Team::class - ); // Filter on missing relation 'MascotAnimal' Team::get() ->filter('MascotAnimal.Name', 'Richard') @@ -1093,7 +1097,7 @@ class DataListTest extends SapphireTest // Filter by null email $nullEmails = $list->filter('Email', null); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Stephen', @@ -1107,7 +1111,7 @@ class DataListTest extends SapphireTest // Filter by non-null $nonNullEmails = $list->filter('Email:not', null); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Damian', @@ -1126,7 +1130,7 @@ class DataListTest extends SapphireTest // Filter by empty only $emptyOnly = $list->filter('Email', ''); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Hamish', @@ -1138,7 +1142,7 @@ class DataListTest extends SapphireTest // Non-empty only. This should include null values, since ExactMatchFilter works around // the caveat that != '' also excludes null values in ANSI SQL-92 behaviour. $nonEmptyOnly = $list->filter('Email:not', ''); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Damian', @@ -1160,7 +1164,7 @@ class DataListTest extends SapphireTest // Filter by many including null, empty string, and non-empty $items1 = $list->filter('Email', array(null, '', 'damian@thefans.com')); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Damian', @@ -1181,7 +1185,7 @@ class DataListTest extends SapphireTest // Filter exclusion of above list $items2 = $list->filter('Email:not', array(null, '', 'damian@thefans.com')); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Richard', @@ -1193,7 +1197,7 @@ class DataListTest extends SapphireTest // Filter by many including empty string and non-empty $items3 = $list->filter('Email', array('', 'damian@thefans.com')); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Damian', @@ -1209,7 +1213,7 @@ class DataListTest extends SapphireTest // Filter by many including empty string and non-empty // This also relies no the workaround for null comparison as in the $nonEmptyOnly test $items4 = $list->filter('Email:not', array('', 'damian@thefans.com')); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Richard', @@ -1233,7 +1237,7 @@ class DataListTest extends SapphireTest 'Email' => null ) ); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Richard', @@ -1251,7 +1255,7 @@ class DataListTest extends SapphireTest // Filter by null or empty values $items6 = $list->filter('Email', array(null, '')); - $this->assertDOSEquals( + $this->assertListEquals( array( array( 'Name' => 'Stephen', @@ -1528,13 +1532,12 @@ class DataListTest extends SapphireTest /** * Test exact match filter with empty array items + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Cannot filter "DataObjectTest_TeamComment"."Name" against an empty set */ public function testEmptyFilter() { - $this->setExpectedException( - "InvalidArgumentException", - 'Cannot filter "DataObjectTest_TeamComment"."Name" against an empty set' - ); $list = TeamComment::get(); $list->exclude('Name', array()); } diff --git a/tests/php/ORM/DataObjectDuplicationTest.php b/tests/php/ORM/DataObjectDuplicationTest.php index 1ec0f3635..b3186d53f 100644 --- a/tests/php/ORM/DataObjectDuplicationTest.php +++ b/tests/php/ORM/DataObjectDuplicationTest.php @@ -183,7 +183,7 @@ class DataObjectDuplicationTest extends SapphireTest // Duplcating $child should only duplicate grandchild $childDuplicate = $child->duplicate(true, 'many_many'); $this->assertEquals(0, $childDuplicate->Parents()->count()); - $this->assertDOSEquals( + $this->assertListEquals( [['Title' => 'GrandChild']], $childDuplicate->Children() ); @@ -191,18 +191,18 @@ class DataObjectDuplicationTest extends SapphireTest // Duplicate belongs_many_many only $belongsDuplicate = $child->duplicate(true, 'belongs_many_many'); $this->assertEquals(0, $belongsDuplicate->Children()->count()); - $this->assertDOSEquals( + $this->assertListEquals( [['Title' => 'Parent']], $belongsDuplicate->Parents() ); // Duplicate all $allDuplicate = $child->duplicate(true, true); - $this->assertDOSEquals( + $this->assertListEquals( [['Title' => 'Parent']], $allDuplicate->Parents() ); - $this->assertDOSEquals( + $this->assertListEquals( [['Title' => 'GrandChild']], $allDuplicate->Children() ); @@ -218,14 +218,14 @@ class DataObjectDuplicationTest extends SapphireTest $three = new DataObjectDuplicationTest\Class3(); $three->text = "Test Text 3"; $one->threes()->add($three); - $this->assertDOSEquals( + $this->assertListEquals( [['text' => 'Test Text 3']], $one->threes() ); // Test duplicate $dupe = $one->duplicate(false, true); $this->assertEquals('Test Text 1', $dupe->text); - $this->assertDOSEquals( + $this->assertListEquals( [['text' => 'Test Text 3']], $dupe->threes() ); diff --git a/tests/php/ORM/DataObjectSchemaTest.php b/tests/php/ORM/DataObjectSchemaTest.php index 483c1d9bf..fad7d8d27 100644 --- a/tests/php/ORM/DataObjectSchemaTest.php +++ b/tests/php/ORM/DataObjectSchemaTest.php @@ -2,6 +2,7 @@ namespace SilverStripe\ORM\Tests; +use InvalidArgumentException; use SilverStripe\Core\ClassInfo; use SilverStripe\Core\Config\Config; use SilverStripe\Dev\SapphireTest; @@ -237,7 +238,8 @@ class DataObjectSchemaTest extends SapphireTest $this->assertEquals(BaseClass::class, $schema->baseDataClass(GrandChildClass::class)); $this->assertEquals(BaseClass::class, $schema->baseDataClass(ucfirst(GrandChildClass::class))); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(InvalidArgumentException::class); + $schema->baseDataClass(DataObject::class); } diff --git a/tests/php/ORM/DataObjectTest.php b/tests/php/ORM/DataObjectTest.php index 7e231a09a..dfbccaab8 100644 --- a/tests/php/ORM/DataObjectTest.php +++ b/tests/php/ORM/DataObjectTest.php @@ -517,10 +517,10 @@ class DataObjectTest extends SapphireTest ]; // Test the IDs on the DataObjects are set correctly - $this->assertDOSEquals($team1Comments, $team1->Comments()); + $this->assertListEquals($team1Comments, $team1->Comments()); // Test that has_many can be infered from the has_one via getNonReciprocalComponent - $this->assertDOSEquals( + $this->assertListEquals( $team1Comments, $team1->inferReciprocalComponent(DataObjectTest\TeamComment::class, 'Team') ); @@ -1259,10 +1259,13 @@ class DataObjectTest extends SapphireTest $this->assertEquals('New and improved team 1', $reloadedTeam1->Title); } + + /** + * @expectedException \SilverStripe\ORM\ValidationException + */ public function testWritingInvalidDataObjectThrowsException() { $validatedObject = new DataObjectTest\ValidatedObject(); - $this->setExpectedException(ValidationException::class); $validatedObject->write(); } @@ -1339,7 +1342,9 @@ class DataObjectTest extends SapphireTest $this->assertFalse($schema->classHasTable(ViewableData::class)); // Invalid class - $this->setExpectedException(ReflectionException::class, 'Class ThisIsntADataObject does not exist'); + $this->expectException(ReflectionException::class); + $this->expectExceptionMessage('Class ThisIsntADataObject does not exist'); + $this->assertFalse($schema->classHasTable("ThisIsntADataObject")); } @@ -1405,24 +1410,30 @@ class DataObjectTest extends SapphireTest ); } + /** + * @expectedException \InvalidArgumentException + */ public function testValidateModelDefinitionsFailsWithArray() { Config::modify()->merge(DataObjectTest\Team::class, 'has_one', array('NotValid' => array('NoArraysAllowed'))); - $this->setExpectedException(InvalidArgumentException::class); DataObject::getSchema()->hasOneComponent(DataObjectTest\Team::class, 'NotValid'); } + /** + * @expectedException \InvalidArgumentException + */ public function testValidateModelDefinitionsFailsWithIntKey() { Config::modify()->set(DataObjectTest\Team::class, 'has_many', array(0 => DataObjectTest\Player::class)); - $this->setExpectedException(InvalidArgumentException::class); DataObject::getSchema()->hasManyComponent(DataObjectTest\Team::class, 0); } + /** + * @expectedException \InvalidArgumentException + */ public function testValidateModelDefinitionsFailsWithIntValue() { Config::modify()->merge(DataObjectTest\Team::class, 'many_many', array('Players' => 12)); - $this->setExpectedException(InvalidArgumentException::class); DataObject::getSchema()->manyManyComponent(DataObjectTest\Team::class, 'Players'); } @@ -1448,7 +1459,8 @@ class DataObjectTest extends SapphireTest $this->assertEquals($changedDO->ClassName, DataObjectTest\SubTeam::class); // Test invalid classes fail - $this->setExpectedException('InvalidArgumentException', "Controller is not a valid subclass of DataObject"); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Controller is not a valid subclass of DataObject'); /** * @skipUpgrade */ @@ -1493,7 +1505,7 @@ class DataObjectTest extends SapphireTest $this->assertEquals(0, $teamWithoutSponsor->Sponsors()->count()); // Test that belongs_many_many can be infered from with getNonReciprocalComponent - $this->assertDOSEquals( + $this->assertListEquals( [ ['Name' => 'Company corp'], ['Name' => 'Team co.'], @@ -1502,7 +1514,7 @@ class DataObjectTest extends SapphireTest ); // Test that many_many can be infered from getNonReciprocalComponent - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'Team 1'], ['Title' => 'Team 2'], @@ -1902,7 +1914,7 @@ class DataObjectTest extends SapphireTest // Test belongs_to can be infered via getNonReciprocalComponent // Note: Will be returned as has_many since the belongs_to is ignored. - $this->assertDOSEquals( + $this->assertListEquals( [['Name' => 'New Company']], $ceo->inferReciprocalComponent(DataObjectTest\Company::class, 'CEO') ); @@ -2078,14 +2090,17 @@ class DataObjectTest extends SapphireTest $this->assertInstanceOf(DataObjectTest\Player::class, DataObjectTest\Player::get()->first()); // You can't pass arguments to LSB syntax - use the DataList methods instead. - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(InvalidArgumentException::class); + DataObjectTest\Player::get(null, "\"ID\" = 1"); } + /** + * @expectedException \InvalidArgumentException + */ public function testBrokenLateStaticBindingStyle() { // If you call DataObject::get() you have to pass a first argument - $this->setExpectedException('InvalidArgumentException'); DataObject::get(); } diff --git a/tests/php/ORM/ManyManyThroughListTest.php b/tests/php/ORM/ManyManyThroughListTest.php index 5d9167e9f..13b39e184 100644 --- a/tests/php/ORM/ManyManyThroughListTest.php +++ b/tests/php/ORM/ManyManyThroughListTest.php @@ -33,7 +33,7 @@ class ManyManyThroughListTest extends SapphireTest { /** @var ManyManyThroughListTest\TestObject $parent */ $parent = $this->objFromFixture(ManyManyThroughListTest\TestObject::class, 'parent1'); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'item 1'], ['Title' => 'item 2'] @@ -68,7 +68,7 @@ class ManyManyThroughListTest extends SapphireTest // Test sorting on join table $items = $parent->Items()->sort('"ManyManyThroughListTest_JoinObject"."Sort"'); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'item 2'], ['Title' => 'item 1'], @@ -77,7 +77,7 @@ class ManyManyThroughListTest extends SapphireTest ); $items = $parent->Items()->sort('"ManyManyThroughListTest_JoinObject"."Sort" ASC'); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'item 1'], ['Title' => 'item 2'], @@ -85,7 +85,7 @@ class ManyManyThroughListTest extends SapphireTest $items ); $items = $parent->Items()->sort('"ManyManyThroughListTest_JoinObject"."Title" DESC'); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'item 2'], ['Title' => 'item 1'], @@ -122,7 +122,7 @@ class ManyManyThroughListTest extends SapphireTest { /** @var ManyManyThroughListTest\TestObject $parent */ $parent = $this->objFromFixture(ManyManyThroughListTest\TestObject::class, 'parent1'); - $this->assertDOSEquals( + $this->assertListEquals( [ ['Title' => 'item 1'], ['Title' => 'item 2'] @@ -131,7 +131,7 @@ class ManyManyThroughListTest extends SapphireTest ); $item1 = $parent->Items()->filter(['Title' => 'item 1'])->first(); $parent->Items()->remove($item1); - $this->assertDOSEquals( + $this->assertListEquals( [['Title' => 'item 2']], $parent->Items() ); @@ -139,6 +139,8 @@ class ManyManyThroughListTest extends SapphireTest /** * Test validation + * + * @expectedException \InvalidArgumentException */ public function testValidateModelValidatesJoinType() { @@ -149,7 +151,7 @@ class ManyManyThroughListTest extends SapphireTest ManyManyThroughListTest\JoinObject::class => 'Text' ] ); - $this->setExpectedException(InvalidArgumentException::class); + DataObject::getSchema()->manyManyComponent(ManyManyThroughListTest\TestObject::class, 'Items'); } diff --git a/tests/php/ORM/PaginatedListTest.php b/tests/php/ORM/PaginatedListTest.php index 305615c43..3dbdd7f72 100644 --- a/tests/php/ORM/PaginatedListTest.php +++ b/tests/php/ORM/PaginatedListTest.php @@ -103,30 +103,33 @@ class PaginatedListTest extends SapphireTest ); $list->setPageLength(2); - $this->assertDOSEquals( + $this->assertListEquals( array(array('Num' => 1), array('Num' => 2)), - $list->getIterator() + ArrayList::create($list->getIterator()->getInnerIterator()->getArrayCopy()) ); $list->setCurrentPage(2); - $this->assertDOSEquals( + $this->assertListEquals( array(array('Num' => 3), array('Num' => 4)), - $list->getIterator() + ArrayList::create($list->getIterator()->getInnerIterator()->getArrayCopy()) ); $list->setCurrentPage(3); - $this->assertDOSEquals( + $this->assertListEquals( array(array('Num' => 5)), - $list->getIterator() + ArrayList::create($list->getIterator()->getInnerIterator()->getArrayCopy()) ); $list->setCurrentPage(999); - $this->assertDOSEquals(array(), $list->getIterator()); + $this->assertListEquals( + array(), + ArrayList::create($list->getIterator()->getInnerIterator()->getArrayCopy()) + ); // Test disabled paging $list->setPageLength(0); $list->setCurrentPage(1); - $this->assertDOSEquals( + $this->assertListEquals( [ array('Num' => 1), array('Num' => 2), @@ -134,7 +137,7 @@ class PaginatedListTest extends SapphireTest array('Num' => 4), array('Num' => 5), ], - $list->getIterator() + ArrayList::create($list->getIterator()->getInnerIterator()->getArrayCopy()) ); // Test with dataobjectset @@ -168,21 +171,21 @@ class PaginatedListTest extends SapphireTest array('PageNum' => 4), array('PageNum' => 5), ); - $this->assertDOSEquals($expectAll, $list->Pages()); + $this->assertListEquals($expectAll, $list->Pages()); $expectLimited = array( array('PageNum' => 2), array('PageNum' => 3, 'CurrentBool' => true), array('PageNum' => 4), ); - $this->assertDOSEquals($expectLimited, $list->Pages(3)); + $this->assertListEquals($expectLimited, $list->Pages(3)); // Disable paging $list->setPageLength(0); $expectAll = array( array('PageNum' => 1, 'CurrentBool' => true), ); - $this->assertDOSEquals($expectAll, $list->Pages()); + $this->assertListEquals($expectAll, $list->Pages()); } public function testPaginationSummary() @@ -204,14 +207,14 @@ class PaginatedListTest extends SapphireTest array('PageNum' => null), array('PageNum' => 25), ); - $this->assertDOSEquals($expect, $list->PaginationSummary(4)); + $this->assertListEquals($expect, $list->PaginationSummary(4)); // Disable paging $list->setPageLength(0); $expect = array( array('PageNum' => 1, 'CurrentBool' => true) ); - $this->assertDOSEquals($expect, $list->PaginationSummary(4)); + $this->assertListEquals($expect, $list->PaginationSummary(4)); } public function testLimitItems() diff --git a/tests/php/ORM/UnsavedRelationListTest.php b/tests/php/ORM/UnsavedRelationListTest.php index cfa134980..e500a698a 100644 --- a/tests/php/ORM/UnsavedRelationListTest.php +++ b/tests/php/ORM/UnsavedRelationListTest.php @@ -55,7 +55,7 @@ class UnsavedRelationListTest extends SapphireTest $children = $object->Children(); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -68,7 +68,7 @@ class UnsavedRelationListTest extends SapphireTest $this->assertNotEquals($children, $object->Children()); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -89,7 +89,7 @@ class UnsavedRelationListTest extends SapphireTest $siblings = $object->Siblings(); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -102,7 +102,7 @@ class UnsavedRelationListTest extends SapphireTest $this->assertNotEquals($siblings, $object->Siblings()); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -123,7 +123,7 @@ class UnsavedRelationListTest extends SapphireTest $children = $object->Children(); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -136,7 +136,7 @@ class UnsavedRelationListTest extends SapphireTest $this->assertNotEquals($children, $object->Children()); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -157,7 +157,7 @@ class UnsavedRelationListTest extends SapphireTest $children = $object->RelatedObjects(); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -170,7 +170,7 @@ class UnsavedRelationListTest extends SapphireTest $this->assertNotEquals($children, $object->RelatedObjects()); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -191,7 +191,7 @@ class UnsavedRelationListTest extends SapphireTest $siblings = $object->Siblings(); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -204,7 +204,7 @@ class UnsavedRelationListTest extends SapphireTest $this->assertNotEquals($siblings, $object->Siblings()); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), @@ -225,7 +225,7 @@ class UnsavedRelationListTest extends SapphireTest $siblings = $object->Siblings(); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A', 'Number' => 1), array('Name' => 'B', 'Number' => 2), @@ -238,7 +238,7 @@ class UnsavedRelationListTest extends SapphireTest $this->assertNotEquals($siblings, $object->Siblings()); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A', 'Number' => 1), array('Name' => 'B', 'Number' => 2), @@ -292,7 +292,7 @@ class UnsavedRelationListTest extends SapphireTest $children = $object->Children(); - $this->assertDOSEquals( + $this->assertListEquals( array( array('Name' => 'A'), array('Name' => 'B'), diff --git a/tests/php/i18n/i18nTest.php b/tests/php/i18n/i18nTest.php index feb1b9960..fa16bab6e 100644 --- a/tests/php/i18n/i18nTest.php +++ b/tests/php/i18n/i18nTest.php @@ -296,7 +296,9 @@ class i18nTest extends SapphireTest ); // Passing in non-associative arrays for placeholders is now an error - $this->setExpectedException(InvalidArgumentException::class, 'Injection must be an associative array'); + $this->expectExceptionMessage(InvalidArgumentException::class); + $this->expectExceptionMessage('Injection must be an associative array'); + i18n::_t( $entity, // has {name} placeholders $default, diff --git a/tests/php/i18n/i18nTextCollectorTest.php b/tests/php/i18n/i18nTextCollectorTest.php index 6e0914a4a..1e8d68aa4 100644 --- a/tests/php/i18n/i18nTextCollectorTest.php +++ b/tests/php/i18n/i18nTextCollectorTest.php @@ -114,10 +114,9 @@ SS; // Test warning is raised on empty default $c->setWarnOnEmptyDefault(true); - $this->setExpectedException( - PHPUnit_Framework_Error_Notice::class, - 'Missing localisation default for key i18nTestModule.INJECTIONS_3' - ); + $this->expectException(PHPUnit_Framework_Error_Notice::class); + $this->expectExceptionMessage('Missing localisation default for key i18nTestModule.INJECTIONS_3'); + $c->collectFromTemplate($html, null, $mymodule); } @@ -190,10 +189,9 @@ SS; // Test warning is raised on empty default $c->setWarnOnEmptyDefault(true); - $this->setExpectedException( - PHPUnit_Framework_Error_Notice::class, - 'Missing localisation default for key Test.PRIOANDCOMMENT' - ); + $this->expectException(PHPUnit_Framework_Error_Notice::class); + $this->expectExceptionMessage('Missing localisation default for key Test.PRIOANDCOMMENT'); + $c->collectFromTemplate($html, 'Test', $mymodule); } @@ -419,10 +417,9 @@ PHP; $this->assertEquals($expectedArray, $collectedTranslatables); // Test warning is raised on empty default - $this->setExpectedException( - PHPUnit_Framework_Error_Notice::class, - 'Missing localisation default for key i18nTestModule.INJECTIONS4' - ); + $this->expectException(PHPUnit_Framework_Error_Notice::class); + $this->expectExceptionMessage('Missing localisation default for key i18nTestModule.INJECTIONS4'); + $php = <<"Cat", "greeting"=>"meow", "goodbye"=>"meow")); PHP;