Merge pull request #11361 from creative-commoners/pulls/6/phpunit11

DEP Use PHPUnit 11
This commit is contained in:
Guy Sartorelli 2024-09-18 15:29:43 +12:00 committed by GitHub
commit 7793664efe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
135 changed files with 1364 additions and 1649 deletions

View File

@ -32,10 +32,10 @@
"m1/env": "^2.2.0", "m1/env": "^2.2.0",
"masterminds/html5": "^2.7.6", "masterminds/html5": "^2.7.6",
"monolog/monolog": "^3.2.0", "monolog/monolog": "^3.2.0",
"nikic/php-parser": "^4.15.0", "nikic/php-parser": "^5.1.0",
"psr/container": "^1.1 || ^2.0", "psr/container": "^1.1 || ^2.0",
"psr/http-message": "^1", "psr/http-message": "^1",
"sebastian/diff": "^4.0", "sebastian/diff": "^6.0",
"silverstripe/config": "^3", "silverstripe/config": "^3",
"silverstripe/assets": "^3", "silverstripe/assets": "^3",
"silverstripe/vendor-plugin": "^2", "silverstripe/vendor-plugin": "^2",
@ -63,7 +63,7 @@
}, },
"require-dev": { "require-dev": {
"composer/semver": "^3.4", "composer/semver": "^3.4",
"phpunit/phpunit": "^9.6", "phpunit/phpunit": "^11.3",
"silverstripe/versioned": "^3", "silverstripe/versioned": "^3",
"squizlabs/php_codesniffer": "^3.7", "squizlabs/php_codesniffer": "^3.7",
"silverstripe/standards": "^1", "silverstripe/standards": "^1",

View File

@ -302,7 +302,7 @@ class ClassManifest
public function getParser() public function getParser()
{ {
if (!$this->parser) { if (!$this->parser) {
$this->parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7); $this->parser = (new ParserFactory)->createForHostVersion();
} }
return $this->parser; return $this->parser;

View File

@ -24,7 +24,7 @@ class ClassManifestErrorHandler implements ErrorHandler
$this->pathname = $pathname; $this->pathname = $pathname;
} }
public function handleError(Error $error) public function handleError(Error $error): void
{ {
$newMessage = sprintf('%s in %s', $error->getRawMessage(), $this->pathname); $newMessage = sprintf('%s in %s', $error->getRawMessage(), $this->pathname);
$error->setRawMessage($newMessage); $error->setRawMessage($newMessage);

View File

@ -4,7 +4,6 @@ namespace SilverStripe\Dev\Constraint;
use PHPUnit\Framework\Constraint\Constraint; use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\ExpectationFailedException;
use SilverStripe\Dev\SSListExporter;
use SilverStripe\Dev\TestOnly; use SilverStripe\Dev\TestOnly;
use SilverStripe\ORM\SS_List; use SilverStripe\ORM\SS_List;
use SilverStripe\View\ViewableData; use SilverStripe\View\ViewableData;
@ -20,8 +19,6 @@ class SSListContains extends Constraint implements TestOnly
*/ */
protected $matches = []; protected $matches = [];
protected SSListExporter $exporter;
/** /**
* Check if the list has left over items that don't match * Check if the list has left over items that don't match
* *
@ -31,8 +28,6 @@ class SSListContains extends Constraint implements TestOnly
public function __construct(array $matches) public function __construct(array $matches)
{ {
$this->exporter = new SSListExporter();
$this->matches = $matches; $this->matches = $matches;
} }

View File

@ -4,7 +4,6 @@ namespace SilverStripe\Dev\Constraint;
use PHPUnit\Framework\Constraint\Constraint; use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\ExpectationFailedException;
use SilverStripe\Dev\SSListExporter;
use SilverStripe\Dev\TestOnly; use SilverStripe\Dev\TestOnly;
use SilverStripe\ORM\SS_List; use SilverStripe\ORM\SS_List;
@ -19,8 +18,6 @@ class SSListContainsOnlyMatchingItems extends Constraint implements TestOnly
*/ */
private $match; private $match;
protected SSListExporter $exporter;
/** /**
* @var ViewableDataContains * @var ViewableDataContains
*/ */
@ -28,8 +25,6 @@ class SSListContainsOnlyMatchingItems extends Constraint implements TestOnly
public function __construct($match) public function __construct($match)
{ {
$this->exporter = new SSListExporter();
$this->constraint = new ViewableDataContains($match); $this->constraint = new ViewableDataContains($match);
$this->match = $match; $this->match = $match;
} }

View File

@ -0,0 +1,9 @@
<?php
namespace SilverStripe\Dev\Exceptions;
use Exception;
class ExpectedErrorException extends Exception
{
}

View File

@ -0,0 +1,9 @@
<?php
namespace SilverStripe\Dev\Exceptions;
use Exception;
class ExpectedNoticeException extends Exception
{
}

View File

@ -0,0 +1,9 @@
<?php
namespace SilverStripe\Dev\Exceptions;
use Exception;
class ExpectedWarningException extends Exception
{
}

View File

@ -134,7 +134,6 @@ abstract class FunctionalTest extends SapphireTest implements TestOnly
/** /**
* Submit a get request * Submit a get request
* @uses Director::test()
* *
* @param string $url * @param string $url
* @param Session $session * @param Session $session
@ -155,7 +154,6 @@ abstract class FunctionalTest extends SapphireTest implements TestOnly
/** /**
* Submit a post request * Submit a post request
* *
* @uses Director::test()
* @param string $url * @param string $url
* @param array $data * @param array $data
* @param array $headers * @param array $headers

View File

@ -1,99 +0,0 @@
<?php
namespace SilverStripe\Dev;
use SebastianBergmann\Exporter\Exporter;
use SebastianBergmann\RecursionContext\Context;
use SilverStripe\ORM\SS_List;
use SilverStripe\View\ViewableData;
use SilverStripe\Dev\Deprecation;
if (!class_exists(Exporter::class)) {
return;
}
/**
* A custom exporter for prettier formatting of SilverStripe specific Objects in PHPUnit's failing test messages.
*
* @deprecated 5.4.0 Will be removed without equivalent functionality to replace it
*/
class SSListExporter extends Exporter implements TestOnly
{
public function __construct()
{
Deprecation::withNoReplacement(function () {
Deprecation::notice(
'5.4.0',
'Will be removed without equivalent functionality to replace it',
Deprecation::SCOPE_CLASS
);
});
}
/**
* @param mixed $value
* @param int $indentation
* @param null|Context $processed
* @return string
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
protected function recursiveExport(&$value, $indentation, $processed = null)
{
if (!$processed) {
$processed = new Context;
}
$whitespace = str_repeat(' ', 4 * $indentation);
if ($value instanceof SS_List) {
$className = get_class($value);
if (($key = $processed->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()
: [];
}
}

View File

@ -3,11 +3,13 @@
namespace SilverStripe\Dev; namespace SilverStripe\Dev;
use Exception; use Exception;
use Facebook\WebDriver\Exception\UnknownErrorException;
use InvalidArgumentException; use InvalidArgumentException;
use LogicException; use LogicException;
use PHPUnit\Framework\Constraint\LogicalNot; use PHPUnit\Framework\Constraint\LogicalNot;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Exception as PHPUnitFrameworkException; use PHPUnit\Framework\Exception as PHPUnitFrameworkException;
use PHPUnit\Framework\TestSize\Unknown;
use PHPUnit\Util\Test as TestUtil; use PHPUnit\Util\Test as TestUtil;
use SilverStripe\CMS\Controllers\RootURLController; use SilverStripe\CMS\Controllers\RootURLController;
use SilverStripe\Control\CLIRequestBuilder; use SilverStripe\Control\CLIRequestBuilder;
@ -41,6 +43,12 @@ use SilverStripe\View\SSViewer;
use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mailer\Transport\NullTransport; use Symfony\Component\Mailer\Transport\NullTransport;
use ReflectionMethod;
use ReflectionClass;
use SilverStripe\Dev\Exceptions\ExpectedErrorException;
use SilverStripe\Dev\Exceptions\ExpectedNoticeException;
use SilverStripe\Dev\Exceptions\ExpectedWarningException;
use SilverStripe\Dev\Exceptions\UnexpectedErrorException;
/** /**
* Test case class for the Silverstripe framework. * Test case class for the Silverstripe framework.
@ -334,6 +342,37 @@ abstract class SapphireTest extends TestCase implements TestOnly
Email::config()->remove('bcc_all_emails_to'); Email::config()->remove('bcc_all_emails_to');
} }
/**
* @param callable|null $oldHandler
*/
private $oldErrorHandler = null;
/**
* Setup a custom error handler to throw exceptions on errors
*/
protected function enableErrorHandler()
{
// If changing this method, ensure that the corresponding table on 00_Unit_Testing.md
// in silverstripe/deveoper-docs is also updated
$this->oldErrorHandler = set_error_handler(
function (int $errno, string $errstr, string $errfile, int $errline) {
// E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING
// cannot be handled in set_error_handler()
// https://www.php.net/manual/en/function.set-error-handler.php
// https://www.php.net/manual/en/errorfunc.constants.php
if (in_array($errno, [E_USER_ERROR, E_RECOVERABLE_ERROR])) {
throw new ExpectedErrorException($errstr);
} elseif (in_array($errno, [E_NOTICE, E_USER_NOTICE])) {
throw new ExpectedNoticeException($errstr);
} elseif (in_array($errno, [E_WARNING, E_USER_WARNING])) {
throw new ExpectedWarningException($errstr);
}
// Use the standard PHP error handler
return false;
}
);
}
/** /**
* Helper method to determine if the current test should enable a test database * Helper method to determine if the current test should enable a test database
* *
@ -563,6 +602,12 @@ abstract class SapphireTest extends TestCase implements TestOnly
// Call state helpers // Call state helpers
static::$state->tearDown($this); static::$state->tearDown($this);
// Reset custom error handler
if ($this->oldErrorHandler) {
restore_error_handler();
$this->oldErrorHandler = null;
}
} }
/** /**
@ -1212,16 +1257,30 @@ abstract class SapphireTest extends TestCase implements TestOnly
} }
/** /**
* Returns the annotations for this test. * Returns the annotations for this test
*
* @return array
*/ */
public function getAnnotations(): array public function getAnnotations(): array
{ {
return TestUtil::parseTestMethodAnnotations( $class = get_class($this);
get_class($this), $method = $this->name();
$this->getName(false) $ret = [];
); foreach (['method', 'class'] as $what) {
if ($what === 'method') {
$reflection = new ReflectionMethod($class, $method);
} else {
$reflection = new ReflectionClass($class);
}
preg_match_all('#@(.*?)\n#s', $reflection->getDocComment(), $annotations);
$ret[$what] = [];
foreach ($annotations[1] as $annotation) {
$parts = explode(' ', $annotation);
$key = array_shift($parts);
$value = implode(' ', $parts);
$ret[$what][$key] ??= [];
$ret[$what][$key][] = $value;
}
}
return $ret;
} }
/** /**

View File

@ -2,10 +2,10 @@
namespace SilverStripe\ORM\FieldType; namespace SilverStripe\ORM\FieldType;
use RuntimeException;
use SilverStripe\Core\ClassInfo; use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use RuntimeException;
use SilverStripe\View\ViewableData; use SilverStripe\View\ViewableData;
trait DBClassNameTrait trait DBClassNameTrait

View File

@ -7,6 +7,7 @@ use Masterminds\HTML5\Elements;
use SebastianBergmann\Diff\Differ; use SebastianBergmann\Diff\Differ;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder;
/** /**
* Class representing a 'diff' between two sequences of HTML strings. * Class representing a 'diff' between two sequences of HTML strings.
@ -285,7 +286,7 @@ class HtmlDiff
private static function getDiffer(): Differ private static function getDiffer(): Differ
{ {
if (!HtmlDiff::$differ) { if (!HtmlDiff::$differ) {
HtmlDiff::$differ = new Differ(); HtmlDiff::$differ = new Differ(new DiffOnlyOutputBuilder());
} }
return HtmlDiff::$differ; return HtmlDiff::$differ;
} }

View File

@ -18,6 +18,7 @@ use SilverStripe\Control\Tests\RequestHandlingTest\HTTPMethodTestController;
use SilverStripe\Dev\FunctionalTest; use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use PHPUnit\Framework\Attributes\DataProvider;
class ControllerTest extends FunctionalTest class ControllerTest extends FunctionalTest
{ {
@ -462,7 +463,7 @@ class ControllerTest extends FunctionalTest
); );
} }
public function provideNormaliseTrailingSlash(): array public static function provideNormaliseTrailingSlash(): array
{ {
// note 93.184.215.14 is the IP address for example.com // note 93.184.215.14 is the IP address for example.com
return [ return [
@ -670,9 +671,7 @@ class ControllerTest extends FunctionalTest
]; ];
} }
/** #[DataProvider('provideNormaliseTrailingSlash')]
* @dataProvider provideNormaliseTrailingSlash
*/
public function testNormaliseTrailingSlash(string $path, string $withSlash, string $withoutSlash): void public function testNormaliseTrailingSlash(string $path, string $withSlash, string $withoutSlash): void
{ {
$absBaseUrlNoSlash = rtrim(Director::absoluteBaseURL(), '/'); $absBaseUrlNoSlash = rtrim(Director::absoluteBaseURL(), '/');
@ -704,9 +703,6 @@ class ControllerTest extends FunctionalTest
$this->assertEquals('HasAction/allowed-action/', $controller->Link('allowed-action')); $this->assertEquals('HasAction/allowed-action/', $controller->Link('allowed-action'));
} }
/**
* @covers \SilverStripe\Control\Controller::hasAction
*/
public function testHasAction() public function testHasAction()
{ {
$controller = new HasAction(); $controller = new HasAction();

View File

@ -17,6 +17,7 @@ use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Environment; use SilverStripe\Core\Environment;
use SilverStripe\Core\Kernel; use SilverStripe\Core\Kernel;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use PHPUnit\Framework\Attributes\DataProvider;
class DirectorTest extends SapphireTest class DirectorTest extends SapphireTest
{ {
@ -40,7 +41,6 @@ class DirectorTest extends SapphireTest
->setForceSSLPatterns([]) ->setForceSSLPatterns([])
->setForceWWW(null) ->setForceWWW(null)
->setEnabledEnvs(true); ->setEnabledEnvs(true);
$this->expectedRedirect = null;
} }
protected function tearDown(): void protected function tearDown(): void
@ -214,14 +214,14 @@ class DirectorTest extends SapphireTest
/** /**
* Tests that {@link Director::is_absolute()} works under different environment types * Tests that {@link Director::is_absolute()} works under different environment types
* @dataProvider provideAbsolutePaths
*/ */
#[DataProvider('provideAbsolutePaths')]
public function testIsAbsolute($path, $result) public function testIsAbsolute($path, $result)
{ {
$this->assertEquals($result, Director::is_absolute($path)); $this->assertEquals($result, Director::is_absolute($path));
} }
public function provideAbsolutePaths() public static function provideAbsolutePaths()
{ {
return [ return [
['C:/something', true], ['C:/something', true],
@ -294,7 +294,7 @@ class DirectorTest extends SapphireTest
/** /**
* @return array * @return array
*/ */
public function providerMakeRelative() public static function providerMakeRelative()
{ {
return [ return [
// Resilience to slash position // Resilience to slash position
@ -409,11 +409,11 @@ class DirectorTest extends SapphireTest
} }
/** /**
* @dataProvider providerMakeRelative
* @param string $baseURL Site base URL * @param string $baseURL Site base URL
* @param string $requestURL Request URL * @param string $requestURL Request URL
* @param string $relativeURL Expected relative URL * @param string $relativeURL Expected relative URL
*/ */
#[DataProvider('providerMakeRelative')]
public function testMakeRelative($baseURL, $requestURL, $relativeURL) public function testMakeRelative($baseURL, $requestURL, $relativeURL)
{ {
Director::config()->set('alternate_base_url', $baseURL); Director::config()->set('alternate_base_url', $baseURL);
@ -543,7 +543,7 @@ class DirectorTest extends SapphireTest
); );
} }
public function providerTestTestRequestCarriesGlobals() public static function providerTestTestRequestCarriesGlobals()
{ {
$tests = []; $tests = [];
$fixture = ['somekey' => 'sometestvalue']; $fixture = ['somekey' => 'sometestvalue'];
@ -558,11 +558,11 @@ class DirectorTest extends SapphireTest
} }
/** /**
* @dataProvider providerTestTestRequestCarriesGlobals
* @param $url * @param $url
* @param $fixture * @param $fixture
* @param $method * @param $method
*/ */
#[DataProvider('providerTestTestRequestCarriesGlobals')]
public function testTestRequestCarriesGlobals($url, $fixture, $method) public function testTestRequestCarriesGlobals($url, $fixture, $method)
{ {
$getresponse = Director::test( $getresponse = Director::test(
@ -602,11 +602,12 @@ class DirectorTest extends SapphireTest
public function testForceWWW() public function testForceWWW()
{ {
$this->expectExceptionRedirect('http://www.mysite.com:9090/some-url'); $this->withExpectExceptionRedirect('http://www.mysite.com:9090/some-url', function () {
Director::mockRequest(function ($request) { Director::mockRequest(function ($request) {
Injector::inst()->registerService($request, HTTPRequest::class); Injector::inst()->registerService($request, HTTPRequest::class);
Director::forceWWW(); Director::forceWWW();
}, 'http://mysite.com:9090/some-url'); }, 'http://mysite.com:9090/some-url');
});
} }
public function testPromisedForceWWW() public function testPromisedForceWWW()
@ -632,11 +633,12 @@ class DirectorTest extends SapphireTest
public function testForceSSLProtectsEntireSite() public function testForceSSLProtectsEntireSite()
{ {
$this->expectExceptionRedirect('https://www.mysite.com:9090/some-url'); $this->withExpectExceptionRedirect('https://www.mysite.com:9090/some-url', function () {
Director::mockRequest(function ($request) { Director::mockRequest(function ($request) {
Injector::inst()->registerService($request, HTTPRequest::class); Injector::inst()->registerService($request, HTTPRequest::class);
Director::forceSSL(); Director::forceSSL();
}, 'http://www.mysite.com:9090/some-url'); }, 'http://www.mysite.com:9090/some-url');
});
} }
public function testPromisedForceSSL() public function testPromisedForceSSL()
@ -664,21 +666,23 @@ class DirectorTest extends SapphireTest
public function testForceSSLOnTopLevelPagePattern() public function testForceSSLOnTopLevelPagePattern()
{ {
// Expect admin to trigger redirect // Expect admin to trigger redirect
$this->expectExceptionRedirect('https://www.mysite.com:9090/admin'); $this->withExpectExceptionRedirect('https://www.mysite.com:9090/admin', function () {
Director::mockRequest(function (HTTPRequest $request) { Director::mockRequest(function (HTTPRequest $request) {
Injector::inst()->registerService($request, HTTPRequest::class); Injector::inst()->registerService($request, HTTPRequest::class);
Director::forceSSL(['/^admin/']); Director::forceSSL(['/^admin/']);
}, 'http://www.mysite.com:9090/admin'); }, 'http://www.mysite.com:9090/admin');
});
} }
public function testForceSSLOnSubPagesPattern() public function testForceSSLOnSubPagesPattern()
{ {
// Expect to redirect to security login page // Expect to redirect to security login page
$this->expectExceptionRedirect('https://www.mysite.com:9090/Security/login'); $this->withExpectExceptionRedirect('https://www.mysite.com:9090/Security/login', function () {
Director::mockRequest(function (HTTPRequest $request) { Director::mockRequest(function (HTTPRequest $request) {
Injector::inst()->registerService($request, HTTPRequest::class); Injector::inst()->registerService($request, HTTPRequest::class);
Director::forceSSL(['/^Security/']); Director::forceSSL(['/^Security/']);
}, 'http://www.mysite.com:9090/Security/login'); }, 'http://www.mysite.com:9090/Security/login');
});
} }
public function testForceSSLWithPatternDoesNotMatchOtherPages() public function testForceSSLWithPatternDoesNotMatchOtherPages()
@ -701,21 +705,23 @@ class DirectorTest extends SapphireTest
public function testForceSSLAlternateDomain() public function testForceSSLAlternateDomain()
{ {
// Ensure that forceSSL throws the appropriate exception // Ensure that forceSSL throws the appropriate exception
$this->expectExceptionRedirect('https://secure.mysite.com/admin'); $this->withExpectExceptionRedirect('https://secure.mysite.com/admin', function () {
Director::mockRequest(function (HTTPRequest $request) { Director::mockRequest(function (HTTPRequest $request) {
Injector::inst()->registerService($request, HTTPRequest::class); Injector::inst()->registerService($request, HTTPRequest::class);
return Director::forceSSL(['/^admin/'], 'secure.mysite.com'); return Director::forceSSL(['/^admin/'], 'secure.mysite.com');
}, 'http://www.mysite.com:9090/admin'); }, 'http://www.mysite.com:9090/admin');
});
} }
public function testForceSSLAlternateDomainWithPort() public function testForceSSLAlternateDomainWithPort()
{ {
// Ensure that forceSSL throws the appropriate exception // Ensure that forceSSL throws the appropriate exception
$this->expectExceptionRedirect('https://secure.mysite.com:81/admin'); $this->withExpectExceptionRedirect('https://secure.mysite.com:81/admin', function () {
Director::mockRequest(function (HTTPRequest $request) { Director::mockRequest(function (HTTPRequest $request) {
Injector::inst()->registerService($request, HTTPRequest::class); Injector::inst()->registerService($request, HTTPRequest::class);
return Director::forceSSL(['/^admin/'], 'secure.mysite.com:81'); return Director::forceSSL(['/^admin/'], 'secure.mysite.com:81');
}, 'http://www.mysite.com:9090/admin'); }, 'http://www.mysite.com:9090/admin');
});
} }
/** /**
@ -744,40 +750,19 @@ class DirectorTest extends SapphireTest
$this->assertEquals(301, $response->getStatusCode()); $this->assertEquals(301, $response->getStatusCode());
} }
/**
* Set url to redirect to
*
* @var string
*/
protected $expectedRedirect = null;
/** /**
* Expects this test to throw a HTTPResponse_Exception with the given redirect * Expects this test to throw a HTTPResponse_Exception with the given redirect
*
* @param string $url
*/ */
protected function expectExceptionRedirect($url) protected function withExpectExceptionRedirect(string $expectedRedirect, callable $callback)
{
$this->expectedRedirect = $url;
}
protected function runTest()
{ {
try { try {
$result = parent::runTest(); $callback();
if ($this->expectedRedirect) { $this->fail("Expected to redirect to $expectedRedirect but no redirect found");
$this->fail("Expected to redirect to {$this->expectedRedirect} but no redirect found");
}
return $result;
} catch (HTTPResponse_Exception $exception) { } catch (HTTPResponse_Exception $exception) {
// Check URL // Check URL
if ($this->expectedRedirect) { $url = $exception->getResponse()->getHeader('Location');
$url = $exception->getResponse()->getHeader('Location'); $this->assertEquals($expectedRedirect, $url, "Expected to redirect to $expectedRedirect");
$this->assertEquals($this->expectedRedirect, $url, "Expected to redirect to {$this->expectedRedirect}"); return null;
return null;
} else {
throw $exception;
}
} }
} }

View File

@ -16,6 +16,7 @@ use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Part\DataPart; use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\AbstractPart; use Symfony\Component\Mime\Part\AbstractPart;
use PHPUnit\Framework\Attributes\DataProvider;
class EmailTest extends SapphireTest class EmailTest extends SapphireTest
{ {
@ -66,30 +67,26 @@ class EmailTest extends SapphireTest
return $attachments[0]; return $attachments[0];
} }
/** #[DataProvider('provideValidEmailAddresses')]
* @dataProvider provideValidEmailAddresses
*/
public function testValidEmailAddress($email): void public function testValidEmailAddress($email): void
{ {
$this->assertTrue(Email::is_valid_address($email)); $this->assertTrue(Email::is_valid_address($email));
} }
/** #[DataProvider('provideInvalidEmailAddresses')]
* @dataProvider provideInvalidEmailAddresses
*/
public function testInvalidEmailAddress($email): void public function testInvalidEmailAddress($email): void
{ {
$this->assertFalse(Email::is_valid_address($email)); $this->assertFalse(Email::is_valid_address($email));
} }
public function provideValidEmailAddresses(): array public static function provideValidEmailAddresses(): array
{ {
return [ return [
['test@example.com', 'test-123@sub.example.com'], ['test@example.com', 'test-123@sub.example.com'],
]; ];
} }
public function provideInvalidEmailAddresses(): array public static function provideInvalidEmailAddresses(): array
{ {
return [ return [
['foo.bar@', '@example.com', 'foo@'], ['foo.bar@', '@example.com', 'foo@'],
@ -538,9 +535,7 @@ class EmailTest extends SapphireTest
$this->assertTrue(true); $this->assertTrue(true);
} }
/** #[DataProvider('provideCreateAddressArray')]
* @dataProvider provideCreateAddressArray
*/
public function testCreateAddressArray(string|array $address, string $name, array $expected): void public function testCreateAddressArray(string|array $address, string $name, array $expected): void
{ {
$method = new \ReflectionMethod(Email::class, 'createAddressArray'); $method = new \ReflectionMethod(Email::class, 'createAddressArray');
@ -553,7 +548,7 @@ class EmailTest extends SapphireTest
} }
} }
public function provideCreateAddressArray(): array public static function provideCreateAddressArray(): array
{ {
return [ return [
[ [

View File

@ -7,6 +7,9 @@ use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\Middleware\TrustedProxyMiddleware; use SilverStripe\Control\Middleware\TrustedProxyMiddleware;
use SilverStripe\Control\Session; use SilverStripe\Control\Session;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Control\Tests\HTTPRequestTest\HTTPRequestTestException;
use PHPUnit\Framework\Attributes\DataProvider;
use SilverStripe\Dev\Exceptions\ExpectedWarningException;
class HTTPRequestTest extends SapphireTest class HTTPRequestTest extends SapphireTest
{ {
@ -55,7 +58,9 @@ class HTTPRequestTest extends SapphireTest
*/ */
public function testWildCardWithFurtherParams() public function testWildCardWithFurtherParams()
{ {
$this->expectWarning(); $this->enableErrorHandler();
$this->expectException(ExpectedWarningException::class);
$this->expectExceptionMessage('All URL params after wildcard parameter $@ will be ignored');
$request = new HTTPRequest('GET', 'admin/crm/test'); $request = new HTTPRequest('GET', 'admin/crm/test');
// all parameters after the first wildcard parameter are ignored // all parameters after the first wildcard parameter are ignored
$request->match('admin/$Action/$@/$Other/$*', true); $request->match('admin/$Action/$@/$Other/$*', true);
@ -150,7 +155,7 @@ class HTTPRequestTest extends SapphireTest
]; ];
} }
public function setHttpMethodDataProvider() public static function setHttpMethodDataProvider()
{ {
return [ return [
'POST request' => ['POST','POST'], 'POST request' => ['POST','POST'],
@ -162,9 +167,7 @@ class HTTPRequestTest extends SapphireTest
]; ];
} }
/** #[DataProvider('setHttpMethodDataProvider')]
* @dataProvider setHttpMethodDataProvider
*/
public function testSetHttpMethod($method, $expected) public function testSetHttpMethod($method, $expected)
{ {
$request = new HTTPRequest('GET', '/hello'); $request = new HTTPRequest('GET', '/hello');

View File

@ -5,6 +5,7 @@ namespace SilverStripe\Control\Tests;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Control\HTTPResponse; use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception; use SilverStripe\Control\HTTPResponse_Exception;
use PHPUnit\Framework\Attributes\DataProvider;
class HTTPResponseTest extends SapphireTest class HTTPResponseTest extends SapphireTest
{ {
@ -45,7 +46,7 @@ class HTTPResponseTest extends SapphireTest
$this->assertEmpty($response->getHeader('X-Animal')); $this->assertEmpty($response->getHeader('X-Animal'));
} }
public function providerSanitiseHeaders() public static function providerSanitiseHeaders()
{ {
return [ return [
'plain text is retained' => ['some arbitrary value1', 'some arbitrary value1'], 'plain text is retained' => ['some arbitrary value1', 'some arbitrary value1'],
@ -54,9 +55,7 @@ class HTTPResponseTest extends SapphireTest
]; ];
} }
/** #[DataProvider('providerSanitiseHeaders')]
* @dataProvider providerSanitiseHeaders
*/
public function testSanitiseHeaders(string $expected, string $value) public function testSanitiseHeaders(string $expected, string $value)
{ {
$response = new HTTPResponse(); $response = new HTTPResponse();
@ -65,7 +64,7 @@ class HTTPResponseTest extends SapphireTest
$this->assertSame($expected, $response->getHeader('X-Sanitised')); $this->assertSame($expected, $response->getHeader('X-Sanitised'));
} }
public function providerTestValidStatusCodes() public static function providerTestValidStatusCodes()
{ {
return [ return [
[200, 'OK'], [200, 'OK'],
@ -76,10 +75,10 @@ class HTTPResponseTest extends SapphireTest
} }
/** /**
* @dataProvider providerTestValidStatusCodes
* @param int $code * @param int $code
* @param string $status * @param string $status
*/ */
#[DataProvider('providerTestValidStatusCodes')]
public function testValidStatusCodes($code, $status) public function testValidStatusCodes($code, $status)
{ {
$response = new HTTPResponse(); $response = new HTTPResponse();

View File

@ -28,19 +28,19 @@ trait HttpRequestMockBuilder
$request->method('getSession')->willReturn($session); $request->method('getSession')->willReturn($session);
$request->method('getURL')->will($this->returnCallback(static function ($addParams) use ($url, $getVars) { $request->method('getURL')->willReturnCallback(static function ($addParams) use ($url, $getVars) {
return $addParams && count($getVars ?? []) ? $url . '?' . http_build_query($getVars) : $url; return $addParams && count($getVars ?? []) ? $url . '?' . http_build_query($getVars) : $url;
})); });
$request->method('getVars')->willReturn($getVars); $request->method('getVars')->willReturn($getVars);
$request->method('getVar')->will($this->returnCallback(static function ($key) use ($getVars) { $request->method('getVar')->willReturnCallback(static function ($key) use ($getVars) {
return isset($getVars[$key]) ? $getVars[$key] : null; return isset($getVars[$key]) ? $getVars[$key] : null;
})); });
$request->method('postVars')->willReturn($postVars); $request->method('postVars')->willReturn($postVars);
$request->method('postVar')->will($this->returnCallback(static function ($key) use ($postVars) { $request->method('postVar')->willReturnCallback(static function ($key) use ($postVars) {
return isset($postVars[$key]) ? $postVars[$key] : null; return isset($postVars[$key]) ? $postVars[$key] : null;
})); });
if (is_null($method)) { if (is_null($method)) {
if (count($postVars ?? [])) { if (count($postVars ?? [])) {

View File

@ -9,6 +9,7 @@ use SilverStripe\Control\Middleware\CanonicalURLMiddleware;
use SilverStripe\Core\Environment; use SilverStripe\Core\Environment;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Control\Director; use SilverStripe\Control\Director;
use PHPUnit\Framework\Attributes\DataProvider;
class CanonicalURLMiddlewareTest extends SapphireTest class CanonicalURLMiddlewareTest extends SapphireTest
{ {
@ -86,7 +87,7 @@ class CanonicalURLMiddlewareTest extends SapphireTest
$this->assertFalse($middleware->getForceBasicAuthToSSL(), 'Explicitly set is returned'); $this->assertFalse($middleware->getForceBasicAuthToSSL(), 'Explicitly set is returned');
} }
public function provideRedirectTrailingSlash() public static function provideRedirectTrailingSlash()
{ {
$testScenarios = []; $testScenarios = [];
foreach ([true, false] as $forceRedirect) { foreach ([true, false] as $forceRedirect) {
@ -103,9 +104,7 @@ class CanonicalURLMiddlewareTest extends SapphireTest
return $testScenarios; return $testScenarios;
} }
/** #[DataProvider('provideRedirectTrailingSlash')]
* @dataProvider provideRedirectTrailingSlash
*/
public function testRedirectTrailingSlash(bool $forceRedirect, bool $addTrailingSlash, bool $requestHasSlash) public function testRedirectTrailingSlash(bool $forceRedirect, bool $addTrailingSlash, bool $requestHasSlash)
{ {
Controller::config()->set('add_trailing_slash', $addTrailingSlash); Controller::config()->set('add_trailing_slash', $addTrailingSlash);
@ -147,7 +146,7 @@ class CanonicalURLMiddlewareTest extends SapphireTest
} }
} }
public function provideRedirectTrailingSlashIgnorePaths() public static function provideRedirectTrailingSlashIgnorePaths()
{ {
return [ return [
[ [
@ -169,9 +168,7 @@ class CanonicalURLMiddlewareTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideRedirectTrailingSlashIgnorePaths')]
* @dataProvider provideRedirectTrailingSlashIgnorePaths
*/
public function testRedirectTrailingSlashIgnorePaths(bool $addTrailingSlash, bool $requestHasSlash) public function testRedirectTrailingSlashIgnorePaths(bool $addTrailingSlash, bool $requestHasSlash)
{ {
Controller::config()->set('add_trailing_slash', $addTrailingSlash); Controller::config()->set('add_trailing_slash', $addTrailingSlash);
@ -206,7 +203,7 @@ class CanonicalURLMiddlewareTest extends SapphireTest
/** @var CanonicalURLMiddleware $middleware */ /** @var CanonicalURLMiddleware $middleware */
$middleware = $this->getMockBuilder(CanonicalURLMiddleware::class) $middleware = $this->getMockBuilder(CanonicalURLMiddleware::class)
->setMethods($mockedMethods) ->onlyMethods($mockedMethods)
->getMock(); ->getMock();
$middleware->expects($this->any())->method('isEnabled')->willReturn(true); $middleware->expects($this->any())->method('isEnabled')->willReturn(true);

View File

@ -5,6 +5,7 @@ namespace SilverStripe\Control\Tests\Middleware;
use SilverStripe\Control\HTTPResponse; use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware; use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use PHPUnit\Framework\Attributes\DataProvider;
class HTTPCacheControlMiddlewareTest extends SapphireTest class HTTPCacheControlMiddlewareTest extends SapphireTest
{ {
@ -18,7 +19,7 @@ class HTTPCacheControlMiddlewareTest extends SapphireTest
HTTPCacheControlMiddleware::reset(); HTTPCacheControlMiddleware::reset();
} }
public function provideCacheStates() public static function provideCacheStates()
{ {
return [ return [
['enableCache', false], ['enableCache', false],
@ -28,9 +29,7 @@ class HTTPCacheControlMiddlewareTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideCacheStates')]
* @dataProvider provideCacheStates
*/
public function testCheckDefaultStates($state, $immutable) public function testCheckDefaultStates($state, $immutable)
{ {
$cc = HTTPCacheControlMiddleware::singleton(); $cc = HTTPCacheControlMiddleware::singleton();
@ -42,9 +41,7 @@ class HTTPCacheControlMiddlewareTest extends SapphireTest
$this->assertStringContainsString('must-revalidate', $response->getHeader('cache-control')); $this->assertStringContainsString('must-revalidate', $response->getHeader('cache-control'));
} }
/** #[DataProvider('provideCacheStates')]
* @dataProvider provideCacheStates
*/
public function testSetMaxAge($state, $immutable) public function testSetMaxAge($state, $immutable)
{ {
$cc = HTTPCacheControlMiddleware::singleton(); $cc = HTTPCacheControlMiddleware::singleton();
@ -127,9 +124,7 @@ class HTTPCacheControlMiddlewareTest extends SapphireTest
$this->assertStringContainsString('max-age=300', $response->getHeader('cache-control')); $this->assertStringContainsString('max-age=300', $response->getHeader('cache-control'));
} }
/** #[DataProvider('provideCacheStates')]
* @dataProvider provideCacheStates
*/
public function testSetNoStore($state, $immutable) public function testSetNoStore($state, $immutable)
{ {
$cc = HTTPCacheControlMiddleware::singleton(); $cc = HTTPCacheControlMiddleware::singleton();
@ -156,9 +151,7 @@ class HTTPCacheControlMiddlewareTest extends SapphireTest
} }
} }
/** #[DataProvider('provideCacheStates')]
* @dataProvider provideCacheStates
*/
public function testSetNoCache($state, $immutable) public function testSetNoCache($state, $immutable)
{ {
$cc = HTTPCacheControlMiddleware::singleton(); $cc = HTTPCacheControlMiddleware::singleton();
@ -185,9 +178,7 @@ class HTTPCacheControlMiddlewareTest extends SapphireTest
} }
} }
/** #[DataProvider('provideCacheStates')]
* @dataProvider provideCacheStates
*/
public function testSetSharedMaxAge($state, $immutable) public function testSetSharedMaxAge($state, $immutable)
{ {
$cc = HTTPCacheControlMiddleware::singleton(); $cc = HTTPCacheControlMiddleware::singleton();
@ -212,9 +203,7 @@ class HTTPCacheControlMiddlewareTest extends SapphireTest
} }
} }
/** #[DataProvider('provideCacheStates')]
* @dataProvider provideCacheStates
*/
public function testSetMustRevalidate($state, $immutable) public function testSetMustRevalidate($state, $immutable)
{ {
$cc = HTTPCacheControlMiddleware::singleton(); $cc = HTTPCacheControlMiddleware::singleton();

View File

@ -65,9 +65,9 @@ class PjaxResponseNegotiatorTest extends SapphireTest
$request->addHeader('Accept', 'application/json'); $request->addHeader('Accept', 'application/json');
$response = $negotiator->respond($request); $response = $negotiator->respond($request);
$json = json_decode($response->getBody() ?? ''); $json = json_decode($response->getBody() ?? '');
$this->assertObjectHasAttribute('myfragment', $json); $this->assertObjectHasProperty('myfragment', $json);
$this->assertEquals('myfragment response', $json->myfragment); $this->assertEquals('myfragment response', $json->myfragment);
$this->assertObjectHasAttribute('otherfragment', $json); $this->assertObjectHasProperty('otherfragment', $json);
$this->assertEquals('otherfragment response', $json->otherfragment); $this->assertEquals('otherfragment response', $json->otherfragment);
} }
@ -92,6 +92,6 @@ class PjaxResponseNegotiatorTest extends SapphireTest
$response = $negotiator->setFragmentOverride(['beta'])->respond($request); $response = $negotiator->setFragmentOverride(['beta'])->respond($request);
$json = json_decode($response->getBody() ?? ''); $json = json_decode($response->getBody() ?? '');
$this->assertFalse(isset($json->alpha)); $this->assertFalse(isset($json->alpha));
$this->assertObjectHasAttribute('beta', $json); $this->assertObjectHasProperty('beta', $json);
} }
} }

View File

@ -5,7 +5,10 @@ namespace SilverStripe\Control\Tests;
use SilverStripe\Control\Controller; use SilverStripe\Control\Controller;
use SilverStripe\Control\Director; use SilverStripe\Control\Director;
use SilverStripe\Control\RequestHandler; use SilverStripe\Control\RequestHandler;
use SilverStripe\Control\Tests\RequestHandlerTest\RequestHandlerTestException;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use PHPUnit\Framework\Attributes\DataProvider;
use SilverStripe\Dev\Exceptions\ExpectedWarningException;
/** /**
* Tests for the RequestHandler class * Tests for the RequestHandler class
@ -14,7 +17,7 @@ class RequestHandlerTest extends SapphireTest
{ {
protected $usesDatabase = false; protected $usesDatabase = false;
public function provideTestLink(): array public static function provideTestLink(): array
{ {
return [ return [
// If there's no url segment, there's no link // If there's no url segment, there's no link
@ -42,14 +45,13 @@ class RequestHandlerTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideTestLink')]
* @dataProvider provideTestLink
*/
public function testLink(?string $urlSegment, ?string $action, ?string $expected) public function testLink(?string $urlSegment, ?string $action, ?string $expected)
{ {
$this->enableErrorHandler();
if ($urlSegment === null) { if ($urlSegment === null) {
$this->expectWarning(); $this->expectException(ExpectedWarningException::class);
$this->expectWarningMessage('Request handler SilverStripe\Control\RequestHandler does not have a url_segment defined. Relying on this link may be an application error'); $this->expectExceptionMessage('Request handler SilverStripe\Control\RequestHandler does not have a url_segment defined. Relying on this link may be an application error');
} }
$handler = new RequestHandler(); $handler = new RequestHandler();
@ -67,14 +69,13 @@ class RequestHandlerTest extends SapphireTest
$this->assertEquals($expected, $handler->Link($action)); $this->assertEquals($expected, $handler->Link($action));
} }
/** #[DataProvider('provideTestLink')]
* @dataProvider provideTestLink
*/
public function testAbsoluteLink(?string $urlSegment, ?string $action, ?string $expected) public function testAbsoluteLink(?string $urlSegment, ?string $action, ?string $expected)
{ {
$this->enableErrorHandler();
if ($urlSegment === null) { if ($urlSegment === null) {
$this->expectWarning(); $this->expectException(ExpectedWarningException::class);
$this->expectWarningMessage('Request handler SilverStripe\Control\RequestHandler does not have a url_segment defined. Relying on this link may be an application error'); $this->expectExceptionMessage('Request handler SilverStripe\Control\RequestHandler does not have a url_segment defined. Relying on this link may be an application error');
} }
$handler = new RequestHandler(); $handler = new RequestHandler();

View File

@ -15,6 +15,8 @@ use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\NullHTTPRequest; use SilverStripe\Control\NullHTTPRequest;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
/** /**
* Tests to cover the {@link Session} class * Tests to cover the {@link Session} class
@ -32,10 +34,8 @@ class SessionTest extends SapphireTest
parent::setUp(); parent::setUp();
} }
/** #[RunInSeparateProcess]
* @runInSeparateProcess #[PreserveGlobalState(false)]
* @preserveGlobalState disabled
*/
public function testInitDoesNotStartSessionWithoutIdentifier() public function testInitDoesNotStartSessionWithoutIdentifier()
{ {
$req = new HTTPRequest('GET', '/'); $req = new HTTPRequest('GET', '/');
@ -44,10 +44,8 @@ class SessionTest extends SapphireTest
$this->assertFalse($session->isStarted()); $this->assertFalse($session->isStarted());
} }
/** #[RunInSeparateProcess]
* @runInSeparateProcess #[PreserveGlobalState(false)]
* @preserveGlobalState disabled
*/
public function testInitStartsSessionWithIdentifier() public function testInitStartsSessionWithIdentifier()
{ {
$req = new HTTPRequest('GET', '/'); $req = new HTTPRequest('GET', '/');
@ -57,10 +55,8 @@ class SessionTest extends SapphireTest
$this->assertTrue($session->isStarted()); $this->assertTrue($session->isStarted());
} }
/** #[RunInSeparateProcess]
* @runInSeparateProcess #[PreserveGlobalState(false)]
* @preserveGlobalState disabled
*/
public function testInitStartsSessionWithData() public function testInitStartsSessionWithData()
{ {
$req = new HTTPRequest('GET', '/'); $req = new HTTPRequest('GET', '/');
@ -69,10 +65,8 @@ class SessionTest extends SapphireTest
$this->assertTrue($session->isStarted()); $this->assertTrue($session->isStarted());
} }
/** #[RunInSeparateProcess]
* @runInSeparateProcess #[PreserveGlobalState(false)]
* @preserveGlobalState disabled
*/
public function testStartUsesDefaultCookieNameWithHttp() public function testStartUsesDefaultCookieNameWithHttp()
{ {
$req = (new HTTPRequest('GET', '/')) $req = (new HTTPRequest('GET', '/'))
@ -83,10 +77,8 @@ class SessionTest extends SapphireTest
$this->assertNotEquals(session_name(), $session->config()->get('cookie_name_secure')); $this->assertNotEquals(session_name(), $session->config()->get('cookie_name_secure'));
} }
/** #[RunInSeparateProcess]
* @runInSeparateProcess #[PreserveGlobalState(false)]
* @preserveGlobalState disabled
*/
public function testStartUsesDefaultCookieNameWithHttpsAndCookieSecureOff() public function testStartUsesDefaultCookieNameWithHttpsAndCookieSecureOff()
{ {
$req = (new HTTPRequest('GET', '/')) $req = (new HTTPRequest('GET', '/'))
@ -97,10 +89,8 @@ class SessionTest extends SapphireTest
$this->assertNotEquals(session_name(), $session->config()->get('cookie_name_secure')); $this->assertNotEquals(session_name(), $session->config()->get('cookie_name_secure'));
} }
/** #[RunInSeparateProcess]
* @runInSeparateProcess #[PreserveGlobalState(false)]
* @preserveGlobalState disabled
*/
public function testStartUsesSecureCookieNameWithHttpsAndCookieSecureOn() public function testStartUsesSecureCookieNameWithHttpsAndCookieSecureOn()
{ {
$req = (new HTTPRequest('GET', '/')) $req = (new HTTPRequest('GET', '/'))
@ -112,10 +102,8 @@ class SessionTest extends SapphireTest
$this->assertEquals(session_name(), $session->config()->get('cookie_name_secure')); $this->assertEquals(session_name(), $session->config()->get('cookie_name_secure'));
} }
/** #[RunInSeparateProcess]
* @runInSeparateProcess #[PreserveGlobalState(false)]
* @preserveGlobalState disabled
*/
public function testStartErrorsWhenStartingTwice() public function testStartErrorsWhenStartingTwice()
{ {
$this->expectException(\BadMethodCallException::class); $this->expectException(\BadMethodCallException::class);
@ -126,10 +114,8 @@ class SessionTest extends SapphireTest
$session->start($req); $session->start($req);
} }
/** #[RunInSeparateProcess]
* @runInSeparateProcess #[PreserveGlobalState(false)]
* @preserveGlobalState disabled
*/
public function testStartRetainsInMemoryData() public function testStartRetainsInMemoryData()
{ {
$this->markTestIncomplete('Test'); $this->markTestIncomplete('Test');
@ -434,7 +420,7 @@ class SessionTest extends SapphireTest
); );
} }
public function provideSecureSamesiteData(): array public static function provideSecureSamesiteData(): array
{ {
$data = []; $data = [];
foreach ([true, false] as $secure) { foreach ([true, false] as $secure) {
@ -462,9 +448,7 @@ class SessionTest extends SapphireTest
return $data; return $data;
} }
/** #[DataProvider('provideSecureSamesiteData')]
* @dataProvider provideSecureSamesiteData
*/
public function testBuildCookieParamsSecureAndSamesite( public function testBuildCookieParamsSecureAndSamesite(
bool $secure, bool $secure,
string $sameSite, string $sameSite,

View File

@ -19,10 +19,11 @@ use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\MemcachedAdapter; use Symfony\Component\Cache\Adapter\MemcachedAdapter;
use Symfony\Component\Cache\Adapter\PhpFilesAdapter; use Symfony\Component\Cache\Adapter\PhpFilesAdapter;
use Symfony\Component\Cache\Adapter\RedisAdapter; use Symfony\Component\Cache\Adapter\RedisAdapter;
use PHPUnit\Framework\Attributes\DataProvider;
class DefaultCacheFactoryTest extends SapphireTest class DefaultCacheFactoryTest extends SapphireTest
{ {
public function provideCreate(): array public static function provideCreate(): array
{ {
$scenarios = [ $scenarios = [
[ [
@ -73,9 +74,7 @@ class DefaultCacheFactoryTest extends SapphireTest
return $allScenarios; return $allScenarios;
} }
/** #[DataProvider('provideCreate')]
* @dataProvider provideCreate
*/
public function testCreate(array $args, ?string $inMemoryCacheFactory): void public function testCreate(array $args, ?string $inMemoryCacheFactory): void
{ {
$oldFactoryValue = Environment::getEnv('SS_IN_MEMORY_CACHE_FACTORY'); $oldFactoryValue = Environment::getEnv('SS_IN_MEMORY_CACHE_FACTORY');

View File

@ -10,7 +10,7 @@ use SilverStripe\Core\Tests\ClassInfoTest\BaseClass;
use SilverStripe\Core\Tests\ClassInfoTest\BaseDataClass; use SilverStripe\Core\Tests\ClassInfoTest\BaseDataClass;
use SilverStripe\Core\Tests\ClassInfoTest\BaseObject; use SilverStripe\Core\Tests\ClassInfoTest\BaseObject;
use SilverStripe\Core\Tests\ClassInfoTest\ChildClass; use SilverStripe\Core\Tests\ClassInfoTest\ChildClass;
use SilverStripe\Core\Tests\ClassInfoTest\ExtendTest; use SilverStripe\Core\Tests\ClassInfoTest\ExtendTest1;
use SilverStripe\Core\Tests\ClassInfoTest\ExtendTest2; use SilverStripe\Core\Tests\ClassInfoTest\ExtendTest2;
use SilverStripe\Core\Tests\ClassInfoTest\ExtendTest3; use SilverStripe\Core\Tests\ClassInfoTest\ExtendTest3;
use SilverStripe\Core\Tests\ClassInfoTest\ExtensionTest1; use SilverStripe\Core\Tests\ClassInfoTest\ExtensionTest1;
@ -24,6 +24,7 @@ use SilverStripe\Core\Tests\ClassInfoTest\WithRelation;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\View\ViewableData; use SilverStripe\View\ViewableData;
use PHPUnit\Framework\Attributes\DataProvider;
class ClassInfoTest extends SapphireTest class ClassInfoTest extends SapphireTest
{ {
@ -38,7 +39,7 @@ class ClassInfoTest extends SapphireTest
WithCustomTable::class, WithCustomTable::class,
WithRelation::class, WithRelation::class,
BaseObject::class, BaseObject::class,
ExtendTest::class, ExtendTest1::class,
ExtendTest2::class, ExtendTest2::class,
ExtendTest3::class, ExtendTest3::class,
]; ];
@ -145,9 +146,6 @@ class ClassInfoTest extends SapphireTest
); );
} }
/**
* @covers \SilverStripe\Core\ClassInfo::ancestry()
*/
public function testAncestry() public function testAncestry()
{ {
$ancestry = ClassInfo::ancestry(ChildClass::class); $ancestry = ClassInfo::ancestry(ChildClass::class);
@ -176,9 +174,6 @@ class ClassInfoTest extends SapphireTest
); );
} }
/**
* @covers \SilverStripe\Core\ClassInfo::dataClassesFor()
*/
public function testDataClassesFor() public function testDataClassesFor()
{ {
$expect = [ $expect = [
@ -211,13 +206,10 @@ class ClassInfoTest extends SapphireTest
$this->assertEquals($expect, ClassInfo::dataClassesFor(strtolower($classes[2] ?? ''))); $this->assertEquals($expect, ClassInfo::dataClassesFor(strtolower($classes[2] ?? '')));
} }
/**
* @covers \SilverStripe\Core\ClassInfo::classesWithExtension()
*/
public function testClassesWithExtensionUsingConfiguredExtensions() public function testClassesWithExtensionUsingConfiguredExtensions()
{ {
$expect = [ $expect = [
'silverstripe\\core\\tests\\classinfotest\\extendtest' => ExtendTest::class, 'silverstripe\\core\\tests\\classinfotest\\extendtest1' => ExtendTest1::class,
'silverstripe\\core\\tests\\classinfotest\\extendtest2' => ExtendTest2::class, 'silverstripe\\core\\tests\\classinfotest\\extendtest2' => ExtendTest2::class,
'silverstripe\\core\\tests\\classinfotest\\extendtest3' => ExtendTest3::class, 'silverstripe\\core\\tests\\classinfotest\\extendtest3' => ExtendTest3::class,
]; ];
@ -228,20 +220,17 @@ class ClassInfoTest extends SapphireTest
); );
$expect = [ $expect = [
'silverstripe\\core\\tests\\classinfotest\\extendtest' => ExtendTest::class, 'silverstripe\\core\\tests\\classinfotest\\extendtest1' => ExtendTest1::class,
'silverstripe\\core\\tests\\classinfotest\\extendtest2' => ExtendTest2::class, 'silverstripe\\core\\tests\\classinfotest\\extendtest2' => ExtendTest2::class,
'silverstripe\\core\\tests\\classinfotest\\extendtest3' => ExtendTest3::class, 'silverstripe\\core\\tests\\classinfotest\\extendtest3' => ExtendTest3::class,
]; ];
$this->assertEquals( $this->assertEquals(
$expect, $expect,
ClassInfo::classesWithExtension(ExtensionTest1::class, ExtendTest::class, true), ClassInfo::classesWithExtension(ExtensionTest1::class, ExtendTest1::class, true),
'ClassInfo::testClassesWithExtension() returns class with extensions applied via class config, including the base class' 'ClassInfo::testClassesWithExtension() returns class with extensions applied via class config, including the base class'
); );
} }
/**
* @covers \SilverStripe\Core\ClassInfo::classesWithExtension()
*/
public function testClassesWithExtensionUsingDynamicallyAddedExtensions() public function testClassesWithExtensionUsingDynamicallyAddedExtensions()
{ {
$this->assertEquals( $this->assertEquals(
@ -250,7 +239,7 @@ class ClassInfoTest extends SapphireTest
'ClassInfo::testClassesWithExtension() returns no classes for extension that hasn\'t been applied yet.' 'ClassInfo::testClassesWithExtension() returns no classes for extension that hasn\'t been applied yet.'
); );
ExtendTest::add_extension(ExtensionTest2::class); ExtendTest1::add_extension(ExtensionTest2::class);
$expect = [ $expect = [
'silverstripe\\core\\tests\\classinfotest\\extendtest2' => ExtendTest2::class, 'silverstripe\\core\\tests\\classinfotest\\extendtest2' => ExtendTest2::class,
@ -258,17 +247,14 @@ class ClassInfoTest extends SapphireTest
]; ];
$this->assertEquals( $this->assertEquals(
$expect, $expect,
ClassInfo::classesWithExtension(ExtensionTest2::class, ExtendTest::class), ClassInfo::classesWithExtension(ExtensionTest2::class, ExtendTest1::class),
'ClassInfo::testClassesWithExtension() returns class with extra extension dynamically added' 'ClassInfo::testClassesWithExtension() returns class with extra extension dynamically added'
); );
} }
/**
* @covers \SilverStripe\Core\ClassInfo::classesWithExtension()
*/
public function testClassesWithExtensionWithDynamicallyRemovedExtensions() public function testClassesWithExtensionWithDynamicallyRemovedExtensions()
{ {
ExtendTest::remove_extension(ExtensionTest1::class); ExtendTest1::remove_extension(ExtensionTest1::class);
$this->assertEquals( $this->assertEquals(
[], [],
@ -277,7 +263,7 @@ class ClassInfoTest extends SapphireTest
); );
} }
/** @dataProvider provideHasMethodCases */ #[DataProvider('provideHasMethodCases')]
public function testHasMethod($object, $method, $output) public function testHasMethod($object, $method, $output)
{ {
$this->assertEquals( $this->assertEquals(
@ -286,7 +272,7 @@ class ClassInfoTest extends SapphireTest
); );
} }
public function provideHasMethodCases() public static function provideHasMethodCases()
{ {
return [ return [
'Basic object' => [ 'Basic object' => [
@ -327,7 +313,7 @@ class ClassInfoTest extends SapphireTest
]; ];
} }
/** @dataProvider provideClassSpecCases */ #[DataProvider('provideClassSpecCases')]
public function testParseClassSpec($input, $output) public function testParseClassSpec($input, $output)
{ {
$this->assertEquals( $this->assertEquals(
@ -336,7 +322,7 @@ class ClassInfoTest extends SapphireTest
); );
} }
public function provideClassSpecCases() public static function provideClassSpecCases()
{ {
return [ return [
'Standard class' => [ 'Standard class' => [

View File

@ -2,7 +2,7 @@
namespace SilverStripe\Core\Tests\ClassInfoTest; namespace SilverStripe\Core\Tests\ClassInfoTest;
class ExtendTest extends BaseObject class ExtendTest1 extends BaseObject
{ {
private static $extensions = [ private static $extensions = [
ExtensionTest1::class, ExtensionTest1::class,

View File

@ -2,6 +2,6 @@
namespace SilverStripe\Core\Tests\ClassInfoTest; namespace SilverStripe\Core\Tests\ClassInfoTest;
class ExtendTest2 extends ExtendTest class ExtendTest2 extends ExtendTest1
{ {
} }

View File

@ -8,6 +8,7 @@ use SilverStripe\Core\Convert;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\View\Parsers\URLSegmentFilter; use SilverStripe\View\Parsers\URLSegmentFilter;
use stdClass; use stdClass;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Test various functions on the {@link Convert} class. * Test various functions on the {@link Convert} class.
@ -416,8 +417,8 @@ PHP
* *
* @param string $memString * @param string $memString
* @param int $expected * @param int $expected
* @dataProvider memString2BytesProvider
*/ */
#[DataProvider('memString2BytesProvider')]
public function testMemString2Bytes($memString, $expected) public function testMemString2Bytes($memString, $expected)
{ {
$this->assertSame($expected, Convert::memstring2bytes($memString)); $this->assertSame($expected, Convert::memstring2bytes($memString));
@ -426,7 +427,7 @@ PHP
/** /**
* @return array * @return array
*/ */
public function memString2BytesProvider() public static function memString2BytesProvider()
{ {
return [ return [
'infinite' => ['-1', -1], 'infinite' => ['-1', -1],
@ -449,8 +450,8 @@ PHP
* *
* @param string $bytes * @param string $bytes
* @param int $expected * @param int $expected
* @dataProvider bytes2MemStringProvider
*/ */
#[DataProvider('bytes2MemStringProvider')]
public function testBytes2MemString($bytes, $expected) public function testBytes2MemString($bytes, $expected)
{ {
$this->assertSame($expected, Convert::bytes2memstring($bytes)); $this->assertSame($expected, Convert::bytes2memstring($bytes));
@ -459,7 +460,7 @@ PHP
/** /**
* @return array * @return array
*/ */
public function bytes2MemStringProvider() public static function bytes2MemStringProvider()
{ {
return [ return [
[0, '0B'], [0, '0B'],
@ -472,7 +473,7 @@ PHP
]; ];
} }
public function providerTestSlashes() public static function providerTestSlashes()
{ {
return [ return [
['bob/bob', '/', true, 'bob/bob'], ['bob/bob', '/', true, 'bob/bob'],
@ -497,12 +498,12 @@ PHP
} }
/** /**
* @dataProvider providerTestSlashes
* @param string $path * @param string $path
* @param string $separator * @param string $separator
* @param bool $multiple * @param bool $multiple
* @param string $expected * @param string $expected
*/ */
#[DataProvider('providerTestSlashes')]
public function testSlashes($path, $separator, $multiple, $expected) public function testSlashes($path, $separator, $multiple, $expected)
{ {
$this->assertEquals($expected, Convert::slashes($path, $separator, $multiple)); $this->assertEquals($expected, Convert::slashes($path, $separator, $multiple));

View File

@ -5,10 +5,11 @@ namespace SilverStripe\Core\Tests;
use ReflectionClass; use ReflectionClass;
use SilverStripe\Core\Environment; use SilverStripe\Core\Environment;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use PHPUnit\Framework\Attributes\DataProvider;
class EnvironmentTest extends SapphireTest class EnvironmentTest extends SapphireTest
{ {
public function providerTestPutEnv() public static function providerTestPutEnv()
{ {
return [ return [
['_ENVTEST_BOOL=true', '_ENVTEST_BOOL', true], ['_ENVTEST_BOOL=true', '_ENVTEST_BOOL', true],
@ -20,18 +21,14 @@ class EnvironmentTest extends SapphireTest
]; ];
} }
/** #[DataProvider('providerTestPutenv')]
* @dataProvider providerTestPutenv
*/
public function testPutEnv($put, $var, $value) public function testPutEnv($put, $var, $value)
{ {
Environment::putEnv($put); Environment::putEnv($put);
$this->assertEquals($value, Environment::getEnv($var)); $this->assertEquals($value, Environment::getEnv($var));
} }
/** #[DataProvider('providerTestPutEnv')]
* @dataProvider providerTestPutEnv
*/
public function testSetEnv($put, $var, $value) public function testSetEnv($put, $var, $value)
{ {
Environment::setEnv($var, $value); Environment::setEnv($var, $value);
@ -68,7 +65,7 @@ class EnvironmentTest extends SapphireTest
$this->assertEquals('global', $GLOBALS['test']); $this->assertEquals('global', $GLOBALS['test']);
} }
public function provideHasEnv() public static function provideHasEnv()
{ {
$setAsOptions = [ $setAsOptions = [
'.env', '.env',
@ -110,9 +107,7 @@ class EnvironmentTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideHasEnv')]
* @dataProvider provideHasEnv
*/
public function testHasEnv(?string $setAs, $value, bool $expected) public function testHasEnv(?string $setAs, $value, bool $expected)
{ {
$name = '_ENVTEST_HAS_ENV'; $name = '_ENVTEST_HAS_ENV';

View File

@ -27,6 +27,7 @@ use SilverStripe\Core\Tests\Injector\InjectorTest\TestStaticInjections;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\TestOnly; use SilverStripe\Dev\TestOnly;
use stdClass; use stdClass;
use PHPUnit\Framework\Attributes\DataProvider;
define('TEST_SERVICES', __DIR__ . '/AopProxyServiceTest'); define('TEST_SERVICES', __DIR__ . '/AopProxyServiceTest');
@ -829,9 +830,7 @@ class InjectorTest extends SapphireTest
$this->assertInstanceOf(OtherTestObject::class, $item->property->property); $this->assertInstanceOf(OtherTestObject::class, $item->property->property);
} }
/** #[DataProvider('provideConvertServicePropertyBackTicks')]
* @dataProvider provideConvertServicePropertyBackTicks
*/
public function testConvertServicePropertyBackTicks($value, $expected) public function testConvertServicePropertyBackTicks($value, $expected)
{ {
Environment::setEnv('INJECTOR_TEST_CSP_A', 'ABC'); Environment::setEnv('INJECTOR_TEST_CSP_A', 'ABC');
@ -841,7 +840,7 @@ class InjectorTest extends SapphireTest
$this->assertSame($expected, $actual); $this->assertSame($expected, $actual);
} }
public function provideConvertServicePropertyBackTicks() public static function provideConvertServicePropertyBackTicks()
{ {
return [ return [
['`INJECTOR_TEST_CSP_A`', 'ABC'], ['`INJECTOR_TEST_CSP_A`', 'ABC'],
@ -906,12 +905,10 @@ class InjectorTest extends SapphireTest
->expects($this->once()) ->expects($this->once())
->method('create') ->method('create')
->with($this->equalTo('service'), $this->equalTo([1, 2, 3])) ->with($this->equalTo('service'), $this->equalTo([1, 2, 3]))
->will( ->willReturnCallback(
$this->returnCallback( function ($args) {
function ($args) { return new InjectorTest\TestObject();
return new InjectorTest\TestObject(); }
}
)
); );
$injector->registerService($factory, 'factory'); $injector->registerService($factory, 'factory');

View File

@ -5,6 +5,7 @@ namespace SilverStripe\Core\Tests\Manifest;
use Exception; use Exception;
use SilverStripe\Core\Manifest\ClassManifest; use SilverStripe\Core\Manifest\ClassManifest;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Tests for the {@link ClassManifest} class. * Tests for the {@link ClassManifest} class.
@ -41,7 +42,7 @@ class ClassManifestTest extends SapphireTest
/** /**
* @return array * @return array
*/ */
public function providerTestGetItemPath() public static function providerTestGetItemPath()
{ {
$paths = [ $paths = [
['CLASSA', 'module/classes/ClassA.php'], ['CLASSA', 'module/classes/ClassA.php'],
@ -66,10 +67,10 @@ class ClassManifestTest extends SapphireTest
} }
/** /**
* @dataProvider providerTestGetItemPath
* @param string $name * @param string $name
* @param string $path * @param string $path
*/ */
#[DataProvider('providerTestGetItemPath')]
public function testGetItemPath($name, $path) public function testGetItemPath($name, $path)
{ {
$this->assertEquals("{$this->base}/$path", $this->manifest->getItemPath($name)); $this->assertEquals("{$this->base}/$path", $this->manifest->getItemPath($name));

View File

@ -12,10 +12,10 @@ class ManifestFileFinderTest extends SapphireTest
{ {
protected $defaultBase; protected $defaultBase;
public function __construct() public function __construct(string $name)
{ {
$this->defaultBase = __DIR__ . '/fixtures/manifestfilefinder'; $this->defaultBase = __DIR__ . '/fixtures/manifestfilefinder';
parent::__construct(); parent::__construct($name);
} }
/** /**

View File

@ -5,6 +5,7 @@ namespace SilverStripe\Core\Tests\Manifest;
use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Core\Manifest\ModuleLoader;
use SilverStripe\Core\Manifest\ModuleManifest; use SilverStripe\Core\Manifest\ModuleManifest;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use PHPUnit\Framework\Attributes\DataProvider;
class ModuleManifestTest extends SapphireTest class ModuleManifestTest extends SapphireTest
{ {
@ -111,7 +112,7 @@ class ModuleManifestTest extends SapphireTest
/** /**
* @return array * @return array
*/ */
public function providerTestGetModuleByPath() public static function providerTestGetModuleByPath()
{ {
return [ return [
['vendor/silverstripe/modulec/code/VendorClassA.php', 'silverstripe/modulec'], ['vendor/silverstripe/modulec/code/VendorClassA.php', 'silverstripe/modulec'],
@ -120,10 +121,10 @@ class ModuleManifestTest extends SapphireTest
} }
/** /**
* @dataProvider providerTestGetModuleByPath
* @param string $path * @param string $path
* @param string $expectedModuleName * @param string $expectedModuleName
*/ */
#[DataProvider('providerTestGetModuleByPath')]
public function testGetModuleByPath($path, $expectedModuleName) public function testGetModuleByPath($path, $expectedModuleName)
{ {
// important - load the manifest that we are working with to the ModuleLoader // important - load the manifest that we are working with to the ModuleLoader

View File

@ -9,6 +9,7 @@ use SilverStripe\View\ThemeResourceLoader;
use SilverStripe\View\ThemeManifest; use SilverStripe\View\ThemeManifest;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Core\Manifest\ModuleManifest; use SilverStripe\Core\Manifest\ModuleManifest;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Tests for the {@link TemplateLoader} class. * Tests for the {@link TemplateLoader} class.
@ -316,7 +317,7 @@ class ThemeResourceLoaderTest extends SapphireTest
} }
} }
public function providerTestGetPath() public static function providerTestGetPath()
{ {
return [ return [
// Legacy theme // Legacy theme
@ -372,10 +373,10 @@ class ThemeResourceLoaderTest extends SapphireTest
} }
/** /**
* @dataProvider providerTestGetPath
* @param string $name Theme identifier * @param string $name Theme identifier
* @param string $path Path to theme * @param string $path Path to theme
*/ */
#[DataProvider('providerTestGetPath')]
public function testGetPath($name, $path) public function testGetPath($name, $path)
{ {
$this->assertEquals($path, $this->loader->getPath($name)); $this->assertEquals($path, $this->loader->getPath($name));

View File

@ -12,8 +12,8 @@ use SilverStripe\Core\Tests\ObjectTest\ExtendTest2;
use SilverStripe\Core\Tests\ObjectTest\ExtendTest3; use SilverStripe\Core\Tests\ObjectTest\ExtendTest3;
use SilverStripe\Core\Tests\ObjectTest\ExtendTest4; use SilverStripe\Core\Tests\ObjectTest\ExtendTest4;
use SilverStripe\Core\Tests\ObjectTest\ExtendTest5; use SilverStripe\Core\Tests\ObjectTest\ExtendTest5;
use SilverStripe\Core\Tests\ObjectTest\ExtensionRemoveTest; use SilverStripe\Core\Tests\ObjectTest\ExtensionRemoveTest1;
use SilverStripe\Core\Tests\ObjectTest\ExtensionTest; use SilverStripe\Core\Tests\ObjectTest\ExtensionTest1;
use SilverStripe\Core\Tests\ObjectTest\ExtensionTest2; use SilverStripe\Core\Tests\ObjectTest\ExtensionTest2;
use SilverStripe\Core\Tests\ObjectTest\ExtensionTest3; use SilverStripe\Core\Tests\ObjectTest\ExtensionTest3;
use SilverStripe\Core\Tests\ObjectTest\MyObject; use SilverStripe\Core\Tests\ObjectTest\MyObject;
@ -36,7 +36,7 @@ class ObjectTest extends SapphireTest
public function testHasmethodBehaviour() public function testHasmethodBehaviour()
{ {
$obj = new ObjectTest\ExtendTest(); $obj = new ObjectTest\ExtendTestBase();
$this->assertTrue($obj->hasMethod('extendableMethod'), "Extension method found in original spelling"); $this->assertTrue($obj->hasMethod('extendableMethod'), "Extension method found in original spelling");
$this->assertTrue($obj->hasMethod('ExTendableMethod'), "Extension method found case-insensitive"); $this->assertTrue($obj->hasMethod('ExTendableMethod'), "Extension method found case-insensitive");
@ -107,13 +107,13 @@ class ObjectTest extends SapphireTest
*/ */
public function testCreateWithArgs() public function testCreateWithArgs()
{ {
$createdObj = ObjectTest\CreateTest::create('arg1', 'arg2', [], null, 'arg5'); $createdObj = ObjectTest\CreateTest1::create('arg1', 'arg2', [], null, 'arg5');
$this->assertEquals($createdObj->constructArguments, ['arg1', 'arg2', [], null, 'arg5']); $this->assertEquals($createdObj->constructArguments, ['arg1', 'arg2', [], null, 'arg5']);
} }
public function testCreateLateStaticBinding() public function testCreateLateStaticBinding()
{ {
$createdObj = ObjectTest\CreateTest::create('arg1', 'arg2', [], null, 'arg5'); $createdObj = ObjectTest\CreateTest1::create('arg1', 'arg2', [], null, 'arg5');
$this->assertEquals($createdObj->constructArguments, ['arg1', 'arg2', [], null, 'arg5']); $this->assertEquals($createdObj->constructArguments, ['arg1', 'arg2', [], null, 'arg5']);
} }
@ -135,16 +135,16 @@ class ObjectTest extends SapphireTest
'SilverStripe\\Core\\Tests\\oBjEcTTEST\\EXTENDTest1', 'SilverStripe\\Core\\Tests\\oBjEcTTEST\\EXTENDTest1',
"SilverStripe\\Core\\Tests\\ObjectTest\\ExtendTest2", "SilverStripe\\Core\\Tests\\ObjectTest\\ExtendTest2",
], ],
ExtensionTest::get_extensions() ExtensionTest1::get_extensions()
); );
$this->assertEquals( $this->assertEquals(
[ [
'SilverStripe\\Core\\Tests\\oBjEcTTEST\\EXTENDTest1', 'SilverStripe\\Core\\Tests\\oBjEcTTEST\\EXTENDTest1',
"SilverStripe\\Core\\Tests\\ObjectTest\\ExtendTest2('FOO', 'BAR')", "SilverStripe\\Core\\Tests\\ObjectTest\\ExtendTest2('FOO', 'BAR')",
], ],
ExtensionTest::get_extensions(null, true) ExtensionTest1::get_extensions(null, true)
); );
$inst = new ExtensionTest(); $inst = new ExtensionTest1();
$extensions = $inst->getExtensionInstances(); $extensions = $inst->getExtensionInstances();
$this->assertCount(2, $extensions); $this->assertCount(2, $extensions);
$this->assertArrayHasKey(ExtendTest1::class, $extensions); $this->assertArrayHasKey(ExtendTest1::class, $extensions);
@ -174,45 +174,45 @@ class ObjectTest extends SapphireTest
{ {
// ObjectTest_ExtendTest1 is built in via $extensions // ObjectTest_ExtendTest1 is built in via $extensions
$this->assertTrue( $this->assertTrue(
ExtensionTest::has_extension('SilverStripe\\Core\\Tests\\oBjEcTTEST\\EXTENDTest1'), ExtensionTest1::has_extension('SilverStripe\\Core\\Tests\\oBjEcTTEST\\EXTENDTest1'),
"Extensions are detected when set on Object::\$extensions on has_extension() without case-sensitivity" "Extensions are detected when set on Object::\$extensions on has_extension() without case-sensitivity"
); );
$this->assertTrue( $this->assertTrue(
ExtensionTest::has_extension(ExtendTest1::class), ExtensionTest1::has_extension(ExtendTest1::class),
"Extensions are detected when set on Object::\$extensions on has_extension() without case-sensitivity" "Extensions are detected when set on Object::\$extensions on has_extension() without case-sensitivity"
); );
$this->assertTrue( $this->assertTrue(
singleton(ExtensionTest::class)->hasExtension(ExtendTest1::class), singleton(ExtensionTest1::class)->hasExtension(ExtendTest1::class),
"Extensions are detected when set on Object::\$extensions on instance hasExtension() without" "Extensions are detected when set on Object::\$extensions on instance hasExtension() without"
. " case-sensitivity" . " case-sensitivity"
); );
// ObjectTest_ExtendTest2 is built in via $extensions (with parameters) // ObjectTest_ExtendTest2 is built in via $extensions (with parameters)
$this->assertTrue( $this->assertTrue(
ExtensionTest::has_extension(ExtendTest2::class), ExtensionTest1::has_extension(ExtendTest2::class),
"Extensions are detected with static has_extension() when set on Object::\$extensions with" "Extensions are detected with static has_extension() when set on Object::\$extensions with"
. " additional parameters" . " additional parameters"
); );
$this->assertTrue( $this->assertTrue(
singleton(ExtensionTest::class)->hasExtension(ExtendTest2::class), singleton(ExtensionTest1::class)->hasExtension(ExtendTest2::class),
"Extensions are detected with instance hasExtension() when set on Object::\$extensions with" "Extensions are detected with instance hasExtension() when set on Object::\$extensions with"
. " additional parameters" . " additional parameters"
); );
$this->assertFalse( $this->assertFalse(
ExtensionTest::has_extension(ExtendTest3::class), ExtensionTest1::has_extension(ExtendTest3::class),
"Other extensions available in the system are not present unless explicitly added to this object" "Other extensions available in the system are not present unless explicitly added to this object"
. " when checking through has_extension()" . " when checking through has_extension()"
); );
$this->assertFalse( $this->assertFalse(
singleton(ExtensionTest::class)->hasExtension(ExtendTest3::class), singleton(ExtensionTest1::class)->hasExtension(ExtendTest3::class),
"Other extensions available in the system are not present unless explicitly added to this object" "Other extensions available in the system are not present unless explicitly added to this object"
. " when checking through instance hasExtension()" . " when checking through instance hasExtension()"
); );
// ObjectTest_ExtendTest3 is added manually // ObjectTest_ExtendTest3 is added manually
ExtensionTest::add_extension(ExtendTest3::class . '("Param")'); ExtensionTest1::add_extension(ExtendTest3::class . '("Param")');
$this->assertTrue( $this->assertTrue(
ExtensionTest::has_extension(ExtendTest3::class), ExtensionTest1::has_extension(ExtendTest3::class),
"Extensions are detected with static has_extension() when added through add_extension()" "Extensions are detected with static has_extension() when added through add_extension()"
); );
// ExtendTest4 is added manually // ExtendTest4 is added manually
@ -235,7 +235,7 @@ class ObjectTest extends SapphireTest
"Sub-Extensions are detected with static has_extension() when added through add_extension()" "Sub-Extensions are detected with static has_extension() when added through add_extension()"
); );
// a singleton() wouldn't work as its already initialized // a singleton() wouldn't work as its already initialized
$objectTest_ExtensionTest = new ExtensionTest(); $objectTest_ExtensionTest = new ExtensionTest1();
$this->assertTrue( $this->assertTrue(
$objectTest_ExtensionTest->hasExtension(ExtendTest3::class), $objectTest_ExtensionTest->hasExtension(ExtendTest3::class),
"Extensions are detected with instance hasExtension() when added through add_extension()" "Extensions are detected with instance hasExtension() when added through add_extension()"
@ -248,37 +248,37 @@ class ObjectTest extends SapphireTest
"Injected sub-extensions are detected with static has_extension() when added through add_extension()" "Injected sub-extensions are detected with static has_extension() when added through add_extension()"
); );
ExtensionTest::remove_extension(ExtendTest3::class); ExtensionTest1::remove_extension(ExtendTest3::class);
} }
public function testRemoveExtension() public function testRemoveExtension()
{ {
// manually add ObjectTest_ExtendTest2 // manually add ObjectTest_ExtendTest2
ObjectTest\ExtensionRemoveTest::add_extension(ExtendTest2::class); ObjectTest\ExtensionRemoveTest1::add_extension(ExtendTest2::class);
$this->assertTrue( $this->assertTrue(
ObjectTest\ExtensionRemoveTest::has_extension(ExtendTest2::class), ObjectTest\ExtensionRemoveTest1::has_extension(ExtendTest2::class),
"Extension added through \$add_extension() are added correctly" "Extension added through \$add_extension() are added correctly"
); );
ObjectTest\ExtensionRemoveTest::remove_extension(ExtendTest2::class); ObjectTest\ExtensionRemoveTest1::remove_extension(ExtendTest2::class);
$this->assertFalse( $this->assertFalse(
ObjectTest\ExtensionRemoveTest::has_extension(ExtendTest2::class), ObjectTest\ExtensionRemoveTest1::has_extension(ExtendTest2::class),
"Extension added through \$add_extension() are detected as removed in has_extension()" "Extension added through \$add_extension() are detected as removed in has_extension()"
); );
$this->assertFalse( $this->assertFalse(
singleton(ExtensionRemoveTest::class)->hasExtension(ExtendTest2::class), singleton(ExtensionRemoveTest1::class)->hasExtension(ExtendTest2::class),
"Extensions added through \$add_extension() are detected as removed in instances through hasExtension()" "Extensions added through \$add_extension() are detected as removed in instances through hasExtension()"
); );
// ObjectTest_ExtendTest1 is already present in $extensions // ObjectTest_ExtendTest1 is already present in $extensions
ObjectTest\ExtensionRemoveTest::remove_extension(ExtendTest1::class); ObjectTest\ExtensionRemoveTest1::remove_extension(ExtendTest1::class);
$this->assertFalse( $this->assertFalse(
ObjectTest\ExtensionRemoveTest::has_extension(ExtendTest1::class), ObjectTest\ExtensionRemoveTest1::has_extension(ExtendTest1::class),
"Extension added through \$extensions are detected as removed in has_extension()" "Extension added through \$extensions are detected as removed in has_extension()"
); );
$objectTest_ExtensionRemoveTest = new ObjectTest\ExtensionRemoveTest(); $objectTest_ExtensionRemoveTest = new ObjectTest\ExtensionRemoveTest1();
$this->assertFalse( $this->assertFalse(
$objectTest_ExtensionRemoveTest->hasExtension(ExtendTest1::class), $objectTest_ExtensionRemoveTest->hasExtension(ExtendTest1::class),
"Extensions added through \$extensions are detected as removed in instances through hasExtension()" "Extensions added through \$extensions are detected as removed in instances through hasExtension()"
@ -287,20 +287,20 @@ class ObjectTest extends SapphireTest
public function testRemoveExtensionWithParameters() public function testRemoveExtensionWithParameters()
{ {
ObjectTest\ExtensionRemoveTest::add_extension(ExtendTest2::class . '("MyParam")'); ObjectTest\ExtensionRemoveTest1::add_extension(ExtendTest2::class . '("MyParam")');
$this->assertTrue( $this->assertTrue(
ObjectTest\ExtensionRemoveTest::has_extension(ExtendTest2::class), ObjectTest\ExtensionRemoveTest1::has_extension(ExtendTest2::class),
"Extension added through \$add_extension() are added correctly" "Extension added through \$add_extension() are added correctly"
); );
ObjectTest\ExtensionRemoveTest::remove_extension(ExtendTest2::class); ObjectTest\ExtensionRemoveTest1::remove_extension(ExtendTest2::class);
$this->assertFalse( $this->assertFalse(
ExtensionRemoveTest::has_extension(ExtendTest2::class), ExtensionRemoveTest1::has_extension(ExtendTest2::class),
"Extension added through \$add_extension() are detected as removed in has_extension()" "Extension added through \$add_extension() are detected as removed in has_extension()"
); );
$objectTest_ExtensionRemoveTest = new ObjectTest\ExtensionRemoveTest(); $objectTest_ExtensionRemoveTest = new ObjectTest\ExtensionRemoveTest1();
$this->assertFalse( $this->assertFalse(
$objectTest_ExtensionRemoveTest->hasExtension(ExtendTest2::class), $objectTest_ExtensionRemoveTest->hasExtension(ExtendTest2::class),
"Extensions added through \$extensions are detected as removed in instances through hasExtension()" "Extensions added through \$extensions are detected as removed in instances through hasExtension()"
@ -326,7 +326,7 @@ class ObjectTest extends SapphireTest
public function testExtend() public function testExtend()
{ {
$object = new ObjectTest\ExtendTest(); $object = new ObjectTest\ExtendTestBase();
$argument = 'test'; $argument = 'test';
$this->assertEquals($object->extend('extendableMethod'), ['ExtendTest2()']); $this->assertEquals($object->extend('extendableMethod'), ['ExtendTest2()']);
@ -334,13 +334,13 @@ class ObjectTest extends SapphireTest
$this->assertEquals($argument, 'modified'); $this->assertEquals($argument, 'modified');
$this->assertEquals( $this->assertEquals(
['ExtendTest()', 'ExtendTest2()'], ['ExtendTestBase()', 'ExtendTest2()'],
$object->invokeWithExtensions('extendableMethod') $object->invokeWithExtensions('extendableMethod')
); );
$arg1 = 'test'; $arg1 = 'test';
$arg2 = 'bob'; $arg2 = 'bob';
$this->assertEquals( $this->assertEquals(
['ExtendTest(test,bob)', 'ExtendTest2(modified,objectmodified)'], ['ExtendTestBase(test,bob)', 'ExtendTest2(modified,objectmodified)'],
$object->invokeWithExtensions('extendableMethod', $arg1, $arg2) $object->invokeWithExtensions('extendableMethod', $arg1, $arg2)
); );
$this->assertEquals('modified', $arg1); $this->assertEquals('modified', $arg1);

View File

@ -2,7 +2,7 @@
namespace SilverStripe\Core\Tests\ObjectTest; namespace SilverStripe\Core\Tests\ObjectTest;
class CacheTest extends BaseObject class CacheTest1 extends BaseObject
{ {
public $count = 0; public $count = 0;

View File

@ -2,7 +2,7 @@
namespace SilverStripe\Core\Tests\ObjectTest; namespace SilverStripe\Core\Tests\ObjectTest;
class CreateTest extends BaseObject class CreateTest1 extends BaseObject
{ {
public $constructArguments; public $constructArguments;

View File

@ -2,7 +2,7 @@
namespace SilverStripe\Core\Tests\ObjectTest; namespace SilverStripe\Core\Tests\ObjectTest;
class ExtendTest extends BaseObject class ExtendTestBase extends BaseObject
{ {
private static $extensions = [ private static $extensions = [
ExtendTest1::class, ExtendTest1::class,
@ -15,6 +15,6 @@ class ExtendTest extends BaseObject
if ($argument2) { if ($argument2) {
$argument2 = 'objectmodified'; $argument2 = 'objectmodified';
} }
return "ExtendTest($args)"; return "ExtendTestBase($args)";
} }
} }

View File

@ -2,7 +2,7 @@
namespace SilverStripe\Core\Tests\ObjectTest; namespace SilverStripe\Core\Tests\ObjectTest;
class ExtensionRemoveTest extends BaseObject class ExtensionRemoveTest1 extends BaseObject
{ {
private static $extensions = [ private static $extensions = [
ExtendTest1::class, ExtendTest1::class,

View File

@ -2,7 +2,7 @@
namespace SilverStripe\Core\Tests\ObjectTest; namespace SilverStripe\Core\Tests\ObjectTest;
class ExtensionTest extends BaseObject class ExtensionTest1 extends BaseObject
{ {
private static $extensions = [ private static $extensions = [
'SilverStripe\\Core\\Tests\\oBjEcTTEST\\EXTENDTest1', 'SilverStripe\\Core\\Tests\\oBjEcTTEST\\EXTENDTest1',

View File

@ -5,16 +5,17 @@ namespace SilverStripe\Core\Tests;
use InvalidArgumentException; use InvalidArgumentException;
use SilverStripe\Core\Path; use SilverStripe\Core\Path;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use PHPUnit\Framework\Attributes\DataProvider;
class PathTest extends SapphireTest class PathTest extends SapphireTest
{ {
/** /**
* Test paths are joined * Test paths are joined
* *
* @dataProvider providerTestJoinPaths
* @param array $args Arguments to pass to Path::join() * @param array $args Arguments to pass to Path::join()
* @param string $expected Expected path * @param string $expected Expected path
*/ */
#[DataProvider('providerTestJoinPaths')]
public function testJoinPaths($args, $expected) public function testJoinPaths($args, $expected)
{ {
$joined = Path::join($args); $joined = Path::join($args);
@ -26,7 +27,7 @@ class PathTest extends SapphireTest
* *
* @return array * @return array
*/ */
public function providerTestJoinPaths() public static function providerTestJoinPaths()
{ {
$tests = [ $tests = [
// Single arg // Single arg
@ -64,10 +65,10 @@ class PathTest extends SapphireTest
/** /**
* Test that joinPaths give the appropriate error * Test that joinPaths give the appropriate error
* *
* @dataProvider providerTestJoinPathsErrors
* @param array $args Arguments to pass to Filesystem::joinPath() * @param array $args Arguments to pass to Filesystem::joinPath()
* @param string $error Expected path * @param string $error Expected path
*/ */
#[DataProvider('providerTestJoinPathsErrors')]
public function testJoinPathsErrors($args, $error) public function testJoinPathsErrors($args, $error)
{ {
$this->expectException(\InvalidArgumentException::class); $this->expectException(\InvalidArgumentException::class);
@ -75,7 +76,7 @@ class PathTest extends SapphireTest
Path::join($args); Path::join($args);
} }
public function providerTestJoinPathsErrors() public static function providerTestJoinPathsErrors()
{ {
return [ return [
[['/base', '../passwd'], 'Can not collapse relative folders'], [['/base', '../passwd'], 'Can not collapse relative folders'],
@ -87,17 +88,17 @@ class PathTest extends SapphireTest
} }
/** /**
* @dataProvider providerTestNormalise
* @param string $input * @param string $input
* @param string $expected * @param string $expected
*/ */
#[DataProvider('providerTestNormalise')]
public function testNormalise($input, $expected) public function testNormalise($input, $expected)
{ {
$output = Path::normalise($input); $output = Path::normalise($input);
$this->assertEquals($expected, $output, "Expected $input to be normalised to $expected"); $this->assertEquals($expected, $output, "Expected $input to be normalised to $expected");
} }
public function providerTestNormalise() public static function providerTestNormalise()
{ {
$tests = [ $tests = [
// Windows paths // Windows paths

View File

@ -60,12 +60,13 @@ use Symfony\Component\Validator\Constraints\Ulid;
use Symfony\Component\Validator\Constraints\Unique; use Symfony\Component\Validator\Constraints\Unique;
use Symfony\Component\Validator\Constraints\Url; use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Validator\Constraints\Uuid; use Symfony\Component\Validator\Constraints\Uuid;
use PHPUnit\Framework\Attributes\DataProvider;
class ConstraintValidatorTest extends SapphireTest class ConstraintValidatorTest extends SapphireTest
{ {
protected $usesDatabase = false; protected $usesDatabase = false;
public function provideValidate(): array public static function provideValidate(): array
{ {
$scenarios = [ $scenarios = [
// basic // basic
@ -309,15 +310,14 @@ class ConstraintValidatorTest extends SapphireTest
* *
* We're not actually testing the validation logic per se - just testing that the validators * We're not actually testing the validation logic per se - just testing that the validators
* all do some validating (hence why they are all set to fail) without exceptions being thrown. * all do some validating (hence why they are all set to fail) without exceptions being thrown.
*
* @dataProvider provideValidate
*/ */
#[DataProvider('provideValidate')]
public function testValidate(mixed $value, Constraint $constraint): void public function testValidate(mixed $value, Constraint $constraint): void
{ {
$this->assertFalse(ConstraintValidator::validate($value, $constraint)->isValid()); $this->assertFalse(ConstraintValidator::validate($value, $constraint)->isValid());
} }
public function provideValidateResults(): array public static function provideValidateResults(): array
{ {
return [ return [
'single constraint, no field' => [ 'single constraint, no field' => [
@ -343,9 +343,7 @@ class ConstraintValidatorTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideValidateResults')]
* @dataProvider provideValidateResults
*/
public function testValidateResults(mixed $value, Constraint|array $constraints, string $fieldName): void public function testValidateResults(mixed $value, Constraint|array $constraints, string $fieldName): void
{ {
$result = ConstraintValidator::validate($value, $constraints, $fieldName); $result = ConstraintValidator::validate($value, $constraints, $fieldName);

View File

@ -9,6 +9,7 @@ use SilverStripe\Core\Kernel;
use SilverStripe\Dev\Backtrace; use SilverStripe\Dev\Backtrace;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use PHPUnit\Framework\Attributes\DataProvider;
class BacktraceTest extends SapphireTest class BacktraceTest extends SapphireTest
{ {
@ -115,7 +116,7 @@ class BacktraceTest extends SapphireTest
$this->assertEquals('myval', $filtered[2]['args']['myarg']); $this->assertEquals('myval', $filtered[2]['args']['myarg']);
} }
public function matchesFilterableClassProvider(): array public static function matchesFilterableClassProvider(): array
{ {
return [ return [
[ [
@ -157,9 +158,7 @@ class BacktraceTest extends SapphireTest
]; ];
} }
/** #[DataProvider('matchesFilterableClassProvider')]
* @dataProvider matchesFilterableClassProvider
*/
public function testMatchesFilterableClass(string $className, string $filterableClass, bool $expected, string $message): void public function testMatchesFilterableClass(string $className, string $filterableClass, bool $expected, string $message): void
{ {
$reflectionMethod = new ReflectionMethod(Backtrace::class . '::matchesFilterableClass'); $reflectionMethod = new ReflectionMethod(Backtrace::class . '::matchesFilterableClass');

View File

@ -17,6 +17,7 @@ use SilverStripe\Dev\Tests\CsvBulkLoaderTest\CanModifyModel;
use SilverStripe\Dev\Tests\CsvBulkLoaderTest\CantCreateModel; use SilverStripe\Dev\Tests\CsvBulkLoaderTest\CantCreateModel;
use SilverStripe\Dev\Tests\CsvBulkLoaderTest\CantDeleteModel; use SilverStripe\Dev\Tests\CsvBulkLoaderTest\CantDeleteModel;
use SilverStripe\Dev\Tests\CsvBulkLoaderTest\CantEditModel; use SilverStripe\Dev\Tests\CsvBulkLoaderTest\CantEditModel;
use PHPUnit\Framework\Attributes\DataProvider;
class CsvBulkLoaderTest extends SapphireTest class CsvBulkLoaderTest extends SapphireTest
{ {
@ -345,9 +346,7 @@ class CsvBulkLoaderTest extends SapphireTest
$this->assertCount(10, $results); $this->assertCount(10, $results);
} }
/** #[DataProvider('provideCheckPermissions')]
* @dataProvider provideCheckPermissions
*/
public function testCheckPermissions(string $class, string $file, bool $respectPerms, string $exceptionMessage) public function testCheckPermissions(string $class, string $file, bool $respectPerms, string $exceptionMessage)
{ {
$loader = new CsvBulkLoader($class); $loader = new CsvBulkLoader($class);
@ -370,7 +369,7 @@ class CsvBulkLoaderTest extends SapphireTest
} }
} }
public function provideCheckPermissions() public static function provideCheckPermissions()
{ {
$scenarios = [ $scenarios = [
'Has all permissions' => [ 'Has all permissions' => [

View File

@ -9,9 +9,12 @@ use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Environment; use SilverStripe\Core\Environment;
use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestException;
use SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject; use SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Kernel; use SilverStripe\Core\Kernel;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\DoesNotPerformAssertions;
class DeprecationTest extends SapphireTest class DeprecationTest extends SapphireTest
{ {
@ -27,14 +30,14 @@ class DeprecationTest extends SapphireTest
{ {
// Use custom error handler for two reasons: // Use custom error handler for two reasons:
// - Filter out errors for deprecated class properties unrelated to this unit test // - Filter out errors for deprecated class properties unrelated to this unit test
// - Allow the use of expectDeprecation(), which doesn't work with E_USER_DEPRECATION by default // - Allow the use of expectException(), which doesn't work with E_USER_DEPRECATION by default
// https://github.com/laminas/laminas-di/pull/30#issuecomment-927585210 // https://github.com/laminas/laminas-di/pull/30#issuecomment-927585210
parent::setup(); parent::setup();
$this->noticesWereEnabled = Deprecation::isEnabled(); $this->noticesWereEnabled = Deprecation::isEnabled();
$this->oldHandler = set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) { $this->oldHandler = set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) {
if ($errno === E_USER_DEPRECATED) { if ($errno === E_USER_DEPRECATED) {
if (str_contains($errstr, 'SilverStripe\\Dev\\Tests\\DeprecationTest')) { if (str_contains($errstr, 'SilverStripe\\Dev\\Tests\\DeprecationTest')) {
throw new Deprecated($errstr, $errno, '', 1); throw new DeprecationTestException($errstr);
} else { } else {
// Suppress any E_USER_DEPRECATED unrelated to this unit-test // Suppress any E_USER_DEPRECATED unrelated to this unit-test
return true; return true;
@ -73,8 +76,8 @@ class DeprecationTest extends SapphireTest
'My message.', 'My message.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testNotice.' 'Called from SilverStripe\Dev\Tests\DeprecationTest->testNotice.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(); Deprecation::enable();
$ret = $this->myDeprecatedMethod(); $ret = $this->myDeprecatedMethod();
$this->assertSame('abc', $ret); $this->assertSame('abc', $ret);
@ -90,8 +93,8 @@ class DeprecationTest extends SapphireTest
'My message.', 'My message.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testCallUserFunc.' 'Called from SilverStripe\Dev\Tests\DeprecationTest->testCallUserFunc.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(); Deprecation::enable();
$ret = call_user_func([$this, 'myDeprecatedMethod']); $ret = call_user_func([$this, 'myDeprecatedMethod']);
$this->assertSame('abc', $ret); $this->assertSame('abc', $ret);
@ -105,8 +108,8 @@ class DeprecationTest extends SapphireTest
'My message.', 'My message.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testCallUserFuncArray.' 'Called from SilverStripe\Dev\Tests\DeprecationTest->testCallUserFuncArray.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(); Deprecation::enable();
$ret = call_user_func_array([$this, 'myDeprecatedMethod'], []); $ret = call_user_func_array([$this, 'myDeprecatedMethod'], []);
$this->assertSame('abc', $ret); $this->assertSame('abc', $ret);
@ -130,8 +133,8 @@ class DeprecationTest extends SapphireTest
'My message.', 'My message.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testWithNoReplacementTrue.' 'Called from SilverStripe\Dev\Tests\DeprecationTest->testWithNoReplacementTrue.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(true); Deprecation::enable(true);
$ret = Deprecation::withNoReplacement(function () { $ret = Deprecation::withNoReplacement(function () {
return $this->myDeprecatedMethod(); return $this->myDeprecatedMethod();
@ -147,8 +150,8 @@ class DeprecationTest extends SapphireTest
'My message.', 'My message.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testWithNoReplacementTrueCallUserFunc.' 'Called from SilverStripe\Dev\Tests\DeprecationTest->testWithNoReplacementTrueCallUserFunc.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(true); Deprecation::enable(true);
$ret = Deprecation::withNoReplacement(function () { $ret = Deprecation::withNoReplacement(function () {
return call_user_func([$this, 'myDeprecatedMethod']); return call_user_func([$this, 'myDeprecatedMethod']);
@ -164,8 +167,8 @@ class DeprecationTest extends SapphireTest
'My message.', 'My message.',
'Called from PHPUnit\Framework\TestCase->runTest.' 'Called from PHPUnit\Framework\TestCase->runTest.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(true); Deprecation::enable(true);
Deprecation::withNoReplacement(function () { Deprecation::withNoReplacement(function () {
Deprecation::notice('123', 'My message.'); Deprecation::notice('123', 'My message.');
@ -180,8 +183,8 @@ class DeprecationTest extends SapphireTest
'Some class message.', 'Some class message.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testClassWithNoReplacement.' 'Called from SilverStripe\Dev\Tests\DeprecationTest->testClassWithNoReplacement.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(true); Deprecation::enable(true);
// using this syntax because my IDE was complaining about DeprecationTestObject not existing // using this syntax because my IDE was complaining about DeprecationTestObject not existing
// when trying to use `new DeprecationTestObject();` // when trying to use `new DeprecationTestObject();`
@ -197,16 +200,14 @@ class DeprecationTest extends SapphireTest
'Some class message.', 'Some class message.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testClassWithInjectorWithNoReplacement.' 'Called from SilverStripe\Dev\Tests\DeprecationTest->testClassWithInjectorWithNoReplacement.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(true); Deprecation::enable(true);
Injector::inst()->get(DeprecationTestObject::class); Injector::inst()->get(DeprecationTestObject::class);
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
/** #[DoesNotPerformAssertions]
* @doesNotPerformAssertions
*/
public function testDisabled() public function testDisabled()
{ {
if ($this->noticesWereEnabled) { if ($this->noticesWereEnabled) {
@ -229,8 +230,8 @@ class DeprecationTest extends SapphireTest
'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.first_config is deprecated.', 'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.first_config is deprecated.',
'My first config message.' 'My first config message.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(); Deprecation::enable();
Config::inst()->get(DeprecationTestObject::class, 'first_config'); Config::inst()->get(DeprecationTestObject::class, 'first_config');
Deprecation::outputNotices(); Deprecation::outputNotices();
@ -242,8 +243,8 @@ class DeprecationTest extends SapphireTest
'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.second_config is deprecated.', 'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.second_config is deprecated.',
'My second config message.' 'My second config message.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(); Deprecation::enable();
Config::inst()->get(DeprecationTestObject::class, 'second_config'); Config::inst()->get(DeprecationTestObject::class, 'second_config');
Deprecation::outputNotices(); Deprecation::outputNotices();
@ -252,8 +253,8 @@ class DeprecationTest extends SapphireTest
public function testConfigGetThird() public function testConfigGetThird()
{ {
$message = 'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.third_config is deprecated.'; $message = 'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.third_config is deprecated.';
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(); Deprecation::enable();
Config::inst()->get(DeprecationTestObject::class, 'third_config'); Config::inst()->get(DeprecationTestObject::class, 'third_config');
Deprecation::outputNotices(); Deprecation::outputNotices();
@ -265,8 +266,8 @@ class DeprecationTest extends SapphireTest
'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.first_config is deprecated.', 'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.first_config is deprecated.',
'My first config message.' 'My first config message.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(); Deprecation::enable();
Config::modify()->set(DeprecationTestObject::class, 'first_config', 'abc'); Config::modify()->set(DeprecationTestObject::class, 'first_config', 'abc');
Deprecation::outputNotices(); Deprecation::outputNotices();
@ -278,14 +279,14 @@ class DeprecationTest extends SapphireTest
'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.array_config is deprecated.', 'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.array_config is deprecated.',
'My array config message.' 'My array config message.'
]); ]);
$this->expectDeprecation(); $this->expectException(DeprecationTestException::class);
$this->expectDeprecationMessage($message); $this->expectExceptionMessage($message);
Deprecation::enable(); Deprecation::enable();
Config::modify()->merge(DeprecationTestObject::class, 'array_config', ['abc']); Config::modify()->merge(DeprecationTestObject::class, 'array_config', ['abc']);
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
public function provideConfigVsEnv() public static function provideConfigVsEnv()
{ {
return [ return [
// env var not set - config setting is respected // env var not set - config setting is respected
@ -326,25 +327,19 @@ class DeprecationTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideConfigVsEnv')]
* @dataProvider provideConfigVsEnv
*/
public function testEnabledConfigVsEnv($envVal, bool $configVal, bool $expected) public function testEnabledConfigVsEnv($envVal, bool $configVal, bool $expected)
{ {
$this->runConfigVsEnvTest('SS_DEPRECATION_ENABLED', $envVal, $configVal, $expected); $this->runConfigVsEnvTest('SS_DEPRECATION_ENABLED', $envVal, $configVal, $expected);
} }
/** #[DataProvider('provideConfigVsEnv')]
* @dataProvider provideConfigVsEnv
*/
public function testShowHttpConfigVsEnv($envVal, bool $configVal, bool $expected) public function testShowHttpConfigVsEnv($envVal, bool $configVal, bool $expected)
{ {
$this->runConfigVsEnvTest('SS_DEPRECATION_SHOW_HTTP', $envVal, $configVal, $expected); $this->runConfigVsEnvTest('SS_DEPRECATION_SHOW_HTTP', $envVal, $configVal, $expected);
} }
/** #[DataProvider('provideConfigVsEnv')]
* @dataProvider provideConfigVsEnv
*/
public function testShowCliConfigVsEnv($envVal, bool $configVal, bool $expected) public function testShowCliConfigVsEnv($envVal, bool $configVal, bool $expected)
{ {
$this->runConfigVsEnvTest('SS_DEPRECATION_SHOW_CLI', $envVal, $configVal, $expected); $this->runConfigVsEnvTest('SS_DEPRECATION_SHOW_CLI', $envVal, $configVal, $expected);
@ -391,7 +386,7 @@ class DeprecationTest extends SapphireTest
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
public function provideVarAsBoolean() public static function provideVarAsBoolean()
{ {
return [ return [
[ [
@ -437,9 +432,7 @@ class DeprecationTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideVarAsBoolean')]
* @dataProvider provideVarAsBoolean
*/
public function testVarAsBoolean($rawValue, bool $expected) public function testVarAsBoolean($rawValue, bool $expected)
{ {
$reflectionVarAsBoolean = new ReflectionMethod(Deprecation::class, 'varAsBoolean'); $reflectionVarAsBoolean = new ReflectionMethod(Deprecation::class, 'varAsBoolean');
@ -448,7 +441,7 @@ class DeprecationTest extends SapphireTest
$this->assertSame($expected, $reflectionVarAsBoolean->invoke(null, $rawValue)); $this->assertSame($expected, $reflectionVarAsBoolean->invoke(null, $rawValue));
} }
public function provideIsEnabled() public static function provideIsEnabled()
{ {
return [ return [
'dev, explicitly enabled' => [ 'dev, explicitly enabled' => [
@ -514,9 +507,7 @@ class DeprecationTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideIsEnabled')]
* @dataProvider provideIsEnabled
*/
public function testIsEnabled(string $envMode, ?bool $envEnabled, bool $staticEnabled, bool $expected) public function testIsEnabled(string $envMode, ?bool $envEnabled, bool $staticEnabled, bool $expected)
{ {
/** @var Kernel $kernel */ /** @var Kernel $kernel */

View File

@ -0,0 +1,10 @@
<?php
namespace SilverStripe\Dev\Tests\DeprecationTest;
use Exception;
use SilverStripe\Dev\TestOnly;
class DeprecationTestException extends Exception implements TestOnly
{
}

View File

@ -11,6 +11,7 @@ use SilverStripe\Dev\DevelopmentAdmin;
use SilverStripe\Dev\FunctionalTest; use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Dev\Tests\DevAdminControllerTest\Controller1; use SilverStripe\Dev\Tests\DevAdminControllerTest\Controller1;
use SilverStripe\Dev\Tests\DevAdminControllerTest\ControllerWithPermissions; use SilverStripe\Dev\Tests\DevAdminControllerTest\ControllerWithPermissions;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Note: the running of this test is handled by the thing it's testing (DevelopmentAdmin controller). * Note: the running of this test is handled by the thing it's testing (DevelopmentAdmin controller).
@ -66,9 +67,7 @@ class DevAdminControllerTest extends FunctionalTest
$this->assertEquals(true, $this->getAndCheckForError('/dev/x2')); $this->assertEquals(true, $this->getAndCheckForError('/dev/x2'));
} }
/** #[DataProvider('getLinksPermissionsProvider')]
* @dataProvider getLinksPermissionsProvider
*/
public function testGetLinks(string $permission, array $present, array $absent): void public function testGetLinks(string $permission, array $present, array $absent): void
{ {
DevelopmentAdmin::config()->set('allow_all_cli', false); DevelopmentAdmin::config()->set('allow_all_cli', false);
@ -94,7 +93,7 @@ class DevAdminControllerTest extends FunctionalTest
} }
} }
protected function getLinksPermissionsProvider() : array public static function getLinksPermissionsProvider() : array
{ {
return [ return [
['ADMIN', ['x1', 'x1/y1', 'x3'], ['x2']], ['ADMIN', ['x1', 'x1/y1', 'x3'], ['x2']],

View File

@ -6,10 +6,11 @@ use SilverStripe\Dev\Constraint\SSListContainsOnly;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use PHPUnit\Framework\Attributes\DataProvider;
class SSListContainsOnlyTest extends SapphireTest class SSListContainsOnlyTest extends SapphireTest
{ {
public function provideMatchesForList() public static function provideMatchesForList()
{ {
return [ return [
[ [
@ -28,7 +29,7 @@ class SSListContainsOnlyTest extends SapphireTest
} }
public function provideInvalidMatchesForList() public static function provideInvalidMatchesForList()
{ {
return [ return [
[ [
@ -50,10 +51,9 @@ class SSListContainsOnlyTest extends SapphireTest
} }
/** /**
* @dataProvider provideMatchesForList()
*
* @param $matches * @param $matches
*/ */
#[DataProvider('provideMatchesForList')]
public function testEvaluateListMatchesCorrectly($matches) public function testEvaluateListMatchesCorrectly($matches)
{ {
$constraint = new SSListContainsOnly($matches); $constraint = new SSListContainsOnly($matches);
@ -74,10 +74,9 @@ class SSListContainsOnlyTest extends SapphireTest
} }
/** /**
* @dataProvider provideInvalidMatchesForList()
*
* @param $matches * @param $matches
*/ */
#[DataProvider('provideInvalidMatchesForList')]
public function testEvaluateListDoesNotMatchWrongMatches($matches) public function testEvaluateListDoesNotMatchWrongMatches($matches)
{ {
$constraint = new SSListContainsOnly($matches); $constraint = new SSListContainsOnly($matches);

View File

@ -6,10 +6,11 @@ use SilverStripe\Dev\Constraint\SSListContains;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use PHPUnit\Framework\Attributes\DataProvider;
class SSListContainsTest extends SapphireTest class SSListContainsTest extends SapphireTest
{ {
public function provideMatchesForList() public static function provideMatchesForList()
{ {
return [ return [
[ [
@ -31,7 +32,7 @@ class SSListContainsTest extends SapphireTest
} }
public function provideInvalidMatchesForList() public static function provideInvalidMatchesForList()
{ {
return [ return [
[ [
@ -53,10 +54,9 @@ class SSListContainsTest extends SapphireTest
} }
/** /**
* @dataProvider provideMatchesForList()
*
* @param $matches * @param $matches
*/ */
#[DataProvider('provideMatchesForList')]
public function testEvaluateListMatchesCorrectly($matches) public function testEvaluateListMatchesCorrectly($matches)
{ {
$constraint = new SSListContains($matches); $constraint = new SSListContains($matches);
@ -65,10 +65,9 @@ class SSListContainsTest extends SapphireTest
} }
/** /**
* @dataProvider provideInvalidMatchesForList()
*
* @param $matches * @param $matches
*/ */
#[DataProvider('provideInvalidMatchesForList')]
public function testEvaluateListDoesNotMatchWrongMatches($matches) public function testEvaluateListDoesNotMatchWrongMatches($matches)
{ {
$constraint = new SSListContains($matches); $constraint = new SSListContains($matches);

View File

@ -1,86 +0,0 @@
<?php
namespace SilverStripe\Dev\Tests;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\SSListExporter;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\Security\Member;
use SilverStripe\View\ArrayData;
class SSListExporterTest extends SapphireTest
{
/**
* @var SSListExporter
*/
private $exporter;
protected function setUp(): void
{
parent::setUp();
$this->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 = [
'ID' => 5,
'Foo' => 'Bar',
'Baz' => 'Boom',
'One' => 'Two'
];
$map = $this->exporter->toMap(DataObject::create($data, DataObject::CREATE_HYDRATED));
$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');
}
}

View File

@ -7,14 +7,22 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use SilverStripe\Security\Permission; use SilverStripe\Security\Permission;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\DataProviderExternal;
use SilverStripe\Dev\Exceptions\ExpectedErrorException;
use SilverStripe\Dev\Exceptions\ExpectedNoticeException;
use SilverStripe\Dev\Exceptions\ExpectedWarningException;
/**
* @sometag This is a test annotation used in the testGetAnnotations test
*/
class SapphireTestTest extends SapphireTest class SapphireTestTest extends SapphireTest
{ {
/** /**
* @return array * @return array
*/ */
public function provideResolveFixturePath() public static function provideResolveFixturePath()
{ {
return [ return [
'sameDirectory' => [ 'sameDirectory' => [
@ -40,9 +48,7 @@ class SapphireTestTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideResolveFixturePath')]
* @dataProvider provideResolveFixturePath
*/
public function testResolveFixturePath($expected, $path, $message) public function testResolveFixturePath($expected, $path, $message)
{ {
$this->assertEquals( $this->assertEquals(
@ -86,13 +92,10 @@ class SapphireTestTest extends SapphireTest
} }
/** /**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideAllMatchingList()
*
* @param $match * @param $match
* @param $itemsForList * @param $itemsForList
*
* @testdox Has assertion assertListAllMatch
*/ */
#[DataProviderExternal('\SilverStripe\Dev\Tests\SapphireTestTest\DataProvider', 'provideAllMatchingList')]
public function testAssertListAllMatch($match, $itemsForList, $message) public function testAssertListAllMatch($match, $itemsForList, $message)
{ {
$list = $this->generateArrayListFromItems($itemsForList); $list = $this->generateArrayListFromItems($itemsForList);
@ -117,13 +120,10 @@ class SapphireTestTest extends SapphireTest
} }
/** /**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideNotMatchingList()
*
* @param $match * @param $match
* @param $itemsForList * @param $itemsForList
*
* @testdox assertion assertListAllMatch fails when not all items are matching
*/ */
#[DataProviderExternal('\SilverStripe\Dev\Tests\SapphireTestTest\DataProvider', 'provideNotMatchingList')]
public function testAssertListAllMatchFailsWhenNotMatchingAllItems($match, $itemsForList) public function testAssertListAllMatchFailsWhenNotMatchingAllItems($match, $itemsForList)
{ {
$this->expectException(ExpectationFailedException::class); $this->expectException(ExpectationFailedException::class);
@ -133,13 +133,10 @@ class SapphireTestTest extends SapphireTest
} }
/** /**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideEqualListsWithEmptyList()
*
* @param $matches * @param $matches
* @param $itemsForList * @param $itemsForList
*
* @testdox Has assertion assertListContains
*/ */
#[DataProviderExternal('\SilverStripe\Dev\Tests\SapphireTestTest\DataProvider', 'provideEqualListsWithEmptyList')]
public function testAssertListContains($matches, $itemsForList) public function testAssertListContains($matches, $itemsForList)
{ {
$list = $this->generateArrayListFromItems($itemsForList); $list = $this->generateArrayListFromItems($itemsForList);
@ -151,12 +148,10 @@ class SapphireTestTest extends SapphireTest
} }
/** /**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideNotContainingList
* @testdox assertion assertListEquals fails on non equal Lists
*
* @param $matches * @param $matches
* @param $itemsForList array * @param $itemsForList array
*/ */
#[DataProviderExternal('\SilverStripe\Dev\Tests\SapphireTestTest\DataProvider', 'provideNotContainingList')]
public function testAssertListContainsFailsIfListDoesNotContainMatch($matches, $itemsForList) public function testAssertListContainsFailsIfListDoesNotContainMatch($matches, $itemsForList)
{ {
$this->expectException(ExpectationFailedException::class); $this->expectException(ExpectationFailedException::class);
@ -169,13 +164,10 @@ class SapphireTestTest extends SapphireTest
} }
/** /**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideNotContainingList
*
* @testdox Has assertion assertListNotContains
*
* @param $matches * @param $matches
* @param $itemsForList * @param $itemsForList
*/ */
#[DataProviderExternal('\SilverStripe\Dev\Tests\SapphireTestTest\DataProvider', 'provideNotContainingList')]
public function testAssertListNotContains($matches, $itemsForList) public function testAssertListNotContains($matches, $itemsForList)
{ {
$list = $this->generateArrayListFromItems($itemsForList); $list = $this->generateArrayListFromItems($itemsForList);
@ -184,13 +176,10 @@ class SapphireTestTest extends SapphireTest
} }
/** /**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideEqualLists
*
* @param $matches * @param $matches
* @param $itemsForList * @param $itemsForList
*
* @testdox assertion assertListNotContains throws a exception when a matching item is found in the list
*/ */
#[DataProviderExternal('\SilverStripe\Dev\Tests\SapphireTestTest\DataProvider', 'provideEqualLists')]
public function testAssertListNotContainsFailsWhenListContainsAMatch($matches, $itemsForList) public function testAssertListNotContainsFailsWhenListContainsAMatch($matches, $itemsForList)
{ {
$this->expectException(ExpectationFailedException::class); $this->expectException(ExpectationFailedException::class);
@ -203,12 +192,10 @@ class SapphireTestTest extends SapphireTest
} }
/** /**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideEqualListsWithEmptyList()
* @testdox Has assertion assertListEquals
*
* @param $matches * @param $matches
* @param $itemsForList * @param $itemsForList
*/ */
#[DataProviderExternal('\SilverStripe\Dev\Tests\SapphireTestTest\DataProvider', 'provideEqualListsWithEmptyList')]
public function testAssertListEquals($matches, $itemsForList) public function testAssertListEquals($matches, $itemsForList)
{ {
$list = $this->generateArrayListFromItems($itemsForList); $list = $this->generateArrayListFromItems($itemsForList);
@ -217,12 +204,10 @@ class SapphireTestTest extends SapphireTest
} }
/** /**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideNonEqualLists
* @testdox assertion assertListEquals fails on non equal Lists
*
* @param $matches * @param $matches
* @param $itemsForList * @param $itemsForList
*/ */
#[DataProviderExternal('\SilverStripe\Dev\Tests\SapphireTestTest\DataProvider', 'provideNonEqualLists')]
public function testAssertListEqualsFailsOnNonEqualLists($matches, $itemsForList) public function testAssertListEqualsFailsOnNonEqualLists($matches, $itemsForList)
{ {
$this->expectException(ExpectationFailedException::class); $this->expectException(ExpectationFailedException::class);
@ -230,4 +215,79 @@ class SapphireTestTest extends SapphireTest
$this->assertListEquals($matches, $list); $this->assertListEquals($matches, $list);
} }
/**
* This test intentionally has non-sensical annotations to test the parser
*
* @lorem ipsum
* @param $one something
* @param $two else
*/
public function testGetAnnotations(): void
{
$this->assertSame([
'method' => [
'lorem' => [
'ipsum'
],
'param' => [
'$one something',
'$two else',
],
],
'class' => [
'sometag' => [
'This is a test annotation used in the testGetAnnotations test'
],
],
], $this->getAnnotations());
}
#[DataProvider('provideEnableErrorHandler')]
public function testEnableErrorHandler(int $errno, ?string $expectedClass): void
{
$this->enableErrorHandler();
$bool = false;
if ($expectedClass) {
$this->expectException($expectedClass);
$this->expectExceptionMessage('test');
}
if ($errno === E_USER_DEPRECATED) {
// Prevent deprecation notices from being displayed
set_error_handler(function ($errno, $errstr) use (&$bool) {
if ($errno === E_USER_DEPRECATED) {
$bool = true;
}
});
trigger_error('test', $errno);
}
trigger_error('test', $errno);
if ($errno === E_USER_DEPRECATED) {
restore_error_handler();
$this->assertTrue($bool);
}
}
public static function provideEnableErrorHandler(): array
{
// Only E_USER_* errors can be triggered, so that's all that's being tested
return [
'error' => [
'errno' => E_USER_ERROR,
'expectedClass' => ExpectedErrorException::class,
],
'notice' => [
'errno' => E_USER_NOTICE,
'expectedClass' => ExpectedNoticeException::class,
],
'warning' => [
'errno' => E_USER_WARNING,
'expectedClass' => ExpectedWarningException::class,
],
'deprecated' => [
'errno' => E_USER_DEPRECATED,
'expectedClass' => null,
],
];
}
} }

View File

@ -8,6 +8,7 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\Validation\RelationValidationService; use SilverStripe\Dev\Validation\RelationValidationService;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataObjectSchema; use SilverStripe\ORM\DataObjectSchema;
use PHPUnit\Framework\Attributes\DataProvider;
class RelationValidationTest extends SapphireTest class RelationValidationTest extends SapphireTest
{ {
@ -26,8 +27,8 @@ class RelationValidationTest extends SapphireTest
* @param string|null $field * @param string|null $field
* @param array $value * @param array $value
* @param array $expected * @param array $expected
* @dataProvider validateCasesProvider
*/ */
#[DataProvider('validateCasesProvider')]
public function testValidation(?string $class, ?string $field, array $value, array $expected): void public function testValidation(?string $class, ?string $field, array $value, array $expected): void
{ {
if ($class && $field) { if ($class && $field) {
@ -49,8 +50,8 @@ class RelationValidationTest extends SapphireTest
* @param string|null $relation * @param string|null $relation
* @param array $config * @param array $config
* @param bool $expected * @param bool $expected
* @dataProvider ignoredClassesProvider
*/ */
#[DataProvider('ignoredClassesProvider')]
public function testIgnoredClass(string $class, ?string $relation, array $config, bool $expected): void public function testIgnoredClass(string $class, ?string $relation, array $config, bool $expected): void
{ {
if (!class_exists($class)) { if (!class_exists($class)) {
@ -67,7 +68,7 @@ class RelationValidationTest extends SapphireTest
$this->assertEquals($expected, $result); $this->assertEquals($expected, $result);
} }
public function validateCasesProvider(): array public static function validateCasesProvider(): array
{ {
return [ return [
'correct setup' => [ 'correct setup' => [
@ -272,7 +273,7 @@ class RelationValidationTest extends SapphireTest
]; ];
} }
public function ignoredClassesProvider(): array public static function ignoredClassesProvider(): array
{ {
return [ return [
'class default' => [ 'class default' => [

View File

@ -7,6 +7,7 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\Tests\ViewableDataContainsTest\TestObject; use SilverStripe\Dev\Tests\ViewableDataContainsTest\TestObject;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use PHPUnit\Framework\Attributes\DataProvider;
class ViewableDataContainsTest extends SapphireTest class ViewableDataContainsTest extends SapphireTest
{ {
@ -15,7 +16,7 @@ class ViewableDataContainsTest extends SapphireTest
'Surname' => 'Schommer' 'Surname' => 'Schommer'
]; ];
public function provideMatchesForList() public static function provideMatchesForList()
{ {
return [ return [
[ [
@ -31,7 +32,7 @@ class ViewableDataContainsTest extends SapphireTest
} }
public function provideInvalidMatchesForList() public static function provideInvalidMatchesForList()
{ {
return [ return [
[ [
@ -47,10 +48,9 @@ class ViewableDataContainsTest extends SapphireTest
} }
/** /**
* @dataProvider provideMatchesForList()
*
* @param $match * @param $match
*/ */
#[DataProvider('provideMatchesForList')]
public function testEvaluateMatchesCorrectlyArrayData($match) public function testEvaluateMatchesCorrectlyArrayData($match)
{ {
$constraint = new ViewableDataContains($match); $constraint = new ViewableDataContains($match);
@ -61,10 +61,9 @@ class ViewableDataContainsTest extends SapphireTest
} }
/** /**
* @dataProvider provideMatchesForList()
*
* @param $match * @param $match
*/ */
#[DataProvider('provideMatchesForList')]
public function testEvaluateMatchesCorrectlyDataObject($match) public function testEvaluateMatchesCorrectlyDataObject($match)
{ {
$constraint = new ViewableDataContains($match); $constraint = new ViewableDataContains($match);
@ -75,10 +74,9 @@ class ViewableDataContainsTest extends SapphireTest
} }
/** /**
* @dataProvider provideInvalidMatchesForList()
*
* @param $matches * @param $matches
*/ */
#[DataProvider('provideInvalidMatchesForList')]
public function testEvaluateDoesNotMatchWrongMatchInArrayData($match) public function testEvaluateDoesNotMatchWrongMatchInArrayData($match)
{ {
$constraint = new ViewableDataContains($match); $constraint = new ViewableDataContains($match);
@ -89,10 +87,9 @@ class ViewableDataContainsTest extends SapphireTest
} }
/** /**
* @dataProvider provideInvalidMatchesForList()
*
* @param $matches * @param $matches
*/ */
#[DataProvider('provideInvalidMatchesForList')]
public function testEvaluateDoesNotMatchWrongMatchInDataObject($match) public function testEvaluateDoesNotMatchWrongMatchInDataObject($match)
{ {
$constraint = new ViewableDataContains($match); $constraint = new ViewableDataContains($match);

View File

@ -14,6 +14,7 @@ use SilverStripe\Security\Member;
use SilverStripe\Security\PasswordValidator; use SilverStripe\Security\PasswordValidator;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use Closure; use Closure;
use PHPUnit\Framework\Attributes\DataProvider;
class ConfirmedPasswordFieldTest extends SapphireTest class ConfirmedPasswordFieldTest extends SapphireTest
{ {
@ -185,8 +186,8 @@ class ConfirmedPasswordFieldTest extends SapphireTest
* @param int|null $maxLength * @param int|null $maxLength
* @param bool $expectValid * @param bool $expectValid
* @param string $expectedMessage * @param string $expectedMessage
* @dataProvider lengthValidationProvider
*/ */
#[DataProvider('lengthValidationProvider')]
public function testLengthValidation($minLength, $maxLength, $expectValid, $expectedMessage = '') public function testLengthValidation($minLength, $maxLength, $expectValid, $expectedMessage = '')
{ {
$field = new ConfirmedPasswordField('Test', 'Testing', [ $field = new ConfirmedPasswordField('Test', 'Testing', [
@ -208,7 +209,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest
/** /**
* @return array[] * @return array[]
*/ */
public function lengthValidationProvider() public static function lengthValidationProvider()
{ {
return [ return [
'valid: within min and max' => [3, 8, true], 'valid: within min and max' => [3, 8, true],
@ -385,9 +386,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest
$this->assertCount(2, $field->getChildren(), 'Current password field should not be removed'); $this->assertCount(2, $field->getChildren(), 'Current password field should not be removed');
} }
/** #[DataProvider('provideSetCanBeEmptySaveInto')]
* @dataProvider provideSetCanBeEmptySaveInto
*/
public function testSetCanBeEmptySaveInto(bool $generateRandomPasswordOnEmpty, ?string $expected) public function testSetCanBeEmptySaveInto(bool $generateRandomPasswordOnEmpty, ?string $expected)
{ {
$field = new ConfirmedPasswordField('Test', 'Change it'); $field = new ConfirmedPasswordField('Test', 'Change it');
@ -403,7 +402,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest
$this->assertSame($expected, $field->Value()); $this->assertSame($expected, $field->Value());
} }
public function provideSetCanBeEmptySaveInto(): array public static function provideSetCanBeEmptySaveInto(): array
{ {
return [ return [
[ [
@ -430,7 +429,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest
$this->assertNotEmpty($passwordField->RightTitle()); $this->assertNotEmpty($passwordField->RightTitle());
} }
public function provideRequired() public static function provideRequired()
{ {
return [ return [
'can be empty' => [true], 'can be empty' => [true],
@ -438,9 +437,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideRequired')]
* @dataProvider provideRequired
*/
public function testRequired(bool $canBeEmpty) public function testRequired(bool $canBeEmpty)
{ {
$field = new ConfirmedPasswordField('Test'); $field = new ConfirmedPasswordField('Test');
@ -448,7 +445,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest
$this->assertSame(!$canBeEmpty, $field->Required()); $this->assertSame(!$canBeEmpty, $field->Required());
} }
public function provideChildFieldsAreRequired() public static function provideChildFieldsAreRequired()
{ {
return [ return [
'not required' => [ 'not required' => [
@ -478,9 +475,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideChildFieldsAreRequired')]
* @dataProvider provideChildFieldsAreRequired
*/
public function testChildFieldsAreRequired(bool $canBeEmpty, bool $required, bool $childrenRequired, bool $expectRequired) public function testChildFieldsAreRequired(bool $canBeEmpty, bool $required, bool $childrenRequired, bool $expectRequired)
{ {
// CWP front-end templates break this logic - but there's no easy fix for that. // CWP front-end templates break this logic - but there's no easy fix for that.

View File

@ -19,7 +19,7 @@ class DatalessFieldTest extends SapphireTest
/** @var DatalessField|MockObject $mock */ /** @var DatalessField|MockObject $mock */
$mock = $this->getMockBuilder(DatalessField::class) $mock = $this->getMockBuilder(DatalessField::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['Field']) ->onlyMethods(['Field'])
->getMock(); ->getMock();
$properties = [ $properties = [

View File

@ -13,6 +13,7 @@ use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form; use SilverStripe\Forms\Form;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\ORM\Map; use SilverStripe\ORM\Map;
use PHPUnit\Framework\Attributes\DataProvider;
class DropdownFieldTest extends SapphireTest class DropdownFieldTest extends SapphireTest
{ {
@ -410,9 +411,8 @@ class DropdownFieldTest extends SapphireTest
/** /**
* The Field() method should be able to handle arrays as values in an edge case. If it couldn't handle it then * The Field() method should be able to handle arrays as values in an edge case. If it couldn't handle it then
* this test would trigger an array to string conversion PHP notice * this test would trigger an array to string conversion PHP notice
*
* @dataProvider arrayValueProvider
*/ */
#[DataProvider('arrayValueProvider')]
public function testDropdownWithArrayValues($value) public function testDropdownWithArrayValues($value)
{ {
$field = $this->createDropdownField(); $field = $this->createDropdownField();
@ -424,7 +424,7 @@ class DropdownFieldTest extends SapphireTest
/** /**
* @return array * @return array
*/ */
public function arrayValueProvider() public static function arrayValueProvider()
{ {
return [ return [
[[]], [[]],

View File

@ -7,12 +7,13 @@ use SilverStripe\Forms\EmailField;
use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\FieldsValidator; use SilverStripe\Forms\FieldsValidator;
use SilverStripe\Forms\Form; use SilverStripe\Forms\Form;
use PHPUnit\Framework\Attributes\DataProvider;
class FieldsValidatorTest extends SapphireTest class FieldsValidatorTest extends SapphireTest
{ {
protected $usesDatabase = false; protected $usesDatabase = false;
public function provideValidation() public static function provideValidation()
{ {
return [ return [
'missing values arent invalid' => [ 'missing values arent invalid' => [
@ -50,9 +51,7 @@ class FieldsValidatorTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideValidation')]
* @dataProvider provideValidation
*/
public function testValidation(array $values, bool $isValid) public function testValidation(array $values, bool $isValid)
{ {
$fieldList = new FieldList([ $fieldList = new FieldList([

View File

@ -16,7 +16,6 @@ class FileFieldTest extends FunctionalTest
{ {
/** /**
* Test a valid upload of a required file in a form. Error is set to 0, as the upload went well * Test a valid upload of a required file in a form. Error is set to 0, as the upload went well
*
*/ */
public function testUploadRequiredFile() public function testUploadRequiredFile()
{ {

View File

@ -38,6 +38,7 @@ use SilverStripe\Security\PermissionCheckboxSetField;
use SilverStripe\Security\PermissionCheckboxSetField_Readonly; use SilverStripe\Security\PermissionCheckboxSetField_Readonly;
use SilverStripe\Forms\SearchableMultiDropdownField; use SilverStripe\Forms\SearchableMultiDropdownField;
use SilverStripe\Forms\SearchableDropdownField; use SilverStripe\Forms\SearchableDropdownField;
use PHPUnit\Framework\Attributes\DataProvider;
class FormFieldTest extends SapphireTest class FormFieldTest extends SapphireTest
{ {
@ -228,7 +229,7 @@ class FormFieldTest extends SapphireTest
/** /**
* Covering all potential inputs for Convert::raw2xml * Covering all potential inputs for Convert::raw2xml
*/ */
public function escapeHtmlDataProvider() public static function escapeHtmlDataProvider()
{ {
return [ return [
['<html>'], ['<html>'],
@ -238,8 +239,8 @@ class FormFieldTest extends SapphireTest
} }
/** /**
* @dataProvider escapeHtmlDataProvider
**/ **/
#[DataProvider('escapeHtmlDataProvider')]
public function testGetAttributesEscapeHtml($value) public function testGetAttributesEscapeHtml($value)
{ {
$key = bin2hex(random_bytes(4)); $key = bin2hex(random_bytes(4));
@ -258,9 +259,7 @@ class FormFieldTest extends SapphireTest
$this->assertFalse(strpos($html ?? '', '<html>')); $this->assertFalse(strpos($html ?? '', '<html>'));
} }
/** #[DataProvider('escapeHtmlDataProvider')]
* @dataProvider escapeHtmlDataProvider
*/
public function testDebugEscapeHtml($value) public function testDebugEscapeHtml($value)
{ {
$field = new FormField('<html>', '<html>', '<html>'); $field = new FormField('<html>', '<html>', '<html>');
@ -606,7 +605,7 @@ class FormFieldTest extends SapphireTest
->getMock(); ->getMock();
$mock->expects($invocationRule = $this->once()) $mock->expects($invocationRule = $this->once())
->method('extendValidationResult') ->method('extendValidationResult')
->will($this->returnValue(true)); ->willReturn(true);
$isValid = $mock->validate(new RequiredFields()); $isValid = $mock->validate(new RequiredFields());
$this->assertTrue($isValid, "$formFieldClass should be valid"); $this->assertTrue($isValid, "$formFieldClass should be valid");
@ -651,8 +650,8 @@ class FormFieldTest extends SapphireTest
/** /**
* @param string $name * @param string $name
* @param string $expected * @param string $expected
* @dataProvider nameToLabelProvider
*/ */
#[DataProvider('nameToLabelProvider')]
public function testNameToLabel($name, $expected) public function testNameToLabel($name, $expected)
{ {
$this->assertSame($expected, FormField::name_to_label($name)); $this->assertSame($expected, FormField::name_to_label($name));
@ -661,7 +660,7 @@ class FormFieldTest extends SapphireTest
/** /**
* @return array[] * @return array[]
*/ */
public function nameToLabelProvider() public static function nameToLabelProvider()
{ {
return [ return [
['TotalAmount', 'Total amount'], ['TotalAmount', 'Total amount'],

View File

@ -17,6 +17,7 @@ use SilverStripe\Forms\Tests\FormScaffolderTest\ParentModel;
use SilverStripe\Forms\Tests\FormScaffolderTest\ParentChildJoin; use SilverStripe\Forms\Tests\FormScaffolderTest\ParentChildJoin;
use SilverStripe\Forms\Tests\FormScaffolderTest\Tag; use SilverStripe\Forms\Tests\FormScaffolderTest\Tag;
use SilverStripe\Forms\TimeField; use SilverStripe\Forms\TimeField;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Tests for DataObject FormField scaffolding * Tests for DataObject FormField scaffolding
@ -171,7 +172,7 @@ class FormScaffolderTest extends SapphireTest
$this->assertFalse($fields->hasTabSet(), 'getFrontEndFields() doesnt produce a TabSet by default'); $this->assertFalse($fields->hasTabSet(), 'getFrontEndFields() doesnt produce a TabSet by default');
} }
public function provideScaffoldRelationFormFields() public static function provideScaffoldRelationFormFields()
{ {
$scenarios = [ $scenarios = [
'ignore no relations' => [ 'ignore no relations' => [
@ -193,9 +194,7 @@ class FormScaffolderTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideScaffoldRelationFormFields')]
* @dataProvider provideScaffoldRelationFormFields
*/
public function testScaffoldRelationFormFields(bool $includeInOwnTab, array $ignoreRelations) public function testScaffoldRelationFormFields(bool $includeInOwnTab, array $ignoreRelations)
{ {
$parent = $this->objFromFixture(ParentModel::class, 'parent1'); $parent = $this->objFromFixture(ParentModel::class, 'parent1');
@ -271,31 +270,29 @@ class FormScaffolderTest extends SapphireTest
$this->assertSame(['Tags'], $fields->column('Name')); $this->assertSame(['Tags'], $fields->column('Name'));
} }
public function provideTabs(): array public static function provideTabs(): array
{ {
return [ return [
'only main tab' => [ 'only main tab' => [
'tabs' => true, 'tabbed' => true,
'mainTabOnly' => true, 'mainTabOnly' => true,
], ],
'all tabs, all fields' => [ 'all tabs, all fields' => [
'tabs' => true, 'tabbed' => true,
'mainTabOnly' => false, 'mainTabOnly' => false,
], ],
'no tabs, no fields' => [ 'no tabs, no fields' => [
'tabs' => false, 'tabbed' => false,
'mainTabOnly' => true, 'mainTabOnly' => true,
], ],
'no tabs, all fields' => [ 'no tabs, all fields' => [
'tabs' => false, 'tabbed' => false,
'mainTabOnly' => false, 'mainTabOnly' => false,
], ],
]; ];
} }
/** #[DataProvider('provideTabs')]
* @dataProvider provideTabs
*/
public function testTabs(bool $tabbed, bool $mainTabOnly): void public function testTabs(bool $tabbed, bool $mainTabOnly): void
{ {
$parent = $this->objFromFixture(ParentModel::class, 'parent1'); $parent = $this->objFromFixture(ParentModel::class, 'parent1');

View File

@ -16,6 +16,7 @@ use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\PopoverField; use SilverStripe\Forms\PopoverField;
use SilverStripe\Forms\FormField; use SilverStripe\Forms\FormField;
use LogicException; use LogicException;
use PHPUnit\Framework\Attributes\DataProvider;
class FormSchemaTest extends SapphireTest class FormSchemaTest extends SapphireTest
{ {
@ -41,9 +42,7 @@ class FormSchemaTest extends SapphireTest
$this->assertEquals($expected, $schema); $this->assertEquals($expected, $schema);
} }
/** #[DataProvider('provideGetSchemaException')]
* @dataProvider provideGetSchemaException
*/
public function testGetSchemaException(string $field, bool $expectException): void public function testGetSchemaException(string $field, bool $expectException): void
{ {
$fields = []; $fields = [];
@ -66,7 +65,7 @@ class FormSchemaTest extends SapphireTest
$formSchema->getSchema($form); $formSchema->getSchema($form);
} }
public function provideGetSchemaException(): array public static function provideGetSchemaException(): array
{ {
return [ return [
[ [

View File

@ -33,6 +33,7 @@ use SilverStripe\Security\RandomGenerator;
use SilverStripe\Security\SecurityToken; use SilverStripe\Security\SecurityToken;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use PHPUnit\Framework\Attributes\DataProvider;
class FormTest extends FunctionalTest class FormTest extends FunctionalTest
{ {
@ -68,7 +69,7 @@ class FormTest extends FunctionalTest
/** /**
* @return array * @return array
*/ */
public function boolDataProvider() public static function boolDataProvider()
{ {
return [ return [
[false], [false],
@ -76,7 +77,7 @@ class FormTest extends FunctionalTest
]; ];
} }
public function formMessageDataProvider() public static function formMessageDataProvider()
{ {
return [ return [
[ [
@ -100,40 +101,40 @@ class FormTest extends FunctionalTest
]; ];
} }
public function formMessageExceptionsDataProvider() public static function formMessageExceptionsDataProvider()
{ {
return [ return [
[ [
'message_1' => [ 'message1' => [
'val' => 'Just a string', 'val' => 'Just a string',
'type' => ValidationResult::TYPE_ERROR, 'type' => ValidationResult::TYPE_ERROR,
'cast' => ValidationResult::CAST_TEXT, 'cast' => ValidationResult::CAST_TEXT,
], ],
'message_2' => [ 'message2' => [
'val' => 'This is a good message', 'val' => 'This is a good message',
'type' => ValidationResult::TYPE_GOOD, 'type' => ValidationResult::TYPE_GOOD,
'cast' => ValidationResult::CAST_TEXT, 'cast' => ValidationResult::CAST_TEXT,
], ],
], ],
[ [
'message_1' => [ 'message1' => [
'val' => 'This is a good message', 'val' => 'This is a good message',
'type' => ValidationResult::TYPE_GOOD, 'type' => ValidationResult::TYPE_GOOD,
'cast' => ValidationResult::CAST_TEXT, 'cast' => ValidationResult::CAST_TEXT,
], ],
'message_2' => [ 'message2' => [
'val' => 'HTML is the future of the web', 'val' => 'HTML is the future of the web',
'type' => ValidationResult::TYPE_GOOD, 'type' => ValidationResult::TYPE_GOOD,
'cast' => ValidationResult::CAST_HTML, 'cast' => ValidationResult::CAST_HTML,
], ],
], ],
[ [
'message_1' => [ 'message1' => [
'val' => 'This is a good message', 'val' => 'This is a good message',
'type' => ValidationResult::TYPE_GOOD, 'type' => ValidationResult::TYPE_GOOD,
'cast' => ValidationResult::CAST_TEXT, 'cast' => ValidationResult::CAST_TEXT,
], ],
'message_2' => [ 'message2' => [
'val' => 'HTML is the future of the web', 'val' => 'HTML is the future of the web',
'type' => ValidationResult::TYPE_GOOD, 'type' => ValidationResult::TYPE_GOOD,
'cast' => ValidationResult::CAST_HTML, 'cast' => ValidationResult::CAST_HTML,
@ -732,7 +733,7 @@ class FormTest extends FunctionalTest
); );
} }
public function provideFormsSet() public static function provideFormsSet()
{ {
return [ return [
'with security token' => 'with security token' =>
@ -756,9 +757,7 @@ class FormTest extends FunctionalTest
]; ];
} }
/** #[DataProvider('provideFormsSet')]
* @dataProvider provideFormsSet
*/
public function testSubmitFormWithSpecifiedParameters( public function testSubmitFormWithSpecifiedParameters(
array $formData, array $formData,
?int $statusCode, ?int $statusCode,
@ -1097,9 +1096,7 @@ class FormTest extends FunctionalTest
); );
} }
/** #[DataProvider('formMessageDataProvider')]
* @dataProvider formMessageDataProvider
*/
public function testFieldMessageAppend($messages) public function testFieldMessageAppend($messages)
{ {
$form = $this->getStubForm(); $form = $this->getStubForm();
@ -1115,9 +1112,7 @@ class FormTest extends FunctionalTest
} }
} }
/** #[DataProvider('formMessageExceptionsDataProvider')]
* @dataProvider formMessageExceptionsDataProvider
*/
public function testFieldMessageAppendExceptions(array $message1, array $message2, bool $force = false) public function testFieldMessageAppendExceptions(array $message1, array $message2, bool $force = false)
{ {
$form = $this->getStubForm(); $form = $this->getStubForm();
@ -1166,9 +1161,9 @@ class FormTest extends FunctionalTest
} }
/** /**
* @dataProvider boolDataProvider
* @param bool $allow * @param bool $allow
*/ */
#[DataProvider('boolDataProvider')]
public function testPasswordPostback($allow) public function testPasswordPostback($allow)
{ {
$form = $this->getStubForm(); $form = $this->getStubForm();

View File

@ -125,7 +125,7 @@ class GridFieldAddNewButtonTest extends SapphireTest
protected function mockSingleton($class) protected function mockSingleton($class)
{ {
$mock = $this->getMockBuilder($class) $mock = $this->getMockBuilder($class)
->setMethods(['canCreate']) ->onlyMethods(['canCreate'])
->getMock(); ->getMock();
Injector::inst()->registerService($mock, $class); Injector::inst()->registerService($mock, $class);

View File

@ -15,9 +15,6 @@ use stdClass;
class GridFieldDataColumnsTest extends SapphireTest class GridFieldDataColumnsTest extends SapphireTest
{ {
/**
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::getDisplayFields
*/
public function testGridFieldGetDefaultDisplayFields() public function testGridFieldGetDefaultDisplayFields()
{ {
$obj = new GridField('testfield', 'testfield', Member::get()); $obj = new GridField('testfield', 'testfield', Member::get());
@ -26,9 +23,6 @@ class GridFieldDataColumnsTest extends SapphireTest
$this->assertEquals($expected, $columns->getDisplayFields($obj)); $this->assertEquals($expected, $columns->getDisplayFields($obj));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::getDisplayFields
*/
public function testGridFieldGetDisplayFieldsWithArrayList() public function testGridFieldGetDisplayFieldsWithArrayList()
{ {
$list = new ArrayList([new ArrayData(['Title' => 'My Item'])]); $list = new ArrayList([new ArrayData(['Title' => 'My Item'])]);
@ -39,10 +33,6 @@ class GridFieldDataColumnsTest extends SapphireTest
$this->assertEquals($expected, $columns->getDisplayFields($obj)); $this->assertEquals($expected, $columns->getDisplayFields($obj));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::setDisplayFields
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::getDisplayFields
*/
public function testGridFieldCustomDisplayFields() public function testGridFieldCustomDisplayFields()
{ {
$obj = new GridField('testfield', 'testfield', Member::get()); $obj = new GridField('testfield', 'testfield', Member::get());
@ -52,10 +42,6 @@ class GridFieldDataColumnsTest extends SapphireTest
$this->assertEquals($expected, $columns->getDisplayFields($obj)); $this->assertEquals($expected, $columns->getDisplayFields($obj));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::setDisplayFields
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::getDisplayFields
*/
public function testGridFieldDisplayFieldsWithBadArguments() public function testGridFieldDisplayFieldsWithBadArguments()
{ {
$this->expectException(InvalidArgumentException::class); $this->expectException(InvalidArgumentException::class);
@ -64,10 +50,6 @@ class GridFieldDataColumnsTest extends SapphireTest
$columns->setDisplayFields(new stdClass()); $columns->setDisplayFields(new stdClass());
} }
/**
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::getFieldCasting
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::setFieldCasting
*/
public function testFieldCasting() public function testFieldCasting()
{ {
$obj = new GridField('testfield', 'testfield'); $obj = new GridField('testfield', 'testfield');
@ -77,10 +59,6 @@ class GridFieldDataColumnsTest extends SapphireTest
$this->assertEquals(["MyShortText"=>"Text->FirstSentence"], $columns->getFieldCasting()); $this->assertEquals(["MyShortText"=>"Text->FirstSentence"], $columns->getFieldCasting());
} }
/**
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::getFieldFormatting
* @covers \SilverStripe\Forms\GridField\GridFieldDataColumns::setFieldFormatting
*/
public function testFieldFormatting() public function testFieldFormatting()
{ {
$obj = new GridField('testfield', 'testfield'); $obj = new GridField('testfield', 'testfield');

View File

@ -26,6 +26,7 @@ use SilverStripe\ORM\ValidationException;
use SilverStripe\Security\Security; use SilverStripe\Security\Security;
use SilverStripe\Security\SecurityToken; use SilverStripe\Security\SecurityToken;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use PHPUnit\Framework\Attributes\DataProvider;
class GridFieldDeleteActionTest extends SapphireTest class GridFieldDeleteActionTest extends SapphireTest
{ {
@ -235,7 +236,7 @@ class GridFieldDeleteActionTest extends SapphireTest
$this->assertNull($group, 'A menu group does not exist when the user cannot delete'); $this->assertNull($group, 'A menu group does not exist when the user cannot delete');
} }
public function provideHandleActionThrowsException() public static function provideHandleActionThrowsException()
{ {
return [ return [
'unlinks relation' => [true], 'unlinks relation' => [true],
@ -243,9 +244,7 @@ class GridFieldDeleteActionTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideHandleActionThrowsException')]
* @dataProvider provideHandleActionThrowsException
*/
public function testHandleActionThrowsException(bool $unlinkRelation) public function testHandleActionThrowsException(bool $unlinkRelation)
{ {
$component = new GridFieldDeleteAction(); $component = new GridFieldDeleteAction();
@ -267,7 +266,7 @@ class GridFieldDeleteActionTest extends SapphireTest
$component->handleAction($gridField, $secondArg, ['RecordID' => 1], []); $component->handleAction($gridField, $secondArg, ['RecordID' => 1], []);
} }
public function provideGetRemoveActionThrowsException() public static function provideGetRemoveActionThrowsException()
{ {
return [ return [
'removes relation' => [true], 'removes relation' => [true],
@ -275,9 +274,7 @@ class GridFieldDeleteActionTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideGetRemoveActionThrowsException')]
* @dataProvider provideGetRemoveActionThrowsException
*/
public function testGetRemoveActionThrowsException(bool $removeRelation) public function testGetRemoveActionThrowsException(bool $removeRelation)
{ {
$component = new GridFieldDeleteAction(); $component = new GridFieldDeleteAction();

View File

@ -26,6 +26,7 @@ use SilverStripe\Forms\Tests\GridField\GridFieldDetailFormTest\PolymorphicPeople
use SilverStripe\Forms\Tests\GridField\GridFieldDetailFormTest\TestController; use SilverStripe\Forms\Tests\GridField\GridFieldDetailFormTest\TestController;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use PHPUnit\Framework\Attributes\DataProvider;
class GridFieldDetailFormTest extends FunctionalTest class GridFieldDetailFormTest extends FunctionalTest
{ {
@ -496,7 +497,7 @@ class GridFieldDetailFormTest extends FunctionalTest
$this->autoFollowRedirection = $origAutoFollow; $this->autoFollowRedirection = $origAutoFollow;
} }
public function provideGetRecordFromRequestFindExisting() public static function provideGetRecordFromRequestFindExisting()
{ {
return [ return [
'No records' => [ 'No records' => [
@ -518,9 +519,7 @@ class GridFieldDetailFormTest extends FunctionalTest
]; ];
} }
/** #[DataProvider('provideGetRecordFromRequestFindExisting')]
* @dataProvider provideGetRecordFromRequestFindExisting
*/
public function testGetRecordFromRequestFindExisting(array $data, bool $hasRecord) public function testGetRecordFromRequestFindExisting(array $data, bool $hasRecord)
{ {
$controller = new TestController(); $controller = new TestController();
@ -538,7 +537,7 @@ class GridFieldDetailFormTest extends FunctionalTest
$this->assertSame($hasRecord, (bool) $reflectionMethod->invoke($component, $gridField, $request)); $this->assertSame($hasRecord, (bool) $reflectionMethod->invoke($component, $gridField, $request));
} }
public function provideGetRecordFromRequestCreateNew() public static function provideGetRecordFromRequestCreateNew()
{ {
// Note that in all of these scenarios a new record gets created, so it *shouldn't* matter what's already in there. // Note that in all of these scenarios a new record gets created, so it *shouldn't* matter what's already in there.
return [ return [
@ -554,9 +553,7 @@ class GridFieldDetailFormTest extends FunctionalTest
]; ];
} }
/** #[DataProvider('provideGetRecordFromRequestCreateNew')]
* @dataProvider provideGetRecordFromRequestCreateNew
*/
public function testGetRecordFromRequestCreateNew(array $data) public function testGetRecordFromRequestCreateNew(array $data)
{ {
$controller = new TestController(); $controller = new TestController();
@ -574,7 +571,7 @@ class GridFieldDetailFormTest extends FunctionalTest
$this->assertEquals(new ArrayDataWithID(['ID' => 0]), $reflectionMethod->invoke($component, $gridField, $request)); $this->assertEquals(new ArrayDataWithID(['ID' => 0]), $reflectionMethod->invoke($component, $gridField, $request));
} }
public function provideGetRecordFromRequestWithoutData() public static function provideGetRecordFromRequestWithoutData()
{ {
// Note that in all of these scenarios a new record gets created, so it *shouldn't* matter what's already in there. // Note that in all of these scenarios a new record gets created, so it *shouldn't* matter what's already in there.
return [ return [
@ -590,9 +587,7 @@ class GridFieldDetailFormTest extends FunctionalTest
]; ];
} }
/** #[DataProvider('provideGetRecordFromRequestWithoutData')]
* @dataProvider provideGetRecordFromRequestWithoutData
*/
public function testGetRecordFromRequestWithoutData(array $data) public function testGetRecordFromRequestWithoutData(array $data)
{ {
$controller = new TestController(); $controller = new TestController();

View File

@ -68,7 +68,6 @@ class GridFieldFilterHeaderTest extends SapphireTest
/** /**
* Tests that the appropriate filter headers are generated * Tests that the appropriate filter headers are generated
*
*/ */
public function testRenderHeaders() public function testRenderHeaders()
{ {

View File

@ -23,6 +23,7 @@ use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldViewButton; use SilverStripe\Forms\GridField\GridFieldViewButton;
use SilverStripe\Forms\Tests\GridField\GridFieldReadonlyTest\GridFieldViewButtonReplacement; use SilverStripe\Forms\Tests\GridField\GridFieldReadonlyTest\GridFieldViewButtonReplacement;
use SilverStripe\Versioned\VersionedGridFieldState\VersionedGridFieldState; use SilverStripe\Versioned\VersionedGridFieldState\VersionedGridFieldState;
use PHPUnit\Framework\Attributes\DataProvider;
class GridFieldReadonlyTest extends SapphireTest class GridFieldReadonlyTest extends SapphireTest
{ {
@ -33,7 +34,7 @@ class GridFieldReadonlyTest extends SapphireTest
Cheerleader::class, Cheerleader::class,
]; ];
public function provideReadOnlyTransformation(): array public static function provideReadOnlyTransformation(): array
{ {
return [ return [
[ [
@ -51,9 +52,8 @@ class GridFieldReadonlyTest extends SapphireTest
/** /**
* The CMS can set the value of a GridField to be a hasMany relation, which needs a readonly state. * The CMS can set the value of a GridField to be a hasMany relation, which needs a readonly state.
* This test ensures GridField has a readonly transformation. * This test ensures GridField has a readonly transformation.
*
* @dataProvider provideReadOnlyTransformation
*/ */
#[DataProvider('provideReadOnlyTransformation')]
public function testReadOnlyTransformation(?string $viewButtonClass) public function testReadOnlyTransformation(?string $viewButtonClass)
{ {
// Build a hasMany Relation via getComponents like ModelAdmin does. // Build a hasMany Relation via getComponents like ModelAdmin does.

View File

@ -31,7 +31,6 @@ class GridFieldSortableHeaderTest extends SapphireTest
/** /**
* Tests that the appropriate sortable headers are generated * Tests that the appropriate sortable headers are generated
*
*/ */
public function testRenderHeaders() public function testRenderHeaders()
{ {

View File

@ -57,19 +57,12 @@ class GridFieldTest extends SapphireTest
], ],
]; ];
/**
* @covers \SilverStripe\Forms\GridField\GridField::__construct
*/
public function testGridField() public function testGridField()
{ {
$obj = new GridField('testfield', 'testfield'); $obj = new GridField('testfield', 'testfield');
$this->assertTrue($obj instanceof GridField, 'Test that the constructor arguments are valid'); $this->assertTrue($obj instanceof GridField, 'Test that the constructor arguments are valid');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::__construct
* @covers \SilverStripe\Forms\GridField\GridField::getList
*/
public function testGridFieldSetList() public function testGridFieldSetList()
{ {
$list = ArrayList::create([1 => 'hello', 2 => 'goodbye']); $list = ArrayList::create([1 => 'hello', 2 => 'goodbye']);
@ -77,12 +70,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals($list, $obj->getList(), 'Testing getList'); $this->assertEquals($list, $obj->getList(), 'Testing getList');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::__construct
* @covers \SilverStripe\Forms\GridField\GridField::getConfig
* @covers \SilverStripe\Forms\GridField\GridFieldConfig_Base::__construct
* @covers \SilverStripe\Forms\GridField\GridFieldConfig::addComponent
*/
public function testGridFieldDefaultConfig() public function testGridFieldDefaultConfig()
{ {
$obj = new GridField('testfield', 'testfield'); $obj = new GridField('testfield', 'testfield');
@ -104,10 +91,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals($expectedComponents, $obj->getConfig()->getComponents(), 'Testing default Config'); $this->assertEquals($expectedComponents, $obj->getConfig()->getComponents(), 'Testing default Config');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridFieldConfig::__construct
* @covers \SilverStripe\Forms\GridField\GridFieldConfig::addComponent
*/
public function testGridFieldSetCustomConfig() public function testGridFieldSetCustomConfig()
{ {
@ -128,10 +111,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals($expectedComponents, $obj->getConfig()->getComponents(), 'Testing default Config'); $this->assertEquals($expectedComponents, $obj->getConfig()->getComponents(), 'Testing default Config');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getModelClass
* @covers \SilverStripe\Forms\GridField\GridField::setModelClass
*/
public function testGridFieldModelClass() public function testGridFieldModelClass()
{ {
$obj = new GridField('testfield', 'testfield', Member::get()); $obj = new GridField('testfield', 'testfield', Member::get());
@ -140,9 +119,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals(Group::class, $obj->getModelClass(), 'Should return Group'); $this->assertEquals(Group::class, $obj->getModelClass(), 'Should return Group');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getModelClass
*/
public function testGridFieldModelClassThrowsException() public function testGridFieldModelClassThrowsException()
{ {
$this->expectException(LogicException::class); $this->expectException(LogicException::class);
@ -150,10 +126,6 @@ class GridFieldTest extends SapphireTest
$obj->getModelClass(); $obj->getModelClass();
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::setList
* @covers \SilverStripe\Forms\GridField\GridField::getList
*/
public function testSetAndGetList() public function testSetAndGetList()
{ {
$list = Member::get(); $list = Member::get();
@ -164,9 +136,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals($arrayList, $obj->getList()); $this->assertEquals($arrayList, $obj->getList());
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getState
*/
public function testGetState() public function testGetState()
{ {
$obj = new GridField('testfield', 'testfield'); $obj = new GridField('testfield', 'testfield');
@ -176,10 +145,6 @@ class GridFieldTest extends SapphireTest
/** /**
* Tests usage of nested GridState values * Tests usage of nested GridState values
*
* @covers \SilverStripe\Forms\GridField\GridState_Data::__get
* @covers \SilverStripe\Forms\GridField\GridState_Data::__call
* @covers \SilverStripe\Forms\GridField\GridState_Data::getData
*/ */
public function testGetStateData() public function testGetStateData()
{ {
@ -220,9 +185,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals(10, $obj->State->Nested->DeeperNested->DataValue(10)); $this->assertEquals(10, $obj->State->Nested->DeeperNested->DataValue(10));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumns
*/
public function testGetColumns() public function testGetColumns()
{ {
$obj = new GridField('testfield', 'testfield', Member::get()); $obj = new GridField('testfield', 'testfield', Member::get());
@ -234,18 +196,12 @@ class GridFieldTest extends SapphireTest
$this->assertEquals($expected, $obj->getColumns()); $this->assertEquals($expected, $obj->getColumns());
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnCount
*/
public function testGetColumnCount() public function testGetColumnCount()
{ {
$obj = new GridField('testfield', 'testfield', Member::get()); $obj = new GridField('testfield', 'testfield', Member::get());
$this->assertEquals(3, $obj->getColumnCount()); $this->assertEquals(3, $obj->getColumnCount());
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnContent
*/
public function testGetColumnContent() public function testGetColumnContent()
{ {
$list = new ArrayList( $list = new ArrayList(
@ -257,9 +213,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals('test@example.org', $obj->getColumnContent($list->first(), 'Email')); $this->assertEquals('test@example.org', $obj->getColumnContent($list->first(), 'Email'));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnContent
*/
public function testGetColumnContentBadArguments() public function testGetColumnContentBadArguments()
{ {
$this->expectException(InvalidArgumentException::class); $this->expectException(InvalidArgumentException::class);
@ -272,9 +225,6 @@ class GridFieldTest extends SapphireTest
$obj->getColumnContent($list->first(), 'non-existing'); $obj->getColumnContent($list->first(), 'non-existing');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnAttributes
*/
public function testGetColumnAttributesEmptyArray() public function testGetColumnAttributesEmptyArray()
{ {
$list = new ArrayList( $list = new ArrayList(
@ -286,9 +236,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals(['class' => 'col-Email'], $obj->getColumnAttributes($list->first(), 'Email')); $this->assertEquals(['class' => 'col-Email'], $obj->getColumnAttributes($list->first(), 'Email'));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnAttributes
*/
public function testGetColumnAttributes() public function testGetColumnAttributes()
{ {
$list = new ArrayList( $list = new ArrayList(
@ -301,9 +248,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals(['class' => 'css-class'], $obj->getColumnAttributes($list->first(), 'Email')); $this->assertEquals(['class' => 'css-class'], $obj->getColumnAttributes($list->first(), 'Email'));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnAttributes
*/
public function testGetColumnAttributesBadArguments() public function testGetColumnAttributesBadArguments()
{ {
$this->expectException(\InvalidArgumentException::class); $this->expectException(\InvalidArgumentException::class);
@ -330,9 +274,6 @@ class GridFieldTest extends SapphireTest
$obj->getColumnAttributes($list->first(), 'Surname'); $obj->getColumnAttributes($list->first(), 'Surname');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnMetadata
*/
public function testGetColumnMetadata() public function testGetColumnMetadata()
{ {
$list = new ArrayList( $list = new ArrayList(
@ -345,9 +286,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals(['metadata' => 'istrue'], $obj->getColumnMetadata('Email')); $this->assertEquals(['metadata' => 'istrue'], $obj->getColumnMetadata('Email'));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnMetadata
*/
public function testGetColumnMetadataBadResponseFromComponent() public function testGetColumnMetadataBadResponseFromComponent()
{ {
$this->expectException(\LogicException::class); $this->expectException(\LogicException::class);
@ -361,9 +299,6 @@ class GridFieldTest extends SapphireTest
$obj->getColumnMetadata('Surname'); $obj->getColumnMetadata('Surname');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getColumnMetadata
*/
public function testGetColumnMetadataBadArguments() public function testGetColumnMetadataBadArguments()
{ {
$this->expectException(\InvalidArgumentException::class); $this->expectException(\InvalidArgumentException::class);
@ -373,9 +308,6 @@ class GridFieldTest extends SapphireTest
$obj->getColumnMetadata('non-exist-qweqweqwe'); $obj->getColumnMetadata('non-exist-qweqweqwe');
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::handleAction
*/
public function testHandleActionBadArgument() public function testHandleActionBadArgument()
{ {
$this->expectException(\InvalidArgumentException::class); $this->expectException(\InvalidArgumentException::class);
@ -383,9 +315,6 @@ class GridFieldTest extends SapphireTest
$obj->handleAlterAction('prft', [], []); $obj->handleAlterAction('prft', [], []);
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::handleAction
*/
public function testHandleAction() public function testHandleAction()
{ {
$config = GridFieldConfig::create()->addComponent(new Component); $config = GridFieldConfig::create()->addComponent(new Component);
@ -393,9 +322,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals('handledAction is executed', $obj->handleAlterAction('jump', [], [])); $this->assertEquals('handledAction is executed', $obj->handleAlterAction('jump', [], []));
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getCastedValue
*/
public function testGetCastedValue() public function testGetCastedValue()
{ {
$obj = new GridField('testfield', 'testfield'); $obj = new GridField('testfield', 'testfield');
@ -403,9 +329,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals('This is a sentence.', $value); $this->assertEquals('This is a sentence.', $value);
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::getCastedValue
*/
public function testGetCastedValueObject() public function testGetCastedValueObject()
{ {
$obj = new GridField('testfield', 'testfield'); $obj = new GridField('testfield', 'testfield');
@ -413,9 +336,6 @@ class GridFieldTest extends SapphireTest
$this->assertEquals('Here is some &lt;html&gt; content', $value); $this->assertEquals('Here is some &lt;html&gt; content', $value);
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::gridFieldAlterAction
*/
public function testGridFieldAlterAction() public function testGridFieldAlterAction()
{ {
$this->markTestIncomplete(); $this->markTestIncomplete();
@ -547,9 +467,6 @@ class GridFieldTest extends SapphireTest
$field->FieldHolder(); $field->FieldHolder();
} }
/**
* @covers \SilverStripe\Forms\GridField\GridField::FieldHolder
*/
public function testCanViewOnlyOddIDs() public function testCanViewOnlyOddIDs()
{ {
$this->logInWithPermission(); $this->logInWithPermission();

View File

@ -18,6 +18,7 @@ use SilverStripe\Forms\HTMLEditor\TinyMCEConfig;
use SilverStripe\Forms\HTMLReadonlyField; use SilverStripe\Forms\HTMLReadonlyField;
use SilverStripe\Forms\Tests\HTMLEditor\HTMLEditorFieldTest\TestObject; use SilverStripe\Forms\Tests\HTMLEditor\HTMLEditorFieldTest\TestObject;
use SilverStripe\ORM\FieldType\DBHTMLText; use SilverStripe\ORM\FieldType\DBHTMLText;
use PHPUnit\Framework\Attributes\DataProvider;
class HTMLEditorFieldTest extends FunctionalTest class HTMLEditorFieldTest extends FunctionalTest
{ {
@ -215,7 +216,7 @@ EOS
); );
} }
public function provideTestValueEntities() public static function provideTestValueEntities()
{ {
return [ return [
"ampersand" => [ "ampersand" => [
@ -233,9 +234,7 @@ EOS
]; ];
} }
/** #[DataProvider('provideTestValueEntities')]
* @dataProvider provideTestValueEntities
*/
public function testValueEntities(string $input, string $result) public function testValueEntities(string $input, string $result)
{ {
$field = new HTMLEditorField("Content"); $field = new HTMLEditorField("Content");

View File

@ -7,11 +7,12 @@ use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig; use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig;
use SilverStripe\Forms\HTMLEditor\HTMLEditorSanitiser; use SilverStripe\Forms\HTMLEditor\HTMLEditorSanitiser;
use SilverStripe\View\Parsers\HTMLValue; use SilverStripe\View\Parsers\HTMLValue;
use PHPUnit\Framework\Attributes\DataProvider;
class HTMLEditorSanitiserTest extends FunctionalTest class HTMLEditorSanitiserTest extends FunctionalTest
{ {
public function provideSanitise(): array public static function provideSanitise(): array
{ {
return [ return [
[ [
@ -155,9 +156,7 @@ class HTMLEditorSanitiserTest extends FunctionalTest
]; ];
} }
/** #[DataProvider('provideSanitise')]
* @dataProvider provideSanitise
*/
public function testSanitisation(string $validElements, string $input, string $output, string $desc): void public function testSanitisation(string $validElements, string $input, string $output, string $desc): void
{ {
foreach (['valid_elements', 'extended_valid_elements'] as $configType) { foreach (['valid_elements', 'extended_valid_elements'] as $configType) {

View File

@ -6,6 +6,7 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\Forms\NumericField; use SilverStripe\Forms\NumericField;
use SilverStripe\Forms\RequiredFields; use SilverStripe\Forms\RequiredFields;
use SilverStripe\i18n\i18n; use SilverStripe\i18n\i18n;
use PHPUnit\Framework\Attributes\DataProvider;
class NumericFieldTest extends SapphireTest class NumericFieldTest extends SapphireTest
{ {
@ -15,12 +16,12 @@ class NumericFieldTest extends SapphireTest
* Test that data loaded in via Form::loadDataFrom(DataObject) will populate the field correctly, * Test that data loaded in via Form::loadDataFrom(DataObject) will populate the field correctly,
* and can format the database value appropriately for the frontend * and can format the database value appropriately for the frontend
* *
* @dataProvider dataForTestSetValue
* @param string $locale Locale to test in * @param string $locale Locale to test in
* @param int $scale Scale size (number of decimal places) * @param int $scale Scale size (number of decimal places)
* @param string $input Input string * @param string $input Input string
* @param int|float $output Expected data value * @param int|float $output Expected data value
*/ */
#[DataProvider('dataForTestSetValue')]
public function testSetValue($locale, $scale, $input, $output) public function testSetValue($locale, $scale, $input, $output)
{ {
$field = new NumericField('Number'); $field = new NumericField('Number');
@ -55,7 +56,7 @@ class NumericFieldTest extends SapphireTest
/** /**
* Test formatting of numbers * Test formatting of numbers
*/ */
public function dataForTestSetValue() public static function dataForTestSetValue()
{ {
return [ return [
// de // de
@ -124,7 +125,7 @@ class NumericFieldTest extends SapphireTest
$this->assertEquals(0, $field->dataValue()); $this->assertEquals(0, $field->dataValue());
} }
public function dataForTestSubmittedValue() public static function dataForTestSubmittedValue()
{ {
return [ return [
['de_DE', 0, '13000', 13000, '13.000'], ['de_DE', 0, '13000', 13000, '13.000'],
@ -187,13 +188,13 @@ class NumericFieldTest extends SapphireTest
} }
/** /**
* @dataProvider dataForTestSubmittedValue
* @param string $locale Locale to test in * @param string $locale Locale to test in
* @param int $scale Scale size (number of decimal places) * @param int $scale Scale size (number of decimal places)
* @param string $submittedValue Input string * @param string $submittedValue Input string
* @param int|float $dataValue Expected data value * @param int|float $dataValue Expected data value
* @param string $cleanedInput * @param string $cleanedInput
*/ */
#[DataProvider('dataForTestSubmittedValue')]
public function testSetSubmittedValue($locale, $scale, $submittedValue, $dataValue, $cleanedInput = null) public function testSetSubmittedValue($locale, $scale, $submittedValue, $dataValue, $cleanedInput = null)
{ {
$field = new NumericField('Number'); $field = new NumericField('Number');

View File

@ -5,10 +5,11 @@ namespace SilverStripe\Forms\Tests;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Forms\PasswordField; use SilverStripe\Forms\PasswordField;
use PHPUnit\Framework\Attributes\DataProvider;
class PasswordFieldTest extends SapphireTest class PasswordFieldTest extends SapphireTest
{ {
public function boolDataProvider() public static function boolDataProvider()
{ {
return [ return [
[false], [false],
@ -17,9 +18,9 @@ class PasswordFieldTest extends SapphireTest
} }
/** /**
* @dataProvider boolDataProvider
* @param bool $bool * @param bool $bool
*/ */
#[DataProvider('boolDataProvider')]
public function testAutocomplete($bool) public function testAutocomplete($bool)
{ {
Config::modify()->set(PasswordField::class, 'autocomplete', $bool); Config::modify()->set(PasswordField::class, 'autocomplete', $bool);
@ -31,9 +32,9 @@ class PasswordFieldTest extends SapphireTest
} }
/** /**
* @dataProvider boolDataProvider
* @param bool $bool * @param bool $bool
*/ */
#[DataProvider('boolDataProvider')]
public function testValuePostback($bool) public function testValuePostback($bool)
{ {
$field = (new PasswordField('test', 'test', 'password')) $field = (new PasswordField('test', 'test', 'password'))

View File

@ -8,6 +8,7 @@ use SilverStripe\Forms\Form;
use SilverStripe\Forms\SearchableDropdownField; use SilverStripe\Forms\SearchableDropdownField;
use SilverStripe\Forms\TreeDropdownField; use SilverStripe\Forms\TreeDropdownField;
use SilverStripe\Security\Group; use SilverStripe\Security\Group;
use PHPUnit\Framework\Attributes\DataProvider;
class RequiredFieldsTest extends SapphireTest class RequiredFieldsTest extends SapphireTest
{ {
@ -290,7 +291,7 @@ class RequiredFieldsTest extends SapphireTest
); );
} }
public function provideHasOneRelationFieldInterfaceValidation(): array public static function provideHasOneRelationFieldInterfaceValidation(): array
{ {
return [ return [
[ [
@ -302,9 +303,7 @@ class RequiredFieldsTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideHasOneRelationFieldInterfaceValidation')]
* @dataProvider provideHasOneRelationFieldInterfaceValidation
*/
public function testHasOneRelationFieldInterfaceValidation(string $className) public function testHasOneRelationFieldInterfaceValidation(string $className)
{ {
$form = new Form(); $form = new Form();

View File

@ -15,6 +15,7 @@ use SilverStripe\Security\SecurityToken;
use SilverStripe\Forms\HiddenField; use SilverStripe\Forms\HiddenField;
use stdClass; use stdClass;
use SilverStripe\Forms\Form; use SilverStripe\Forms\Form;
use PHPUnit\Framework\Attributes\DataProvider;
class SearchableDropdownTraitTest extends SapphireTest class SearchableDropdownTraitTest extends SapphireTest
{ {
@ -103,9 +104,7 @@ class SearchableDropdownTraitTest extends SapphireTest
$this->assertSame('Something', $field->getLabelField()); $this->assertSame('Something', $field->getLabelField());
} }
/** #[DataProvider('provideGetValueArray')]
* @dataProvider provideGetValueArray
*/
public function testGetValueArray(mixed $value, string|array $expected): void public function testGetValueArray(mixed $value, string|array $expected): void
{ {
if ($value === '<DataListValue>') { if ($value === '<DataListValue>') {
@ -121,7 +120,7 @@ class SearchableDropdownTraitTest extends SapphireTest
$this->assertSame($expected, $field->getValueArray()); $this->assertSame($expected, $field->getValueArray());
} }
public function provideGetValueArray(): array public static function provideGetValueArray(): array
{ {
return [ return [
'empty' => [ 'empty' => [
@ -219,7 +218,7 @@ class SearchableDropdownTraitTest extends SapphireTest
$this->assertFalse($schema['searchable']); $this->assertFalse($schema['searchable']);
} }
public function provideLazyLoadedDoesntCallGetSource() public static function provideLazyLoadedDoesntCallGetSource()
{ {
$methodsToCall = [ $methodsToCall = [
'Field', 'Field',
@ -244,9 +243,7 @@ class SearchableDropdownTraitTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideLazyLoadedDoesntCallGetSource')]
* @dataProvider provideLazyLoadedDoesntCallGetSource
*/
public function testLazyLoadedDoesntCallGetSource(string $fieldClass, string $methodToCall) public function testLazyLoadedDoesntCallGetSource(string $fieldClass, string $methodToCall)
{ {
// Some methods aren't shared between the two form fields. // Some methods aren't shared between the two form fields.

View File

@ -5,10 +5,11 @@ namespace SilverStripe\Forms\Tests;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Forms\UrlField; use SilverStripe\Forms\UrlField;
use SilverStripe\Forms\RequiredFields; use SilverStripe\Forms\RequiredFields;
use PHPUnit\Framework\Attributes\DataProvider;
class UrlFieldTest extends SapphireTest class UrlFieldTest extends SapphireTest
{ {
public function provideValidate(): array public static function provideValidate(): array
{ {
return [ return [
[ [
@ -78,13 +79,11 @@ class UrlFieldTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideValidate')]
* @dataProvider provideValidate public function testValidate(string $url, bool $valid)
*/
public function testValidate(string $email, bool $valid)
{ {
$field = new UrlField('MyUrl'); $field = new UrlField('MyUrl');
$field->setValue($email); $field->setValue($url);
$validator = new RequiredFields(); $validator = new RequiredFields();
$field->validate($validator); $field->validate($validator);
$expectedCount = $valid ? 0 : 1; $expectedCount = $valid ? 0 : 1;

View File

@ -21,7 +21,7 @@ class DebugViewFriendlyErrorFormatterTest extends SapphireTest
{ {
/** @var DebugViewFriendlyErrorFormatter|MockObject $mock */ /** @var DebugViewFriendlyErrorFormatter|MockObject $mock */
$mock = $this->getMockBuilder(DebugViewFriendlyErrorFormatter::class) $mock = $this->getMockBuilder(DebugViewFriendlyErrorFormatter::class)
->setMethods(['output']) ->onlyMethods(['output'])
->getMock(); ->getMock();
$mock->expects($this->once())->method('output')->with(403)->willReturn('foo'); $mock->expects($this->once())->method('output')->with(403)->willReturn('foo');
@ -32,7 +32,7 @@ class DebugViewFriendlyErrorFormatterTest extends SapphireTest
{ {
/** @var DebugViewFriendlyErrorFormatter|MockObject $mock */ /** @var DebugViewFriendlyErrorFormatter|MockObject $mock */
$mock = $this->getMockBuilder(DebugViewFriendlyErrorFormatter::class) $mock = $this->getMockBuilder(DebugViewFriendlyErrorFormatter::class)
->setMethods(['output']) ->onlyMethods(['output'])
->getMock(); ->getMock();
$mock->setStatusCode(404); $mock->setStatusCode(404);
@ -51,7 +51,7 @@ class DebugViewFriendlyErrorFormatterTest extends SapphireTest
/** @var DebugViewFriendlyErrorFormatter|MockObject $mock */ /** @var DebugViewFriendlyErrorFormatter|MockObject $mock */
$mock = $this->getMockBuilder(DebugViewFriendlyErrorFormatter::class) $mock = $this->getMockBuilder(DebugViewFriendlyErrorFormatter::class)
->setMethods(['format']) ->onlyMethods(['format'])
->getMock(); ->getMock();
$mock->expects($this->exactly(3)) $mock->expects($this->exactly(3))

View File

@ -13,6 +13,7 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\Logging\DebugViewFriendlyErrorFormatter; use SilverStripe\Logging\DebugViewFriendlyErrorFormatter;
use SilverStripe\Logging\DetailedErrorFormatter; use SilverStripe\Logging\DetailedErrorFormatter;
use SilverStripe\Logging\HTTPOutputHandler; use SilverStripe\Logging\HTTPOutputHandler;
use PHPUnit\Framework\Attributes\DataProvider;
class HTTPOutputHandlerTest extends SapphireTest class HTTPOutputHandlerTest extends SapphireTest
{ {
@ -58,7 +59,7 @@ class HTTPOutputHandlerTest extends SapphireTest
$this->assertInstanceOf(DetailedErrorFormatter::class, $handler->getFormatter()); $this->assertInstanceOf(DetailedErrorFormatter::class, $handler->getFormatter());
} }
public function provideShouldShowError() public static function provideShouldShowError()
{ {
$provide = []; $provide = [];
// See https://www.php.net/manual/en/errorfunc.constants.php // See https://www.php.net/manual/en/errorfunc.constants.php
@ -145,9 +146,7 @@ class HTTPOutputHandlerTest extends SapphireTest
return $provide; return $provide;
} }
/** #[DataProvider('provideShouldShowError')]
* @dataProvider provideShouldShowError
*/
public function testShouldShowError( public function testShouldShowError(
int $errorCode, int $errorCode,
bool $triggeringError, bool $triggeringError,

View File

@ -5,10 +5,10 @@ namespace SilverStripe\ORM\Tests;
use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\ExpectationFailedException;
use SilverStripe\ORM\ArrayLib; use SilverStripe\ORM\ArrayLib;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use PHPUnit\Framework\Attributes\DataProvider;
class ArrayLibTest extends SapphireTest class ArrayLibTest extends SapphireTest
{ {
public function testInvert() public function testInvert()
{ {
$arr = [ $arr = [
@ -369,7 +369,7 @@ class ArrayLibTest extends SapphireTest
} }
} }
public function provideInsertBefore(): array public static function provideInsertBefore(): array
{ {
return [ return [
'simple insertion' => [ 'simple insertion' => [
@ -445,9 +445,7 @@ class ArrayLibTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideInsertBefore')]
* @dataProvider provideInsertBefore
*/
public function testInsertBefore(mixed $insert, mixed $before, bool $strict, bool $splat, array $expected): void public function testInsertBefore(mixed $insert, mixed $before, bool $strict, bool $splat, array $expected): void
{ {
$array = ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last']; $array = ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last'];
@ -455,75 +453,75 @@ class ArrayLibTest extends SapphireTest
$this->assertSame($expected, $final); $this->assertSame($expected, $final);
} }
public function provideInsertAfter(): array public static function provideInsertAfter(): array
{ {
return [ return [
'simple insertion' => [ 'simple insertion' => [
'insert' => 'new', 'insert' => 'new',
'before' => 'def', 'after' => 'def',
'strict' => true, 'strict' => true,
'splat' => false, 'splat' => false,
'expected' => ['abc', '', [1,2,3], 'def', 'new', '0', null, true, 0, 'last'] 'expected' => ['abc', '', [1,2,3], 'def', 'new', '0', null, true, 0, 'last']
], ],
'insert after first' => [ 'insert after first' => [
'insert' => 'new', 'insert' => 'new',
'before' => 'abc', 'after' => 'abc',
'strict' => true, 'strict' => true,
'splat' => false, 'splat' => false,
'expected' => ['abc', 'new', '', [1,2,3], 'def', '0', null, true, 0, 'last'] 'expected' => ['abc', 'new', '', [1,2,3], 'def', '0', null, true, 0, 'last']
], ],
'insert after last' => [ 'insert after last' => [
'insert' => 'new', 'insert' => 'new',
'before' => 'last', 'after' => 'last',
'strict' => true, 'strict' => true,
'splat' => false, 'splat' => false,
'expected' => ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last', 'new'] 'expected' => ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last', 'new']
], ],
'insert after missing' => [ 'insert after missing' => [
'insert' => 'new', 'insert' => 'new',
'before' => 'this value isnt there', 'after' => 'this value isnt there',
'strict' => true, 'strict' => true,
'splat' => false, 'splat' => false,
'expected' => ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last', 'new'] 'expected' => ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last', 'new']
], ],
'strict' => [ 'strict' => [
'insert' => 'new', 'insert' => 'new',
'before' => 0, 'after' => 0,
'strict' => true, 'strict' => true,
'splat' => false, 'splat' => false,
'expected' => ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'new', 'last'] 'expected' => ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'new', 'last']
], ],
'not strict' => [ 'not strict' => [
'insert' => 'new', 'insert' => 'new',
'before' => 0, 'after' => 0,
'strict' => false, 'strict' => false,
'splat' => false, 'splat' => false,
'expected' => ['abc', '', [1,2,3], 'def', '0', 'new', null, true, 0, 'last'] 'expected' => ['abc', '', [1,2,3], 'def', '0', 'new', null, true, 0, 'last']
], ],
'after array' => [ 'after array' => [
'insert' => 'new', 'insert' => 'new',
'before' => [1,2,3], 'after' => [1,2,3],
'strict' => true, 'strict' => true,
'splat' => false, 'splat' => false,
'expected' => ['abc', '', [1,2,3], 'new', 'def', '0', null, true, 0, 'last'] 'expected' => ['abc', '', [1,2,3], 'new', 'def', '0', null, true, 0, 'last']
], ],
'after missing array' => [ 'after missing array' => [
'insert' => 'new', 'insert' => 'new',
'before' => ['a', 'b', 'c'], 'after' => ['a', 'b', 'c'],
'strict' => true, 'strict' => true,
'splat' => false, 'splat' => false,
'expected' => ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last', 'new'] 'expected' => ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last', 'new']
], ],
'splat array' => [ 'splat array' => [
'insert' => ['a', 'b', 'c'], 'insert' => ['a', 'b', 'c'],
'before' => 'def', 'after' => 'def',
'strict' => true, 'strict' => true,
'splat' => true, 'splat' => true,
'expected' => ['abc', '', [1,2,3], 'def', 'a', 'b', 'c', '0', null, true, 0, 'last'] 'expected' => ['abc', '', [1,2,3], 'def', 'a', 'b', 'c', '0', null, true, 0, 'last']
], ],
'no splat array' => [ 'no splat array' => [
'insert' => ['a', 'b', 'c'], 'insert' => ['a', 'b', 'c'],
'before' => 'def', 'after' => 'def',
'strict' => true, 'strict' => true,
'splat' => false, 'splat' => false,
'expected' => ['abc', '', [1,2,3], 'def', ['a', 'b', 'c'], '0', null, true, 0, 'last'] 'expected' => ['abc', '', [1,2,3], 'def', ['a', 'b', 'c'], '0', null, true, 0, 'last']
@ -531,9 +529,7 @@ class ArrayLibTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideInsertAfter')]
* @dataProvider provideInsertAfter
*/
public function testInsertAfter(mixed $insert, mixed $after, bool $strict, bool $splat, array $expected): void public function testInsertAfter(mixed $insert, mixed $after, bool $strict, bool $splat, array $expected): void
{ {
$array = ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last']; $array = ['abc', '', [1,2,3], 'def', '0', null, true, 0, 'last'];

View File

@ -8,6 +8,7 @@ use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\Filterable; use SilverStripe\ORM\Filterable;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use stdClass; use stdClass;
use PHPUnit\Framework\Attributes\DataProvider;
class ArrayListTest extends SapphireTest class ArrayListTest extends SapphireTest
{ {
@ -118,7 +119,7 @@ class ArrayListTest extends SapphireTest
$this->assertEquals($list->Count(), $count); $this->assertEquals($list->Count(), $count);
} }
public function limitDataProvider(): array public static function limitDataProvider(): array
{ {
$all = [ ['Key' => 1], ['Key' => 2], ['Key' => 3] ]; $all = [ ['Key' => 1], ['Key' => 2], ['Key' => 3] ];
list($one, $two, $three) = $all; list($one, $two, $three) = $all;
@ -141,9 +142,7 @@ class ArrayListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('limitDataProvider')]
* @dataProvider limitDataProvider
*/
public function testLimit($length, $offset, array $expected) public function testLimit($length, $offset, array $expected)
{ {
$data = [ $data = [
@ -343,9 +342,9 @@ class ArrayListTest extends SapphireTest
); );
} }
public function provideFindWithSearchfilters() public static function provideFindWithSearchfilters()
{ {
$objects = $this->getFilterWithSearchfiltersObjects(); $objects = ArrayListTest::getFilterWithSearchfiltersObjects();
return [ return [
// test a couple of search filters // test a couple of search filters
// don't need to be as explicit as the filter tests, just check the syntax works // don't need to be as explicit as the filter tests, just check the syntax works
@ -387,9 +386,7 @@ class ArrayListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideFindWithSearchfilters')]
* @dataProvider provideFindWithSearchfilters
*/
public function testFindWithSearchfilters(array $args, array $objects, object|array|null $expected) public function testFindWithSearchfilters(array $args, array $objects, object|array|null $expected)
{ {
$list = new ArrayList($objects); $list = new ArrayList($objects);
@ -970,21 +967,19 @@ class ArrayListTest extends SapphireTest
$this->assertEquals($expected, $list->toArray(), 'List should only contain Steve and Steve and Clair'); $this->assertEquals($expected, $list->toArray(), 'List should only contain Steve and Steve and Clair');
} }
/** #[DataProvider('provideFilterNullComparisons')]
* @dataProvider provideFilterNullComparisons public function testFilterNullComparisons(mixed $objectValue, mixed $filterValues, bool $doesMatch, bool $negated = false)
*/
public function testFilterNullComparisons(mixed $objectValue, mixed $filterValue, bool $doesMatch, bool $negated = false)
{ {
$filterField = 'Value'; $filterField = 'Value';
if ($negated) { if ($negated) {
$filterField .= ':not'; $filterField .= ':not';
} }
$list = new ArrayList([['Value' => $objectValue]]); $list = new ArrayList([['Value' => $objectValue]]);
$list = $list->filter($filterField, $filterValue); $list = $list->filter($filterField, $filterValues);
$this->assertCount($doesMatch ? 1 : 0, $list); $this->assertCount($doesMatch ? 1 : 0, $list);
} }
public function provideFilterNullComparisons() public static function provideFilterNullComparisons()
{ {
// This is for backwards compatibility, since arraylist used to just do a straight == comparison // This is for backwards compatibility, since arraylist used to just do a straight == comparison
// Everything that passes here would have passed a $objectValue == $filterValue comparison previously // Everything that passes here would have passed a $objectValue == $filterValue comparison previously
@ -1091,7 +1086,7 @@ class ArrayListTest extends SapphireTest
return $scenarios; return $scenarios;
} }
private function getFilterWithSearchfiltersObjects() private static function getFilterWithSearchfiltersObjects()
{ {
return [ return [
[ [
@ -1149,12 +1144,12 @@ class ArrayListTest extends SapphireTest
]; ];
} }
public function provideFilterWithSearchfilters() public static function provideFilterWithSearchfilters()
{ {
// Note that search filter tests here are to test syntax and to ensure all supported search filters // Note that search filter tests here are to test syntax and to ensure all supported search filters
// work with arraylist - but we don't need to test every possible edge case here, // work with arraylist - but we don't need to test every possible edge case here,
// we can rely on individual searchfilter unit tests for many edge cases // we can rely on individual searchfilter unit tests for many edge cases
$objects = $this->getFilterWithSearchfiltersObjects(); $objects = ArrayListTest::getFilterWithSearchfiltersObjects();
return [ return [
// exact match filter tests // exact match filter tests
'exact match - negate' => [ 'exact match - negate' => [
@ -1171,7 +1166,7 @@ class ArrayListTest extends SapphireTest
'expected' => [$objects[1], $objects[3], $objects[4]], 'expected' => [$objects[1], $objects[3], $objects[4]],
], ],
'exact match negated - nothing gets filtered out' => [ 'exact match negated - nothing gets filtered out' => [
'filter' => ['Title:not', 'No object has this title - we should have all objects'], 'args' => ['Title:not', 'No object has this title - we should have all objects'],
'objects' => $objects, 'objects' => $objects,
'expected' => $objects, 'expected' => $objects,
], ],
@ -1311,9 +1306,7 @@ class ArrayListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideFilterWithSearchfilters')]
* @dataProvider provideFilterWithSearchfilters
*/
public function testFilterWithSearchfilters(array $args, array $objects, array $expected) public function testFilterWithSearchfilters(array $args, array $objects, array $expected)
{ {
$list = new ArrayList($objects); $list = new ArrayList($objects);
@ -1321,9 +1314,9 @@ class ArrayListTest extends SapphireTest
$this->assertEquals(array_column($expected, 'ID'), $list->column('ID')); $this->assertEquals(array_column($expected, 'ID'), $list->column('ID'));
} }
public function provideFilterAnyWithSearchfilters() public static function provideFilterAnyWithSearchfilters()
{ {
$objects = $this->getFilterWithSearchfiltersObjects(); $objects = ArrayListTest::getFilterWithSearchfiltersObjects();
return [ return [
// test a couple of search filters // test a couple of search filters
// don't need to be as explicit as the filter tests, just check the syntax works // don't need to be as explicit as the filter tests, just check the syntax works
@ -1368,9 +1361,7 @@ class ArrayListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideFilterAnyWithSearchfilters')]
* @dataProvider provideFilterAnyWithSearchfilters
*/
public function testFilterAnyWithSearchfilters(array $args, array $objects, array $expected) public function testFilterAnyWithSearchfilters(array $args, array $objects, array $expected)
{ {
$list = new ArrayList($objects); $list = new ArrayList($objects);
@ -1378,7 +1369,7 @@ class ArrayListTest extends SapphireTest
$this->assertEquals(array_column($expected, 'ID'), $list->column('ID')); $this->assertEquals(array_column($expected, 'ID'), $list->column('ID'));
} }
public function provideFilterAny() public static function provideFilterAny()
{ {
$list = new ArrayList( $list = new ArrayList(
[ [
@ -1429,9 +1420,7 @@ class ArrayListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideFilterAny')]
* @dataProvider provideFilterAny
*/
public function testFilterAny(ArrayList $list, array $args, array $contains) public function testFilterAny(ArrayList $list, array $args, array $contains)
{ {
$filteredList = $list->filterAny(...$args)->toArray(); $filteredList = $list->filterAny(...$args)->toArray();
@ -1650,12 +1639,12 @@ class ArrayListTest extends SapphireTest
$this->assertEquals($expected, $list->toArray()); $this->assertEquals($expected, $list->toArray());
} }
public function provideExcludeWithSearchfilters() public static function provideExcludeWithSearchfilters()
{ {
// If it's included in the filter test, then it's excluded in the exclude test, // If it's included in the filter test, then it's excluded in the exclude test,
// so we can just use the same scenarios and reverse the expected results. // so we can just use the same scenarios and reverse the expected results.
$objects = $this->getFilterWithSearchfiltersObjects(); $objects = ArrayListTest::getFilterWithSearchfiltersObjects();
$scenarios = $this->provideFilterWithSearchfilters(); $scenarios = ArrayListTest::provideFilterWithSearchfilters();
foreach ($scenarios as $name => $scenario) { foreach ($scenarios as $name => $scenario) {
$kept = []; $kept = [];
$excluded = []; $excluded = [];
@ -1672,9 +1661,7 @@ class ArrayListTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideExcludeWithSearchfilters')]
* @dataProvider provideExcludeWithSearchfilters
*/
public function testExcludeWithSearchfilters(array $args, array $objects, array $expected) public function testExcludeWithSearchfilters(array $args, array $objects, array $expected)
{ {
$list = new ArrayList($objects); $list = new ArrayList($objects);
@ -1682,12 +1669,12 @@ class ArrayListTest extends SapphireTest
$this->assertEquals($expected, $list->toArray()); $this->assertEquals($expected, $list->toArray());
} }
public function provideExcludeAnyWithSearchfilters() public static function provideExcludeAnyWithSearchfilters()
{ {
// If it's included in the filterAny test, then it's excluded in the excludeAny test, // If it's included in the filterAny test, then it's excluded in the excludeAny test,
// so we can just use the same scenarios and reverse the expected results. // so we can just use the same scenarios and reverse the expected results.
$objects = $this->getFilterWithSearchfiltersObjects(); $objects = ArrayListTest::getFilterWithSearchfiltersObjects();
$scenarios = $this->provideFilterAnyWithSearchfilters(); $scenarios = ArrayListTest::provideFilterAnyWithSearchfilters();
foreach ($scenarios as $name => $scenario) { foreach ($scenarios as $name => $scenario) {
$kept = []; $kept = [];
$excluded = []; $excluded = [];
@ -1704,9 +1691,7 @@ class ArrayListTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideExcludeAnyWithSearchfilters')]
* @dataProvider provideExcludeAnyWithSearchfilters
*/
public function testExcludeAnyWithSearchfilters(array $args, array $objects, array $expected) public function testExcludeAnyWithSearchfilters(array $args, array $objects, array $expected)
{ {
$list = new ArrayList($objects); $list = new ArrayList($objects);
@ -1714,11 +1699,11 @@ class ArrayListTest extends SapphireTest
$this->assertEquals($expected, $list->toArray()); $this->assertEquals($expected, $list->toArray());
} }
public function provideExcludeAny() public static function provideExcludeAny()
{ {
// If it's included in the filterAny test, then it's excluded in the excludeAny test, // If it's included in the filterAny test, then it's excluded in the excludeAny test,
// so we can just use the same scenarios and reverse the expected results. // so we can just use the same scenarios and reverse the expected results.
$scenarios = $this->provideFilterAny(); $scenarios = ArrayListTest::provideFilterAny();
foreach ($scenarios as $name => $scenario) { foreach ($scenarios as $name => $scenario) {
$kept = []; $kept = [];
$excluded = []; $excluded = [];
@ -1738,9 +1723,7 @@ class ArrayListTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideExcludeAny')]
* @dataProvider provideExcludeAny
*/
public function testExcludeAny(ArrayList $list, array $args, array $contains) public function testExcludeAny(ArrayList $list, array $args, array $contains)
{ {
$filteredList = $list->excludeAny(...$args)->toArray(); $filteredList = $list->excludeAny(...$args)->toArray();

View File

@ -6,12 +6,13 @@ use ReflectionMethod;
use SilverStripe\Core\Environment; use SilverStripe\Core\Environment;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Connect\DBQueryBuilder; use SilverStripe\ORM\Connect\DBQueryBuilder;
use PHPUnit\Framework\Attributes\DataProvider;
class DBQueryBuilderTest extends SapphireTest class DBQueryBuilderTest extends SapphireTest
{ {
protected $usesDatabase = false; protected $usesDatabase = false;
public function provideShouldBuildTraceComment(): array public static function provideShouldBuildTraceComment(): array
{ {
return [ return [
[ [
@ -47,9 +48,7 @@ class DBQueryBuilderTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideShouldBuildTraceComment')]
* @dataProvider provideShouldBuildTraceComment
*/
public function testShouldBuildTraceComment(?bool $envValue, bool $yamlValue, bool $expected): void public function testShouldBuildTraceComment(?bool $envValue, bool $yamlValue, bool $expected): void
{ {
$queryBuilder = new DBQueryBuilder(); $queryBuilder = new DBQueryBuilder();

View File

@ -9,6 +9,7 @@ use SilverStripe\i18n\i18n;
use SilverStripe\ORM\FieldType\DBDate; use SilverStripe\ORM\FieldType\DBDate;
use SilverStripe\ORM\FieldType\DBDatetime; use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\FieldType\DBField;
use PHPUnit\Framework\Attributes\DataProvider;
class DBDateTest extends SapphireTest class DBDateTest extends SapphireTest
{ {
@ -349,8 +350,8 @@ class DBDateTest extends SapphireTest
/** /**
* @param string $adjustment * @param string $adjustment
* @param string $expected * @param string $expected
* @dataProvider modifyProvider
*/ */
#[DataProvider('modifyProvider')]
public function testModify($adjustment, $expected) public function testModify($adjustment, $expected)
{ {
/** @var DBDate $dateField */ /** @var DBDate $dateField */
@ -362,7 +363,7 @@ class DBDateTest extends SapphireTest
/** /**
* @return array[] * @return array[]
*/ */
public function modifyProvider() public static function modifyProvider()
{ {
return [ return [
['+1 day', '2019-03-04'], ['+1 day', '2019-03-04'],

View File

@ -5,6 +5,7 @@ namespace SilverStripe\ORM\Tests;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\i18n\i18n; use SilverStripe\i18n\i18n;
use SilverStripe\ORM\FieldType\DBDatetime; use SilverStripe\ORM\FieldType\DBDatetime;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Tests for {@link Datetime} class. * Tests for {@link Datetime} class.
@ -271,8 +272,8 @@ class DBDatetimeTest extends SapphireTest
/** /**
* @param string $adjustment * @param string $adjustment
* @param string $expected * @param string $expected
* @dataProvider modifyProvider
*/ */
#[DataProvider('modifyProvider')]
public function testModify($adjustment, $expected) public function testModify($adjustment, $expected)
{ {
DBDatetime::set_mock_now('2019-03-03 12:00:00'); DBDatetime::set_mock_now('2019-03-03 12:00:00');
@ -283,7 +284,7 @@ class DBDatetimeTest extends SapphireTest
/** /**
* @return array[] * @return array[]
*/ */
public function modifyProvider() public static function modifyProvider()
{ {
return [ return [
['+1 day', '2019-03-04 12:00:00'], ['+1 day', '2019-03-04 12:00:00'],
@ -303,7 +304,7 @@ class DBDatetimeTest extends SapphireTest
]; ];
} }
public function provideGetTimeBetween(): array public static function provideGetTimeBetween(): array
{ {
return [ return [
'no time between' => [ 'no time between' => [
@ -339,9 +340,7 @@ class DBDatetimeTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideGetTimeBetween')]
* @dataProvider provideGetTimeBetween
*/
public function testGetTimeBetween(string $timeBefore, string $timeAfter, string $expected): void public function testGetTimeBetween(string $timeBefore, string $timeAfter, string $expected): void
{ {
$before = (new DBDateTime())->setValue($timeBefore); $before = (new DBDateTime())->setValue($timeBefore);

View File

@ -6,6 +6,7 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\FieldType\DBEnum; use SilverStripe\ORM\FieldType\DBEnum;
use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\DB; use SilverStripe\ORM\DB;
use PHPUnit\Framework\Attributes\DataProvider;
class DBEnumTest extends SapphireTest class DBEnumTest extends SapphireTest
{ {
@ -17,11 +18,11 @@ class DBEnumTest extends SapphireTest
protected $usesDatabase = true; protected $usesDatabase = true;
/** /**
* @dataProvider provideParse
* *
* nullifyEmpty is an option on DBString, which DBEnum extends * nullifyEmpty is an option on DBString, which DBEnum extends
* Mainly used for testing that Enum short-array style syntax works while passing in options * Mainly used for testing that Enum short-array style syntax works while passing in options
*/ */
#[DataProvider('provideParse')]
public function testParse(?string $expectedDefault, bool $expectedNullifyEmpty, string $spec) public function testParse(?string $expectedDefault, bool $expectedNullifyEmpty, string $spec)
{ {
/** @var DBEnum $enum */ /** @var DBEnum $enum */
@ -31,7 +32,7 @@ class DBEnumTest extends SapphireTest
$this->assertEquals($expectedNullifyEmpty, $enum->getNullifyEmpty()); $this->assertEquals($expectedNullifyEmpty, $enum->getNullifyEmpty());
} }
public function provideParse() public static function provideParse()
{ {
return [ return [
// standard syntax - double quotes // standard syntax - double quotes

View File

@ -29,6 +29,7 @@ use SilverStripe\ORM\FieldType\DBText;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\FieldType\DBYear; use SilverStripe\ORM\FieldType\DBYear;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Tests for DBField objects. * Tests for DBField objects.
@ -206,9 +207,7 @@ class DBFieldTest extends SapphireTest
$this->assertEquals(PHP_INT_MAX, $bigInt->getValue()); $this->assertEquals(PHP_INT_MAX, $bigInt->getValue());
} }
/** #[DataProvider('dataProviderPrepValueForDBArrayValue')]
* @dataProvider dataProviderPrepValueForDBArrayValue
*/
public function testPrepValueForDBArrayValue($dbFieldName, $scalarValueOnly, $extraArgs = []) public function testPrepValueForDBArrayValue($dbFieldName, $scalarValueOnly, $extraArgs = [])
{ {
$reflection = new \ReflectionClass($dbFieldName); $reflection = new \ReflectionClass($dbFieldName);
@ -226,7 +225,7 @@ class DBFieldTest extends SapphireTest
$this->assertEquals($scalarValueOnly, $dbField->scalarValueOnly()); $this->assertEquals($scalarValueOnly, $dbField->scalarValueOnly());
} }
public function dataProviderPrepValueForDBArrayValue() public static function dataProviderPrepValueForDBArrayValue()
{ {
return [ return [
[DBBigInt::class, true], [DBBigInt::class, true],

View File

@ -11,6 +11,7 @@ use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Tests\DBHTMLTextTest\TestShortcode; use SilverStripe\ORM\Tests\DBHTMLTextTest\TestShortcode;
use SilverStripe\View\Parsers\ShortcodeParser; use SilverStripe\View\Parsers\ShortcodeParser;
use PHPUnit\Framework\Attributes\DataProvider;
class DBHTMLTextTest extends SapphireTest class DBHTMLTextTest extends SapphireTest
{ {
@ -45,7 +46,7 @@ class DBHTMLTextTest extends SapphireTest
/** /**
* Test {@link Text->LimitCharacters()} * Test {@link Text->LimitCharacters()}
*/ */
public function providerLimitCharacters() public static function providerLimitCharacters()
{ {
// HTML characters are stripped safely // HTML characters are stripped safely
return [ return [
@ -58,10 +59,10 @@ class DBHTMLTextTest extends SapphireTest
/** /**
* Test {@link DBHTMLText->LimitCharacters()} * Test {@link DBHTMLText->LimitCharacters()}
* *
* @dataProvider providerLimitCharacters
* @param string $originalValue * @param string $originalValue
* @param string $expectedValue * @param string $expectedValue
*/ */
#[DataProvider('providerLimitCharacters')]
public function testLimitCharacters($originalValue, $expectedValue) public function testLimitCharacters($originalValue, $expectedValue)
{ {
$textObj = DBField::create_field('HTMLFragment', $originalValue); $textObj = DBField::create_field('HTMLFragment', $originalValue);
@ -72,7 +73,7 @@ class DBHTMLTextTest extends SapphireTest
/** /**
* @return array * @return array
*/ */
public function providerLimitCharactersToClosestWord() public static function providerLimitCharactersToClosestWord()
{ {
// HTML is converted safely to plain text // HTML is converted safely to plain text
return [ return [
@ -98,12 +99,12 @@ class DBHTMLTextTest extends SapphireTest
/** /**
* Test {@link DBHTMLText->LimitCharactersToClosestWord()} * Test {@link DBHTMLText->LimitCharactersToClosestWord()}
* *
* @dataProvider providerLimitCharactersToClosestWord
* *
* @param string $originalValue Raw string input * @param string $originalValue Raw string input
* @param int $limit * @param int $limit
* @param string $expectedValue Expected template value * @param string $expectedValue Expected template value
*/ */
#[DataProvider('providerLimitCharactersToClosestWord')]
public function testLimitCharactersToClosestWord($originalValue, $limit, $expectedValue) public function testLimitCharactersToClosestWord($originalValue, $limit, $expectedValue)
{ {
$textObj = DBField::create_field('HTMLFragment', $originalValue); $textObj = DBField::create_field('HTMLFragment', $originalValue);
@ -111,7 +112,7 @@ class DBHTMLTextTest extends SapphireTest
$this->assertEquals($expectedValue, $result); $this->assertEquals($expectedValue, $result);
} }
public function providerSummary() public static function providerSummary()
{ {
return [ return [
[ [
@ -167,11 +168,11 @@ class DBHTMLTextTest extends SapphireTest
} }
/** /**
* @dataProvider providerSummary
* @param string $originalValue * @param string $originalValue
* @param int $limit * @param int $limit
* @param string $expectedValue * @param string $expectedValue
*/ */
#[DataProvider('providerSummary')]
public function testSummary($originalValue, $limit, $expectedValue) public function testSummary($originalValue, $limit, $expectedValue)
{ {
$textObj = DBField::create_field('HTMLFragment', $originalValue); $textObj = DBField::create_field('HTMLFragment', $originalValue);
@ -199,7 +200,7 @@ class DBHTMLTextTest extends SapphireTest
public function providerFirstSentence() public static function providerFirstSentence()
{ {
return [ return [
// Same behaviour as DBTextTest // Same behaviour as DBTextTest
@ -216,10 +217,10 @@ class DBHTMLTextTest extends SapphireTest
} }
/** /**
* @dataProvider providerFirstSentence
* @param string $originalValue * @param string $originalValue
* @param string $expectedValue * @param string $expectedValue
*/ */
#[DataProvider('providerFirstSentence')]
public function testFirstSentence($originalValue, $expectedValue) public function testFirstSentence($originalValue, $expectedValue)
{ {
$textObj = DBField::create_field('HTMLFragment', $originalValue); $textObj = DBField::create_field('HTMLFragment', $originalValue);
@ -251,7 +252,7 @@ class DBHTMLTextTest extends SapphireTest
$this->assertEquals(['a'], $field->getWhitelist()); $this->assertEquals(['a'], $field->getWhitelist());
} }
public function providerToPlain() public static function providerToPlain()
{ {
return [ return [
[ [
@ -274,10 +275,10 @@ class DBHTMLTextTest extends SapphireTest
} }
/** /**
* @dataProvider providerToPlain
* @param string $html * @param string $html
* @param string $plain * @param string $plain
*/ */
#[DataProvider('providerToPlain')]
public function testToPlain($html, $plain) public function testToPlain($html, $plain)
{ {
/** /**
@ -292,7 +293,7 @@ class DBHTMLTextTest extends SapphireTest
* *
* @return array * @return array
*/ */
public function providerContextSummary() public static function providerContextSummary()
{ {
return [ return [
[ [
@ -358,12 +359,12 @@ class DBHTMLTextTest extends SapphireTest
} }
/** /**
* @dataProvider providerContextSummary
* @param string $originalValue Input * @param string $originalValue Input
* @param int $limit Number of characters * @param int $limit Number of characters
* @param string $keywords Keywords to highlight * @param string $keywords Keywords to highlight
* @param string $expectedValue Expected output (XML encoded safely) * @param string $expectedValue Expected output (XML encoded safely)
*/ */
#[DataProvider('providerContextSummary')]
public function testContextSummary($originalValue, $limit, $keywords, $expectedValue) public function testContextSummary($originalValue, $limit, $keywords, $expectedValue)
{ {
$text = DBField::create_field('HTMLFragment', $originalValue); $text = DBField::create_field('HTMLFragment', $originalValue);

View File

@ -7,12 +7,14 @@ use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Connect\DBSchemaManager; use SilverStripe\ORM\Connect\DBSchemaManager;
use SilverStripe\ORM\Tests\DBSchemaManagerTest\ChildClass; use SilverStripe\ORM\Tests\DBSchemaManagerTest\ChildClass;
use PHPUnit\Framework\Attributes\DataProvider;
use SilverStripe\ORM\Tests\DBSchemaManagerTest\TestDBSchemaManager;
class DBSchemaManagerTest extends SapphireTest class DBSchemaManagerTest extends SapphireTest
{ {
protected $usesDatabase = false; protected $usesDatabase = false;
public function provideCanCheckAndRepairTable() public static function provideCanCheckAndRepairTable()
{ {
return [ return [
// not ignored, but globally not allowed // not ignored, but globally not allowed
@ -48,9 +50,7 @@ class DBSchemaManagerTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideCanCheckAndRepairTable')]
* @dataProvider provideCanCheckAndRepairTable
*/
public function testCanCheckAndRepairTable(string $tableName, bool $checkAndRepairOnBuild, bool $expected) public function testCanCheckAndRepairTable(string $tableName, bool $checkAndRepairOnBuild, bool $expected)
{ {
// set config // set config
@ -72,6 +72,6 @@ class DBSchemaManagerTest extends SapphireTest
*/ */
private function getConcreteSchemaManager(): DBSchemaManager private function getConcreteSchemaManager(): DBSchemaManager
{ {
return $this->getMockBuilder(DBSchemaManager::class)->getMockForAbstractClass(); return new TestDBSchemaManager();
} }
} }

View File

@ -0,0 +1,170 @@
<?php
namespace SilverStripe\ORM\Tests\DBSchemaManagerTest;
use SilverStripe\ORM\Connect\DBSchemaManager;
class TestDBSchemaManager extends DBSchemaManager
{
public function hasTable($tableName)
{
return true;
}
public function IdColumn($asDbValue = false, $hasAutoIncPK = true)
{
return '';
}
public function checkAndRepairTable($tableName)
{
return true;
}
public function enumValuesForField($tableName, $fieldName)
{
return [];
}
public function dbDataType($type)
{
return '';
}
public function databaseList()
{
return [];
}
public function databaseExists($name)
{
return true;
}
public function createDatabase($name)
{
return true;
}
public function dropDatabase($name)
{
return '';
}
public function alterIndex($tableName, $indexName, $indexSpec)
{
}
protected function indexKey($table, $index, $spec)
{
return '';
}
public function indexList($table)
{
return [];
}
public function tableList()
{
return [];
}
public function createTable(
$table,
$fields = null,
$indexes = null,
$options = null,
$advancedOptions = null
) {
return '';
}
public function alterTable(
$table,
$newFields = null,
$newIndexes = null,
$alteredFields = null,
$alteredIndexes = null,
$alteredOptions = null,
$advancedOptions = null
) {
}
public function renameTable($oldTableName, $newTableName)
{
}
function createField($table, $field, $spec)
{
}
function renameField($tableName, $oldName, $newName)
{
}
function fieldList($table)
{
return [];
}
function boolean($values)
{
return '';
}
function date($values)
{
return '';
}
function decimal($values)
{
return '';
}
function enum($values)
{
return '';
}
function set($values)
{
return '';
}
function float($values)
{
return '';
}
function int($values)
{
return '';
}
function datetime($values)
{
return '';
}
function text($values)
{
return '';
}
function time($values)
{
return '';
}
function varchar($values)
{
return '';
}
function year($values)
{
return '';
}
}

View File

@ -11,9 +11,6 @@ use SilverStripe\ORM\Tests\DBStringTest\MyStringField;
class DBStringTest extends SapphireTest class DBStringTest extends SapphireTest
{ {
/**
* @covers \SilverStripe\ORM\FieldType\DBField::forTemplate()
*/
public function testForTemplate() public function testForTemplate()
{ {
$this->assertEquals( $this->assertEquals(
@ -35,9 +32,6 @@ class DBStringTest extends SapphireTest
); );
} }
/**
* @covers \SilverStripe\ORM\FieldType\DBString::LowerCase()
*/
public function testLowerCase() public function testLowerCase()
{ {
/** @var MyStringField $field */ /** @var MyStringField $field */
@ -48,9 +42,6 @@ class DBStringTest extends SapphireTest
); );
} }
/**
* @covers \SilverStripe\ORM\FieldType\DBString::UpperCase()
*/
public function testUpperCase() public function testUpperCase()
{ {
/** @var MyStringField $field */ /** @var MyStringField $field */

View File

@ -5,6 +5,7 @@ namespace SilverStripe\ORM\Tests;
use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\FieldType\DBText; use SilverStripe\ORM\FieldType\DBText;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Tests parsing and summary methods on DBText * Tests parsing and summary methods on DBText
@ -33,7 +34,7 @@ class DBTextTest extends SapphireTest
/** /**
* Test {@link Text->LimitCharacters()} * Test {@link Text->LimitCharacters()}
*/ */
public function providerLimitCharacters() public static function providerLimitCharacters()
{ {
// Plain text values always encoded safely // Plain text values always encoded safely
// HTML stored in non-html fields is treated literally. // HTML stored in non-html fields is treated literally.
@ -48,10 +49,10 @@ class DBTextTest extends SapphireTest
/** /**
* Test {@link Text->LimitCharacters()} * Test {@link Text->LimitCharacters()}
* *
* @dataProvider providerLimitCharacters
* @param string $originalValue * @param string $originalValue
* @param string $expectedValue * @param string $expectedValue
*/ */
#[DataProvider('providerLimitCharacters')]
public function testLimitCharacters($originalValue, $expectedValue) public function testLimitCharacters($originalValue, $expectedValue)
{ {
$textObj = DBField::create_field('Text', $originalValue); $textObj = DBField::create_field('Text', $originalValue);
@ -62,7 +63,7 @@ class DBTextTest extends SapphireTest
/** /**
* @return array * @return array
*/ */
public function providerLimitCharactersToClosestWord() public static function providerLimitCharactersToClosestWord()
{ {
return [ return [
// Standard words limited, ellipsis added if truncated // Standard words limited, ellipsis added if truncated
@ -91,12 +92,12 @@ class DBTextTest extends SapphireTest
/** /**
* Test {@link Text->LimitCharactersToClosestWord()} * Test {@link Text->LimitCharactersToClosestWord()}
* *
* @dataProvider providerLimitCharactersToClosestWord
* *
* @param string $originalValue Raw string input * @param string $originalValue Raw string input
* @param int $limit * @param int $limit
* @param string $expectedValue Expected template value * @param string $expectedValue Expected template value
*/ */
#[DataProvider('providerLimitCharactersToClosestWord')]
public function testLimitCharactersToClosestWord($originalValue, $limit, $expectedValue) public function testLimitCharactersToClosestWord($originalValue, $limit, $expectedValue)
{ {
$textObj = DBField::create_field('Text', $originalValue); $textObj = DBField::create_field('Text', $originalValue);
@ -107,7 +108,7 @@ class DBTextTest extends SapphireTest
/** /**
* Test {@link Text->LimitWordCount()} * Test {@link Text->LimitWordCount()}
*/ */
public function providerLimitWordCount() public static function providerLimitWordCount()
{ {
return [ return [
// Standard words limited, ellipsis added if truncated // Standard words limited, ellipsis added if truncated
@ -137,12 +138,12 @@ class DBTextTest extends SapphireTest
/** /**
* Test {@link DBText->LimitWordCount()} * Test {@link DBText->LimitWordCount()}
* *
* @dataProvider providerLimitWordCount
* *
* @param string $originalValue Raw string input * @param string $originalValue Raw string input
* @param int $limit Number of words * @param int $limit Number of words
* @param string $expectedValue Expected template value * @param string $expectedValue Expected template value
*/ */
#[DataProvider('providerLimitWordCount')]
public function testLimitWordCount($originalValue, $limit, $expectedValue) public function testLimitWordCount($originalValue, $limit, $expectedValue)
{ {
$textObj = DBField::create_field('Text', $originalValue); $textObj = DBField::create_field('Text', $originalValue);
@ -150,9 +151,7 @@ class DBTextTest extends SapphireTest
$this->assertEquals($expectedValue, $result); $this->assertEquals($expectedValue, $result);
} }
/** public static function providerLimitSentences()
*/
public function providerLimitSentences()
{ {
return [ return [
['', 2, ''], ['', 2, ''],
@ -172,11 +171,11 @@ class DBTextTest extends SapphireTest
/** /**
* Test {@link DBText->LimitSentences()} * Test {@link DBText->LimitSentences()}
* *
* @dataProvider providerLimitSentences
* @param string $originalValue * @param string $originalValue
* @param int $limit Number of sentences * @param int $limit Number of sentences
* @param string $expectedValue Expected template value * @param string $expectedValue Expected template value
*/ */
#[DataProvider('providerLimitSentences')]
public function testLimitSentences($originalValue, $limit, $expectedValue) public function testLimitSentences($originalValue, $limit, $expectedValue)
{ {
$textObj = DBField::create_field('Text', $originalValue); $textObj = DBField::create_field('Text', $originalValue);
@ -184,7 +183,7 @@ class DBTextTest extends SapphireTest
$this->assertEquals($expectedValue, $result); $this->assertEquals($expectedValue, $result);
} }
public function providerFirstSentence() public static function providerFirstSentence()
{ {
return [ return [
['', ''], ['', ''],
@ -204,10 +203,10 @@ class DBTextTest extends SapphireTest
} }
/** /**
* @dataProvider providerFirstSentence
* @param string $originalValue * @param string $originalValue
* @param string $expectedValue * @param string $expectedValue
*/ */
#[DataProvider('providerFirstSentence')]
public function testFirstSentence($originalValue, $expectedValue) public function testFirstSentence($originalValue, $expectedValue)
{ {
$textObj = DBField::create_field('Text', $originalValue); $textObj = DBField::create_field('Text', $originalValue);
@ -220,7 +219,7 @@ class DBTextTest extends SapphireTest
* *
* @return array * @return array
*/ */
public function providerContextSummary() public static function providerContextSummary()
{ {
return [ return [
[ [
@ -279,7 +278,7 @@ class DBTextTest extends SapphireTest
* *
* @return array * @return array
*/ */
public function providerSummary() public static function providerSummary()
{ {
return [ return [
'simple test' => [ 'simple test' => [
@ -336,12 +335,12 @@ class DBTextTest extends SapphireTest
} }
/** /**
* @dataProvider providerContextSummary
* @param string $originalValue Input * @param string $originalValue Input
* @param int $limit Number of characters * @param int $limit Number of characters
* @param string $keywords Keywords to highlight * @param string $keywords Keywords to highlight
* @param string $expectedValue Expected output (XML encoded safely) * @param string $expectedValue Expected output (XML encoded safely)
*/ */
#[DataProvider('providerContextSummary')]
public function testContextSummary($originalValue, $limit, $keywords, $expectedValue) public function testContextSummary($originalValue, $limit, $keywords, $expectedValue)
{ {
$text = DBField::create_field('Text', $originalValue); $text = DBField::create_field('Text', $originalValue);
@ -413,12 +412,12 @@ class DBTextTest extends SapphireTest
} }
/** /**
* @dataProvider providerSummary
* @param string $originalValue Input * @param string $originalValue Input
* @param int $words Number of words * @param int $words Number of words
* @param mixed $add Ellipsis (false for default or string for custom text) * @param mixed $add Ellipsis (false for default or string for custom text)
* @param string $expectedValue Expected output (XML encoded safely) * @param string $expectedValue Expected output (XML encoded safely)
*/ */
#[DataProvider('providerSummary')]
public function testSummary($originalValue, $words, $add, $expectedValue) public function testSummary($originalValue, $words, $add, $expectedValue)
{ {
$text = DBField::create_field(DBText::class, $originalValue); $text = DBField::create_field(DBText::class, $originalValue);

View File

@ -7,6 +7,7 @@ use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\FieldType\DBTime; use SilverStripe\ORM\FieldType\DBTime;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use PHPUnit\Framework\Attributes\DataProvider;
class DBTimeTest extends SapphireTest class DBTimeTest extends SapphireTest
{ {
@ -16,7 +17,7 @@ class DBTimeTest extends SapphireTest
i18n::set_locale('en_NZ'); i18n::set_locale('en_NZ');
} }
public function dataTestParse() public static function dataTestParse()
{ {
return [ return [
// Test am-pm conversion // Test am-pm conversion
@ -31,10 +32,10 @@ class DBTimeTest extends SapphireTest
} }
/** /**
* @dataProvider dataTestParse
* @param string $input * @param string $input
* @param string $expected * @param string $expected
*/ */
#[DataProvider('dataTestParse')]
public function testParse($input, $expected) public function testParse($input, $expected)
{ {
$time = DBField::create_field('Time', $input); $time = DBField::create_field('Time', $input);

View File

@ -39,6 +39,7 @@ use SilverStripe\ORM\Tests\DataListTest\EagerLoading\BelongsManyManySubSubEagerL
use SilverStripe\ORM\Tests\DataListTest\EagerLoading\MixedHasManyEagerLoadObject; use SilverStripe\ORM\Tests\DataListTest\EagerLoading\MixedHasManyEagerLoadObject;
use SilverStripe\ORM\Tests\DataListTest\EagerLoading\MixedHasOneEagerLoadObject; use SilverStripe\ORM\Tests\DataListTest\EagerLoading\MixedHasOneEagerLoadObject;
use SilverStripe\ORM\Tests\DataListTest\EagerLoading\MixedManyManyEagerLoadObject; use SilverStripe\ORM\Tests\DataListTest\EagerLoading\MixedManyManyEagerLoadObject;
use PHPUnit\Framework\Attributes\DataProvider;
class DataListEagerLoadingTest extends SapphireTest class DataListEagerLoadingTest extends SapphireTest
{ {
@ -162,9 +163,7 @@ class DataListEagerLoadingTest extends SapphireTest
$this->showQueries = DataListEagerLoadingTest::SHOW_QUERIES_RESET; $this->showQueries = DataListEagerLoadingTest::SHOW_QUERIES_RESET;
} }
/** #[DataProvider('provideEagerLoadRelations')]
* @dataProvider provideEagerLoadRelations
*/
public function testEagerLoadRelations(string $iden, array $eagerLoad, int $expected): void public function testEagerLoadRelations(string $iden, array $eagerLoad, int $expected): void
{ {
$this->createEagerLoadData(); $this->createEagerLoadData();
@ -180,7 +179,7 @@ class DataListEagerLoadingTest extends SapphireTest
$this->assertSame($expected, $selectCount); $this->assertSame($expected, $selectCount);
} }
public function provideEagerLoadRelations(): array public static function provideEagerLoadRelations(): array
{ {
return [ return [
// Include the lazy-loaded expectation here, since if the number // Include the lazy-loaded expectation here, since if the number
@ -756,9 +755,7 @@ class DataListEagerLoadingTest extends SapphireTest
return [$results, $selectCount]; return [$results, $selectCount];
} }
/** #[DataProvider('provideEagerLoadRelationsEmpty')]
* @dataProvider provideEagerLoadRelationsEmpty
*/
public function testEagerLoadRelationsEmpty(string $eagerLoadRelation, int $expectedNumQueries): void public function testEagerLoadRelationsEmpty(string $eagerLoadRelation, int $expectedNumQueries): void
{ {
EagerLoadObject::create(['Title' => 'test object'])->write(); EagerLoadObject::create(['Title' => 'test object'])->write();
@ -779,35 +776,35 @@ class DataListEagerLoadingTest extends SapphireTest
$this->assertSame($expectedNumQueries, $numQueries); $this->assertSame($expectedNumQueries, $numQueries);
} }
public function provideEagerLoadRelationsEmpty(): array public static function provideEagerLoadRelationsEmpty(): array
{ {
return [ return [
'has_one' => [ 'has_one' => [
'eagerLoad' => 'HasOneEagerLoadObject', 'eagerLoadRelation' => 'HasOneEagerLoadObject',
'expectedNumQueries' => 1, 'expectedNumQueries' => 1,
], ],
'polymorph_has_one' => [ 'polymorph_has_one' => [
'eagerLoad' => 'HasOnePolymorphObject', 'eagerLoadRelation' => 'HasOnePolymorphObject',
'expectedNumQueries' => 1, 'expectedNumQueries' => 1,
], ],
'belongs_to' => [ 'belongs_to' => [
'eagerLoad' => 'BelongsToEagerLoadObject', 'eagerLoadRelation' => 'BelongsToEagerLoadObject',
'expectedNumQueries' => 2, 'expectedNumQueries' => 2,
], ],
'has_many' => [ 'has_many' => [
'eagerLoad' => 'HasManyEagerLoadObjects', 'eagerLoadRelation' => 'HasManyEagerLoadObjects',
'expectedNumQueries' => 2, 'expectedNumQueries' => 2,
], ],
'many_many' => [ 'many_many' => [
'eagerLoad' => 'ManyManyEagerLoadObjects', 'eagerLoadRelation' => 'ManyManyEagerLoadObjects',
'expectedNumQueries' => 2, 'expectedNumQueries' => 2,
], ],
'many_many through' => [ 'many_many through' => [
'eagerLoad' => 'ManyManyThroughEagerLoadObjects', 'eagerLoadRelation' => 'ManyManyThroughEagerLoadObjects',
'expectedNumQueries' => 2, 'expectedNumQueries' => 2,
], ],
'belongs_many_many' => [ 'belongs_many_many' => [
'eagerLoad' => 'BelongsManyManyEagerLoadObjects', 'eagerLoadRelation' => 'BelongsManyManyEagerLoadObjects',
'expectedNumQueries' => 2, 'expectedNumQueries' => 2,
], ],
]; ];
@ -830,9 +827,7 @@ class DataListEagerLoadingTest extends SapphireTest
EagerLoadObject::get()->eagerLoad($eagerLoadRelation); EagerLoadObject::get()->eagerLoad($eagerLoadRelation);
} }
/** #[DataProvider('provideEagerLoadInvalidRelationException')]
* @dataProvider provideEagerLoadInvalidRelationException
*/
public function testEagerLoadInvalidRelationException(string $eagerLoadRelation): void public function testEagerLoadInvalidRelationException(string $eagerLoadRelation): void
{ {
$this->expectException(InvalidArgumentException::class); $this->expectException(InvalidArgumentException::class);
@ -841,7 +836,7 @@ class DataListEagerLoadingTest extends SapphireTest
EagerLoadObject::get()->eagerLoad($eagerLoadRelation)->toArray(); EagerLoadObject::get()->eagerLoad($eagerLoadRelation)->toArray();
} }
public function provideEagerLoadInvalidRelationException(): array public static function provideEagerLoadInvalidRelationException(): array
{ {
return [ return [
[ [
@ -856,9 +851,7 @@ class DataListEagerLoadingTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideEagerLoadManyManyExtraFields')]
* @dataProvider provideEagerLoadManyManyExtraFields
*/
public function testEagerLoadManyManyExtraFields(string $parentClass, string $eagerLoadRelation): void public function testEagerLoadManyManyExtraFields(string $parentClass, string $eagerLoadRelation): void
{ {
$this->createEagerLoadData(); $this->createEagerLoadData();
@ -887,7 +880,7 @@ class DataListEagerLoadingTest extends SapphireTest
} }
} }
public function provideEagerLoadManyManyExtraFields(): array public static function provideEagerLoadManyManyExtraFields(): array
{ {
return [ return [
[ [
@ -901,9 +894,7 @@ class DataListEagerLoadingTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideEagerLoadManyManyThroughJoinRecords')]
* @dataProvider provideEagerLoadManyManyThroughJoinRecords
*/
public function testEagerLoadManyManyThroughJoinRecords(string $parentClass, string $eagerLoadRelation): void public function testEagerLoadManyManyThroughJoinRecords(string $parentClass, string $eagerLoadRelation): void
{ {
$this->createEagerLoadData(); $this->createEagerLoadData();
@ -936,7 +927,7 @@ class DataListEagerLoadingTest extends SapphireTest
} }
} }
public function provideEagerLoadManyManyThroughJoinRecords(): array public static function provideEagerLoadManyManyThroughJoinRecords(): array
{ {
return [ return [
[ [
@ -950,10 +941,8 @@ class DataListEagerLoadingTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideEagerLoadRelations')]
* @dataProvider provideEagerLoadRelations public function testEagerLoadingFilteredList(string $iden, array $eagerLoad, int $expected): void
*/
public function testEagerLoadingFilteredList(string $iden, array $eagerLoad): void
{ {
$this->createEagerLoadData(5); $this->createEagerLoadData(5);
$filter = ['Title:GreaterThan' => 'obj 0']; $filter = ['Title:GreaterThan' => 'obj 0'];
@ -970,10 +959,8 @@ class DataListEagerLoadingTest extends SapphireTest
$this->validateEagerLoadingResults($iden, EagerLoadObject::get()->filter($filter), $dataList); $this->validateEagerLoadingResults($iden, EagerLoadObject::get()->filter($filter), $dataList);
} }
/** #[DataProvider('provideEagerLoadRelations')]
* @dataProvider provideEagerLoadRelations public function testEagerLoadingSortedList(string $iden, array $eagerLoad, int $expected): void
*/
public function testEagerLoadingSortedList(string $iden, array $eagerLoad): void
{ {
$this->createEagerLoadData(3); $this->createEagerLoadData(3);
$items = [ $items = [
@ -999,10 +986,8 @@ class DataListEagerLoadingTest extends SapphireTest
$this->validateEagerLoadingResults($iden, EagerLoadObject::get()->sort($sort), $dataList); $this->validateEagerLoadingResults($iden, EagerLoadObject::get()->sort($sort), $dataList);
} }
/** #[DataProvider('provideEagerLoadRelations')]
* @dataProvider provideEagerLoadRelations public function testEagerLoadingLimitedList(string $iden, array $eagerLoad, int $expected): void
*/
public function testEagerLoadingLimitedList(string $iden, array $eagerLoad): void
{ {
// Make sure to create more base records AND more records on at least one relation than the limit // Make sure to create more base records AND more records on at least one relation than the limit
// to ensure the limit isn't accidentally carried through to the relations. // to ensure the limit isn't accidentally carried through to the relations.
@ -1016,10 +1001,8 @@ class DataListEagerLoadingTest extends SapphireTest
$this->validateEagerLoadingResults($iden, EagerLoadObject::get()->limit($limit), $dataList); $this->validateEagerLoadingResults($iden, EagerLoadObject::get()->limit($limit), $dataList);
} }
/** #[DataProvider('provideEagerLoadRelations')]
* @dataProvider provideEagerLoadRelations public function testRepeatedIterationOfEagerLoadedList(string $iden, array $eagerLoad, int $expected): void
*/
public function testRepeatedIterationOfEagerLoadedList(string $iden, array $eagerLoad): void
{ {
// We need at least 3 base records for many_many relations to have fewer db queries than lazy-loaded lists. // We need at least 3 base records for many_many relations to have fewer db queries than lazy-loaded lists.
$this->createEagerLoadData(3); $this->createEagerLoadData(3);
@ -1034,10 +1017,9 @@ class DataListEagerLoadingTest extends SapphireTest
* This test validates that you can call eagerLoad() anywhere on the list before * This test validates that you can call eagerLoad() anywhere on the list before
* execution, including before or after sort/limit/filter, etc - and it will * execution, including before or after sort/limit/filter, etc - and it will
* work the same way regardless of when it was called. * work the same way regardless of when it was called.
*
* @dataProvider provideEagerLoadRelations
*/ */
public function testEagerLoadWorksAnywhereBeforeExecution(string $iden, array $eagerLoad): void #[DataProvider('provideEagerLoadRelations')]
public function testEagerLoadWorksAnywhereBeforeExecution(string $iden, array $eagerLoad, int $expected): void
{ {
$this->createEagerLoadData(7); $this->createEagerLoadData(7);
$filter = ['Title:LessThan' => 'obj 5']; $filter = ['Title:LessThan' => 'obj 5'];
@ -1066,10 +1048,8 @@ class DataListEagerLoadingTest extends SapphireTest
$this->validateEagerLoadingResults($iden, $lazyList, $eagerList4); $this->validateEagerLoadingResults($iden, $lazyList, $eagerList4);
} }
/** #[DataProvider('provideEagerLoadRelations')]
* @dataProvider provideEagerLoadRelations public function testEagerLoadWithChunkedFetch(string $iden, array $eagerLoad, int $expected): void
*/
public function testEagerLoadWithChunkedFetch(string $iden, array $eagerLoad): void
{ {
$this->createEagerLoadData(10); $this->createEagerLoadData(10);
$dataList = EagerLoadObject::get()->eagerLoad(...$eagerLoad); $dataList = EagerLoadObject::get()->eagerLoad(...$eagerLoad);
@ -1098,9 +1078,7 @@ class DataListEagerLoadingTest extends SapphireTest
} }
} }
/** #[DataProvider('provideEagerLoadingEmptyRelations')]
* @dataProvider provideEagerLoadingEmptyRelations
*/
public function testEagerLoadingEmptyRelations(string $iden, string $eagerLoad): void public function testEagerLoadingEmptyRelations(string $iden, string $eagerLoad): void
{ {
$numBaseRecords = 3; $numBaseRecords = 3;
@ -1251,7 +1229,7 @@ class DataListEagerLoadingTest extends SapphireTest
} }
} }
public function provideEagerLoadingEmptyRelations(): array public static function provideEagerLoadingEmptyRelations(): array
{ {
return [ return [
[ [
@ -1362,7 +1340,7 @@ class DataListEagerLoadingTest extends SapphireTest
EagerLoadObject::get()->eagerLoad(['HasManyEagerLoadObjects' => 'HasManyEagerLoadObjects']); EagerLoadObject::get()->eagerLoad(['HasManyEagerLoadObjects' => 'HasManyEagerLoadObjects']);
} }
public function provideNoLimitEagerLoadingQuery(): array public static function provideNoLimitEagerLoadingQuery(): array
{ {
// Note we don't test has_one or belongs_to because those don't accept a callback at all. // Note we don't test has_one or belongs_to because those don't accept a callback at all.
return [ return [
@ -1391,9 +1369,8 @@ class DataListEagerLoadingTest extends SapphireTest
/** /**
* Tests that attempting to limit an eagerloading query will throw an exception. * Tests that attempting to limit an eagerloading query will throw an exception.
*
* @dataProvider provideNoLimitEagerLoadingQuery
*/ */
#[DataProvider('provideNoLimitEagerLoadingQuery')]
public function testNoLimitEagerLoadingQuery(string $relation, string $relationType, callable $callback): void public function testNoLimitEagerLoadingQuery(string $relation, string $relationType, callable $callback): void
{ {
// Need to have at least one record in the main list for eagerloading to even be triggered. // Need to have at least one record in the main list for eagerloading to even be triggered.
@ -1407,7 +1384,7 @@ class DataListEagerLoadingTest extends SapphireTest
EagerLoadObject::get()->eagerLoad([$relation => $callback])->toArray(); EagerLoadObject::get()->eagerLoad([$relation => $callback])->toArray();
} }
public function provideCannotManipulateUnaryRelationQuery(): array public static function provideCannotManipulateUnaryRelationQuery(): array
{ {
return [ return [
'has_one' => [ 'has_one' => [
@ -1423,9 +1400,8 @@ class DataListEagerLoadingTest extends SapphireTest
/** /**
* Tests that attempting to manipulate a has_one or belongs_to eagerloading query will throw an exception. * Tests that attempting to manipulate a has_one or belongs_to eagerloading query will throw an exception.
*
* @dataProvider provideCannotManipulateUnaryRelationQuery
*/ */
#[DataProvider('provideCannotManipulateUnaryRelationQuery')]
public function testCannotManipulateUnaryRelationQuery(string $relation, string $relationType): void public function testCannotManipulateUnaryRelationQuery(string $relation, string $relationType): void
{ {
// Need to have at least one record in the main list for eagerloading to even be triggered. // Need to have at least one record in the main list for eagerloading to even be triggered.
@ -1458,7 +1434,7 @@ class DataListEagerLoadingTest extends SapphireTest
])->toArray(); ])->toArray();
} }
public function provideManipulatingEagerloadingQuery(): array public static function provideManipulatingEagerloadingQuery(): array
{ {
return [ return [
'nested has_many' => [ 'nested has_many' => [
@ -1586,9 +1562,8 @@ class DataListEagerLoadingTest extends SapphireTest
/** /**
* Tests that callbacks can be used to manipulate eagerloading queries * Tests that callbacks can be used to manipulate eagerloading queries
*
* @dataProvider provideManipulatingEagerloadingQuery
*/ */
#[DataProvider('provideManipulatingEagerloadingQuery')]
public function testManipulatingEagerloadingQuery(string $relationType, array $relations, array $eagerLoad, array $expected): void public function testManipulatingEagerloadingQuery(string $relationType, array $relations, array $eagerLoad, array $expected): void
{ {
$relationNames = array_keys($relations); $relationNames = array_keys($relations);

View File

@ -34,6 +34,7 @@ use SilverStripe\ORM\FieldType\DBVarchar;
use SilverStripe\ORM\Filters\SearchFilter; use SilverStripe\ORM\Filters\SearchFilter;
use SilverStripe\ORM\Tests\DataObjectTest\RelationChildFirst; use SilverStripe\ORM\Tests\DataObjectTest\RelationChildFirst;
use SilverStripe\ORM\Tests\DataObjectTest\RelationChildSecond; use SilverStripe\ORM\Tests\DataObjectTest\RelationChildSecond;
use PHPUnit\Framework\Attributes\DataProvider;
class DataListTest extends SapphireTest class DataListTest extends SapphireTest
{ {
@ -89,7 +90,7 @@ class DataListTest extends SapphireTest
$this->assertEquals(2, count($list ?? [])); $this->assertEquals(2, count($list ?? []));
} }
public function provideDefaultCaseSensitivity() public static function provideDefaultCaseSensitivity()
{ {
return [ return [
[ [
@ -135,9 +136,7 @@ class DataListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideDefaultCaseSensitivity')]
* @dataProvider provideDefaultCaseSensitivity
*/
public function testDefaultCaseSensitivity(bool $caseSensitive, array $filter, int $expectedCount) public function testDefaultCaseSensitivity(bool $caseSensitive, array $filter, int $expectedCount)
{ {
SearchFilter::config()->set('default_case_sensitive', $caseSensitive); SearchFilter::config()->set('default_case_sensitive', $caseSensitive);
@ -203,7 +202,7 @@ class DataListTest extends SapphireTest
$this->assertEquals(['Joe', 'Phil'], $list->limit(2, 1)->column('Name')); $this->assertEquals(['Joe', 'Phil'], $list->limit(2, 1)->column('Name'));
} }
public function limitDataProvider(): array public static function limitDataProvider(): array
{ {
return [ return [
'no limit' => [null, 0, 3], 'no limit' => [null, 0, 3],
@ -220,9 +219,7 @@ class DataListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('limitDataProvider')]
* @dataProvider limitDataProvider
*/
public function testLimitAndOffset($length, $offset, $expectedCount, $expectException = false) public function testLimitAndOffset($length, $offset, $expectedCount, $expectException = false)
{ {
$list = TeamComment::get(); $list = TeamComment::get();
@ -304,7 +301,7 @@ class DataListTest extends SapphireTest
$this->assertSQLEquals($expected, $list->sql($parameters)); $this->assertSQLEquals($expected, $list->sql($parameters));
} }
public function provideJoin() public static function provideJoin()
{ {
return [ return [
[ [
@ -322,9 +319,7 @@ class DataListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideJoin')]
* @dataProvider provideJoin
*/
public function testJoin(string $joinMethod, string $joinType) public function testJoin(string $joinMethod, string $joinType)
{ {
$db = DB::get_conn(); $db = DB::get_conn();
@ -352,9 +347,7 @@ class DataListTest extends SapphireTest
$this->assertEmpty($parameters); $this->assertEmpty($parameters);
} }
/** #[DataProvider('provideJoin')]
* @dataProvider provideJoin
*/
public function testJoinParameterised(string $joinMethod, string $joinType) public function testJoinParameterised(string $joinMethod, string $joinType)
{ {
$db = DB::get_conn(); $db = DB::get_conn();
@ -680,7 +673,7 @@ class DataListTest extends SapphireTest
public function testSortInvalidParameters() public function testSortInvalidParameters()
{ {
$this->expectException(InvalidArgumentException::class); $this->expectException(InvalidArgumentException::class);
$this->expectDeprecationMessage('Fans is not a linear relation on model SilverStripe\ORM\Tests\DataObjectTest\Player'); $this->expectExceptionMessage('Fans is not a linear relation on model SilverStripe\ORM\Tests\DataObjectTest\Player');
$list = Team::get(); $list = Team::get();
$list->sort('Founder.Fans.Surname'); // Can't sort on has_many $list->sort('Founder.Fans.Surname'); // Can't sort on has_many
} }
@ -1897,9 +1890,6 @@ class DataListTest extends SapphireTest
$this->assertEquals('Phil', $list->last()->Name, 'Last comment should be from Phil'); $this->assertEquals('Phil', $list->last()->Name, 'Last comment should be from Phil');
} }
/**
*
*/
public function testSortByRelation() public function testSortByRelation()
{ {
$list = TeamComment::get(); $list = TeamComment::get();
@ -1948,9 +1938,7 @@ class DataListTest extends SapphireTest
); );
} }
/** #[DataProvider('provideRawSqlSortException')]
* @dataProvider provideRawSqlSortException
*/
public function testRawSqlSort(string $sort, string $type): void public function testRawSqlSort(string $sort, string $type): void
{ {
$type = explode('|', $type)[0]; $type = explode('|', $type)[0];
@ -1978,9 +1966,7 @@ class DataListTest extends SapphireTest
Team::get()->sort($sort)->column('ID'); Team::get()->sort($sort)->column('ID');
} }
/** #[DataProvider('provideRawSqlSortException')]
* @dataProvider provideRawSqlSortException
*/
public function testRawSqlOrderBy(string $sort, string $type): void public function testRawSqlOrderBy(string $sort, string $type): void
{ {
$type = explode('|', $type)[1]; $type = explode('|', $type)[1];
@ -2005,7 +1991,7 @@ class DataListTest extends SapphireTest
Team::get()->orderBy($sort)->column('ID'); Team::get()->orderBy($sort)->column('ID');
} }
public function provideRawSqlSortException(): array public static function provideRawSqlSortException(): array
{ {
return [ return [
['Title', 'valid|valid'], ['Title', 'valid|valid'],
@ -2033,9 +2019,7 @@ class DataListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideSortDirectionValidationTwoArgs')]
* @dataProvider provideSortDirectionValidationTwoArgs
*/
public function testSortDirectionValidationTwoArgs(string $direction, string $type): void public function testSortDirectionValidationTwoArgs(string $direction, string $type): void
{ {
if ($type === 'valid') { if ($type === 'valid') {
@ -2047,7 +2031,7 @@ class DataListTest extends SapphireTest
Team::get()->sort('Title', $direction)->column('ID'); Team::get()->sort('Title', $direction)->column('ID');
} }
public function provideSortDirectionValidationTwoArgs(): array public static function provideSortDirectionValidationTwoArgs(): array
{ {
return [ return [
['ASC', 'valid'], ['ASC', 'valid'],
@ -2060,9 +2044,8 @@ class DataListTest extends SapphireTest
/** /**
* Test passing scalar values to sort() * Test passing scalar values to sort()
*
* @dataProvider provideSortScalarValues
*/ */
#[DataProvider('provideSortScalarValues')]
public function testSortScalarValues(mixed $emtpyValue, string $type): void public function testSortScalarValues(mixed $emtpyValue, string $type): void
{ {
$this->assertSame(['Subteam 1'], Team::get()->limit(1)->column('Title')); $this->assertSame(['Subteam 1'], Team::get()->limit(1)->column('Title'));
@ -2080,7 +2063,7 @@ class DataListTest extends SapphireTest
$this->assertSame(['Subteam 1'], $list->limit(1)->column('Title')); $this->assertSame(['Subteam 1'], $list->limit(1)->column('Title'));
} }
public function provideSortScalarValues(): array public static function provideSortScalarValues(): array
{ {
return [ return [
['', 'empty-scalar'], ['', 'empty-scalar'],
@ -2261,9 +2244,7 @@ class DataListTest extends SapphireTest
$list->offsetUnset(0); $list->offsetUnset(0);
} }
/** #[DataProvider('provideRelation')]
* @dataProvider provideRelation
*/
public function testRelation(string $parentClass, string $relation, ?array $expected) public function testRelation(string $parentClass, string $relation, ?array $expected)
{ {
$list = $parentClass::get()->relation($relation); $list = $parentClass::get()->relation($relation);
@ -2274,7 +2255,7 @@ class DataListTest extends SapphireTest
} }
} }
public function provideRelation() public static function provideRelation()
{ {
return [ return [
'many_many' => [ 'many_many' => [
@ -2302,9 +2283,7 @@ class DataListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideCreateDataObject')]
* @dataProvider provideCreateDataObject
*/
public function testCreateDataObject(string $dataClass, string $realClass, array $row) public function testCreateDataObject(string $dataClass, string $realClass, array $row)
{ {
$list = new DataList($dataClass); $list = new DataList($dataClass);
@ -2326,7 +2305,7 @@ class DataListTest extends SapphireTest
} }
} }
public function provideCreateDataObject() public static function provideCreateDataObject()
{ {
return [ return [
'no ClassName' => [ 'no ClassName' => [

View File

@ -21,6 +21,7 @@ use SilverStripe\ORM\Tests\DataObjectSchemaTest\HasIndexesInFieldSpecs;
use SilverStripe\ORM\Tests\DataObjectSchemaTest\NoFields; use SilverStripe\ORM\Tests\DataObjectSchemaTest\NoFields;
use SilverStripe\ORM\Tests\DataObjectSchemaTest\WithCustomTable; use SilverStripe\ORM\Tests\DataObjectSchemaTest\WithCustomTable;
use SilverStripe\ORM\Tests\DataObjectSchemaTest\WithRelation; use SilverStripe\ORM\Tests\DataObjectSchemaTest\WithRelation;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* Tests schema inspection of DataObjects * Tests schema inspection of DataObjects
@ -159,9 +160,7 @@ class DataObjectSchemaTest extends SapphireTest
); );
} }
/** #[DataProvider('provideFieldSpec')]
* @dataProvider provideFieldSpec
*/
public function testFieldSpec(array $args, array $expected): void public function testFieldSpec(array $args, array $expected): void
{ {
$schema = DataObject::getSchema(); $schema = DataObject::getSchema();
@ -173,7 +172,7 @@ class DataObjectSchemaTest extends SapphireTest
$this->assertEquals($expected, $schema->fieldSpecs(...$args)); $this->assertEquals($expected, $schema->fieldSpecs(...$args));
} }
public function provideFieldSpec(): array public static function provideFieldSpec(): array
{ {
return [ return [
'just pass a class' => [ 'just pass a class' => [
@ -254,9 +253,6 @@ class DataObjectSchemaTest extends SapphireTest
]; ];
} }
/**
* @covers \SilverStripe\ORM\DataObjectSchema::baseDataClass()
*/
public function testBaseDataClass() public function testBaseDataClass()
{ {
$schema = DataObject::getSchema(); $schema = DataObject::getSchema();
@ -405,16 +401,14 @@ class DataObjectSchemaTest extends SapphireTest
); );
} }
/** #[DataProvider('provideHasOneComponent')]
* @dataProvider provideHasOneComponent
*/
public function testHasOneComponent(string $class, string $component, string $expected): void public function testHasOneComponent(string $class, string $component, string $expected): void
{ {
$this->assertSame($expected, DataObject::getSchema()->hasOneComponent($class, $component)); $this->assertSame($expected, DataObject::getSchema()->hasOneComponent($class, $component));
} }
public function provideHasOneComponent(): array public static function provideHasOneComponent(): array
{ {
return [ return [
[ [
@ -440,9 +434,7 @@ class DataObjectSchemaTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideHasOneComponentHandlesMultipleRelations')]
* @dataProvider provideHasOneComponentHandlesMultipleRelations
*/
public function testHasOneComponentHandlesMultipleRelations(string $class, string $component, bool $expected): void public function testHasOneComponentHandlesMultipleRelations(string $class, string $component, bool $expected): void
{ {
$this->assertSame( $this->assertSame(
@ -451,7 +443,7 @@ class DataObjectSchemaTest extends SapphireTest
); );
} }
public function provideHasOneComponentHandlesMultipleRelations(): array public static function provideHasOneComponentHandlesMultipleRelations(): array
{ {
return [ return [
[ [

View File

@ -27,6 +27,7 @@ use SilverStripe\Security\Member;
use SilverStripe\View\ViewableData; use SilverStripe\View\ViewableData;
use ReflectionMethod; use ReflectionMethod;
use stdClass; use stdClass;
use PHPUnit\Framework\Attributes\DataProvider;
class DataObjectTest extends SapphireTest class DataObjectTest extends SapphireTest
{ {
@ -92,9 +93,7 @@ class DataObjectTest extends SapphireTest
); );
} }
/** #[DataProvider('provideSingletons')]
* @dataProvider provideSingletons
*/
public function testSingleton($inst, $defaultValue, $altDefaultValue) public function testSingleton($inst, $defaultValue, $altDefaultValue)
{ {
$inst = $inst(); $inst = $inst();
@ -113,7 +112,7 @@ class DataObjectTest extends SapphireTest
} }
} }
public function provideSingletons() public static function provideSingletons()
{ {
// because PHPUnit evaluates test providers *before* setUp methods // because PHPUnit evaluates test providers *before* setUp methods
// any extensions added in the setUp methods won't be available // any extensions added in the setUp methods won't be available
@ -2674,7 +2673,7 @@ class DataObjectTest extends SapphireTest
$this->assertSame('SOME VALUE', $obj->MyTestField); $this->assertSame('SOME VALUE', $obj->MyTestField);
} }
public function provideTestGetDatabaseBackedField() public static function provideTestGetDatabaseBackedField()
{ {
return [ return [
['Captain.IsRetired', 'Captain.IsRetired'], ['Captain.IsRetired', 'Captain.IsRetired'],
@ -2704,9 +2703,7 @@ class DataObjectTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideTestGetDatabaseBackedField')]
* @dataProvider provideTestGetDatabaseBackedField
*/
public function testGetDatabaseBackedField(string $fieldPath, $expected) public function testGetDatabaseBackedField(string $fieldPath, $expected)
{ {
$dataObjectClass = new DataObject(); $dataObjectClass = new DataObject();

View File

@ -10,6 +10,11 @@ use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\Queries\SQLSelect; use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\ORM\Tests\DataQueryTest\ObjectE; use SilverStripe\ORM\Tests\DataQueryTest\ObjectE;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use SilverStripe\ORM\Tests\DataQueryTest\DataQueryTestException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\DoesNotPerformAssertions;
use SilverStripe\Dev\Exceptions\ExpectedErrorException;
use SilverStripe\Dev\Exceptions\ExpectedWarningException;
class DataQueryTest extends SapphireTest class DataQueryTest extends SapphireTest
{ {
@ -56,7 +61,7 @@ class DataQueryTest extends SapphireTest
$this->assertEquals('Foo', $result['Title']); $this->assertEquals('Foo', $result['Title']);
} }
public function provideJoins() public static function provideJoins()
{ {
return [ return [
[ [
@ -74,9 +79,7 @@ class DataQueryTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideJoins')]
* @dataProvider provideJoins
*/
public function testJoins($joinMethod, $joinType) public function testJoins($joinMethod, $joinType)
{ {
$dq = new DataQuery(Member::class); $dq = new DataQuery(Member::class);
@ -101,9 +104,7 @@ class DataQueryTest extends SapphireTest
$this->assertStringContainsString('"testctwo_DataQueryTest_C"."ID" = "DataQueryTest_B"."TestCTwoID"', $dq->sql()); $this->assertStringContainsString('"testctwo_DataQueryTest_C"."ID" = "DataQueryTest_B"."TestCTwoID"', $dq->sql());
} }
/** #[DataProvider('provideApplyRelationMultiRelational')]
* @dataProvider provideApplyRelationMultiRelational
*/
public function testApplyRelationMultiRelational(string $relation): void public function testApplyRelationMultiRelational(string $relation): void
{ {
$dq = new DataQuery(DataQueryTest\ObjectHasMultiRelationalHasMany::class); $dq = new DataQuery(DataQueryTest\ObjectHasMultiRelationalHasMany::class);
@ -116,7 +117,7 @@ class DataQueryTest extends SapphireTest
$this->assertStringContainsString($joinAliasWithQuotes . '."MultiRelationalClass" = "DataQueryTest_ObjectHasMultiRelationalHasMany"."ClassName"', $dq->sql()); $this->assertStringContainsString($joinAliasWithQuotes . '."MultiRelationalClass" = "DataQueryTest_ObjectHasMultiRelationalHasMany"."ClassName"', $dq->sql());
} }
public function provideApplyRelationMultiRelational(): array public static function provideApplyRelationMultiRelational(): array
{ {
return [ return [
'relation1' => [ 'relation1' => [
@ -215,7 +216,7 @@ class DataQueryTest extends SapphireTest
$this->assertTrue(true); $this->assertTrue(true);
} }
public function provideFieldCollision() public static function provideFieldCollision()
{ {
return [ return [
'allow collisions' => [true], 'allow collisions' => [true],
@ -223,11 +224,10 @@ class DataQueryTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideFieldCollision')]
* @dataProvider provideFieldCollision
*/
public function testFieldCollision($allowCollisions) public function testFieldCollision($allowCollisions)
{ {
$this->enableErrorHandler();
$dataQuery = new DataQuery(DataQueryTest\ObjectB::class); $dataQuery = new DataQuery(DataQueryTest\ObjectB::class);
$dataQuery->selectField('COALESCE(NULL, 1) AS "Title"'); $dataQuery->selectField('COALESCE(NULL, 1) AS "Title"');
$dataQuery->setAllowCollidingFieldStatements($allowCollisions); $dataQuery->setAllowCollidingFieldStatements($allowCollisions);
@ -235,8 +235,8 @@ class DataQueryTest extends SapphireTest
if ($allowCollisions) { if ($allowCollisions) {
$this->assertSQLContains('THEN "DataQueryTest_B"."Title" WHEN COALESCE(NULL, 1) AS "Title" IS NOT NULL THEN COALESCE(NULL, 1) AS "Title" ELSE NULL END AS "Title"', $dataQuery->sql()); $this->assertSQLContains('THEN "DataQueryTest_B"."Title" WHEN COALESCE(NULL, 1) AS "Title" IS NOT NULL THEN COALESCE(NULL, 1) AS "Title" ELSE NULL END AS "Title"', $dataQuery->sql());
} else { } else {
$this->expectError(); $this->expectException(ExpectedWarningException::class);
$this->expectErrorMessageMatches('/^Bad collision item /'); $this->expectExceptionMessageMatches('/^Bad collision item /');
} }
$dataQuery->getFinalisedQuery(); $dataQuery->getFinalisedQuery();
@ -604,7 +604,7 @@ class DataQueryTest extends SapphireTest
); );
} }
public function provideWith() public static function provideWith()
{ {
return [ return [
// Simple scenarios to test auto-join functionality // Simple scenarios to test auto-join functionality
@ -720,7 +720,7 @@ class DataQueryTest extends SapphireTest
'extraManipulations' => [ 'extraManipulations' => [
'innerJoin' => ['hierarchy', '"SQLSelectTestCteRecursive"."ID" = "hierarchy"."parent_id"'], 'innerJoin' => ['hierarchy', '"SQLSelectTestCteRecursive"."ID" = "hierarchy"."parent_id"'],
], ],
'expected' => [ 'expectedItems' => [
'fixtures' => [ 'fixtures' => [
'grandparent', 'grandparent',
'parent', 'parent',
@ -731,9 +731,7 @@ class DataQueryTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideWith')]
* @dataProvider provideWith
*/
public function testWith( public function testWith(
string $dataClass, string $dataClass,
string $name, string $name,
@ -864,8 +862,8 @@ class DataQueryTest extends SapphireTest
/** /**
* Tests that CTE queries have appropriate JOINs for subclass tables etc. * Tests that CTE queries have appropriate JOINs for subclass tables etc.
* If `$query->query()->` was replaced with `$query->query->` in DataQuery::with(), this test would throw an exception. * If `$query->query()->` was replaced with `$query->query->` in DataQuery::with(), this test would throw an exception.
* @doesNotPerformAssertions
*/ */
#[DoesNotPerformAssertions]
public function testWithUsingDataQueryAppliesRelations() public function testWithUsingDataQueryAppliesRelations()
{ {
if (!DB::get_conn()->supportsCteQueries()) { if (!DB::get_conn()->supportsCteQueries()) {

View File

@ -0,0 +1,10 @@
<?php
namespace SilverStripe\ORM\Tests\DataQueryTest;
use SilverStripe\Dev\TestOnly;
use Exception;
class DataQueryTestException extends Exception implements TestOnly
{
}

View File

@ -31,6 +31,7 @@ use SilverStripe\ORM\ManyManyList;
use SilverStripe\ORM\ManyManyThroughList; use SilverStripe\ORM\ManyManyThroughList;
use SilverStripe\ORM\Tests\DataObjectTest\RelationChildFirst; use SilverStripe\ORM\Tests\DataObjectTest\RelationChildFirst;
use SilverStripe\ORM\Tests\DataObjectTest\RelationChildSecond; use SilverStripe\ORM\Tests\DataObjectTest\RelationChildSecond;
use PHPUnit\Framework\Attributes\DataProvider;
class EagerLoadedListTest extends SapphireTest class EagerLoadedListTest extends SapphireTest
{ {
@ -42,7 +43,7 @@ class EagerLoadedListTest extends SapphireTest
return DataListTest::getExtraDataObjects(); return DataListTest::getExtraDataObjects();
} }
private function getBasicRecordRows(): array private static function getBasicRecordRows(): array
{ {
return [ return [
[ [
@ -109,7 +110,7 @@ class EagerLoadedListTest extends SapphireTest
public function testHasID() public function testHasID()
{ {
$list = new EagerLoadedList(Sortable::class, DataList::class); $list = new EagerLoadedList(Sortable::class, DataList::class);
foreach ($this->getBasicRecordRows() as $row) { foreach (EagerLoadedListTest::getBasicRecordRows() as $row) {
$list->addRow($row); $list->addRow($row);
} }
$this->assertTrue($list->hasID(3)); $this->assertTrue($list->hasID(3));
@ -205,9 +206,7 @@ class EagerLoadedListTest extends SapphireTest
$this->assertSame($rows, $list->getRows()); $this->assertSame($rows, $list->getRows());
} }
/** #[DataProvider('provideAddRowBadID')]
* @dataProvider provideAddRowBadID
*/
public function testAddRowBadID(array $row) public function testAddRowBadID(array $row)
{ {
$list = new EagerLoadedList(TeamComment::class, DataList::class); $list = new EagerLoadedList(TeamComment::class, DataList::class);
@ -216,7 +215,7 @@ class EagerLoadedListTest extends SapphireTest
$list->addRow($row); $list->addRow($row);
} }
public function provideAddRowBadID() public static function provideAddRowBadID()
{ {
return [ return [
[['ID' => null]], [['ID' => null]],
@ -254,9 +253,7 @@ class EagerLoadedListTest extends SapphireTest
$this->assertTrue($list->exists()); $this->assertTrue($list->exists());
} }
/** #[DataProvider('provideIteration')]
* @dataProvider provideIteration
*/
public function testIteration(string $dataListClass): void public function testIteration(string $dataListClass): void
{ {
// Get some garbage values for the manymany component so we don't get errors. // Get some garbage values for the manymany component so we don't get errors.
@ -270,7 +267,7 @@ class EagerLoadedListTest extends SapphireTest
$manyManyComponent['extraFields'] = []; $manyManyComponent['extraFields'] = [];
} }
$rows = $this->getBasicRecordRows(); $rows = EagerLoadedListTest::getBasicRecordRows();
$eagerloadedDataClass = Sortable::class; $eagerloadedDataClass = Sortable::class;
$foreignID = $dataListClass === DataList::class ? null : 9999; $foreignID = $dataListClass === DataList::class ? null : 9999;
@ -286,7 +283,7 @@ class EagerLoadedListTest extends SapphireTest
$this->iterate($list, $rows, array_column($rows, 'ID')); $this->iterate($list, $rows, array_column($rows, 'ID'));
} }
public function provideIteration() public static function provideIteration()
{ {
return [ return [
[DataList::class], [DataList::class],
@ -296,7 +293,7 @@ class EagerLoadedListTest extends SapphireTest
]; ];
} }
private function iterate(EagerLoadedList $list, array $rows, array $expectedIDs): void private function iterate(EagerLoadedList $list, array $rows, array $expected): void
{ {
$foundIDs = []; $foundIDs = [];
foreach ($list as $record) { foreach ($list as $record) {
@ -314,19 +311,17 @@ class EagerLoadedListTest extends SapphireTest
$foundIDs[] = $record->ID; $foundIDs[] = $record->ID;
} }
// Assert all (and only) the expected records were included in the list // Assert all (and only) the expected records were included in the list
$this->assertSame($expectedIDs, $foundIDs); $this->assertSame($expected, $foundIDs);
} }
/** #[DataProvider('provideFilter')]
* @dataProvider provideFilter #[DataProvider('provideFilterWithSearchFilters')]
* @dataProvider provideFilterWithSearchFilters
*/
public function testFilter( public function testFilter(
string $dataListClass, string $dataListClass,
string $eagerloadedDataClass, string $eagerloadedDataClass,
array $rows, array $rows,
array $filter, array $filter,
array $expectedIDs array $expected,
): void { ): void {
// Get some garbage values for the manymany component so we don't get errors. // Get some garbage values for the manymany component so we don't get errors.
// Real relations aren't necessary for this test. // Real relations aren't necessary for this test.
@ -348,41 +343,41 @@ class EagerLoadedListTest extends SapphireTest
// Validate that the unfiltered list still has all records, and the filtered list has the expected amount // Validate that the unfiltered list still has all records, and the filtered list has the expected amount
$this->assertCount(count($rows), $list); $this->assertCount(count($rows), $list);
$this->assertCount(count($expectedIDs), $filteredList); $this->assertCount(count($expected), $filteredList);
// Validate that the filtered list has the CORRECT records // Validate that the filtered list has the CORRECT records
$this->iterate($list, $rows, array_column($rows, 'ID')); $this->iterate($list, $rows, array_column($rows, 'ID'));
} }
public function provideFilter(): array public static function provideFilter(): array
{ {
$rows = $this->getBasicRecordRows(); $rows = EagerLoadedListTest::getBasicRecordRows();
return [ return [
[ [
'dataListClass' => DataList::class, 'dataListClass' => DataList::class,
'eagerloadedDataClass' => ValidatedObject::class, 'eagerloadedDataClass' => ValidatedObject::class,
$rows, 'rows' => $rows,
'filter' => ['Created' => '2023-01-01 00:00:00'], 'filter' => ['Created' => '2023-01-01 00:00:00'],
'expected' => [2, 3], 'expected' => [2, 3],
], ],
[ [
'dataListClass' => HasManyList::class, 'dataListClass' => HasManyList::class,
'eagerloadedDataClass' => ValidatedObject::class, 'eagerloadedDataClass' => ValidatedObject::class,
$rows, 'rows' => $rows,
'filter' => ['Created' => '2023-01-01 00:00:00'], 'filter' => ['Created' => '2023-01-01 00:00:00'],
'expected' => [2, 3], 'expected' => [2, 3],
], ],
[ [
'dataListClass' => ManyManyList::class, 'dataListClass' => ManyManyList::class,
'eagerloadedDataClass' => ValidatedObject::class, 'eagerloadedDataClass' => ValidatedObject::class,
$rows, 'rows' => $rows,
'filter' => ['Created' => '2023-12-01 00:00:00'], 'filter' => ['Created' => '2023-12-01 00:00:00'],
'expected' => [], 'expected' => [],
], ],
[ [
'dataListClass' => ManyManyThroughList::class, 'dataListClass' => ManyManyThroughList::class,
'eagerloadedDataClass' => ValidatedObject::class, 'eagerloadedDataClass' => ValidatedObject::class,
$rows, 'rows' => $rows,
'filter' => [ 'filter' => [
'Created' => '2023-01-01 00:00:00', 'Created' => '2023-01-01 00:00:00',
'Name' => 'test obj 3', 'Name' => 'test obj 3',
@ -392,7 +387,7 @@ class EagerLoadedListTest extends SapphireTest
[ [
'dataListClass' => ManyManyThroughList::class, 'dataListClass' => ManyManyThroughList::class,
'eagerloadedDataClass' => ValidatedObject::class, 'eagerloadedDataClass' => ValidatedObject::class,
$rows, 'rows' => $rows,
'filter' => [ 'filter' => [
'Created' => '2023-01-01 00:00:00', 'Created' => '2023-01-01 00:00:00',
'Name' => 'not there', 'Name' => 'not there',
@ -402,7 +397,7 @@ class EagerLoadedListTest extends SapphireTest
[ [
'dataListClass' => ManyManyThroughList::class, 'dataListClass' => ManyManyThroughList::class,
'eagerloadedDataClass' => ValidatedObject::class, 'eagerloadedDataClass' => ValidatedObject::class,
$rows, 'rows' => $rows,
'filter' => [ 'filter' => [
'Name' => ['test obj 1', 'test obj 3', 'not there'], 'Name' => ['test obj 1', 'test obj 3', 'not there'],
], ],
@ -411,7 +406,7 @@ class EagerLoadedListTest extends SapphireTest
[ [
'dataListClass' => ManyManyThroughList::class, 'dataListClass' => ManyManyThroughList::class,
'eagerloadedDataClass' => ValidatedObject::class, 'eagerloadedDataClass' => ValidatedObject::class,
$rows, 'rows' => $rows,
'filter' => [ 'filter' => [
'Name' => ['not there', 'also not there'], 'Name' => ['not there', 'also not there'],
], ],
@ -420,7 +415,7 @@ class EagerLoadedListTest extends SapphireTest
[ [
'dataListClass' => ManyManyThroughList::class, 'dataListClass' => ManyManyThroughList::class,
'eagerloadedDataClass' => ValidatedObject::class, 'eagerloadedDataClass' => ValidatedObject::class,
$rows, 'rows' => $rows,
'filter' => [ 'filter' => [
'ID' => [1, 2], 'ID' => [1, 2],
], ],
@ -429,9 +424,9 @@ class EagerLoadedListTest extends SapphireTest
]; ];
} }
public function provideFilterWithSearchFilters() public static function provideFilterWithSearchFilters()
{ {
$rows = $this->getBasicRecordRows(); $rows = EagerLoadedListTest::getBasicRecordRows();
$scenarios = [ $scenarios = [
// exact match filter tests // exact match filter tests
'exact match - negate' => [ 'exact match - negate' => [
@ -555,12 +550,10 @@ class EagerLoadedListTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideFilterAnyWithSearchFilters')]
* @dataProvider provideFilterAnyWithSearchFilters public function testFilterAnyWithSearchfilters(array $filter, array $expected): void
*/
public function testFilterAnyWithSearchfilters(array $filter, array $expectedIDs): void
{ {
$rows = $this->getBasicRecordRows(); $rows = EagerLoadedListTest::getBasicRecordRows();
$list = new EagerLoadedList(ValidatedObject::class, DataList::class); $list = new EagerLoadedList(ValidatedObject::class, DataList::class);
foreach ($rows as $row) { foreach ($rows as $row) {
$list->addRow($row); $list->addRow($row);
@ -569,13 +562,13 @@ class EagerLoadedListTest extends SapphireTest
// Validate that the unfiltered list still has all records, and the filtered list has the expected amount // Validate that the unfiltered list still has all records, and the filtered list has the expected amount
$this->assertCount(count($rows), $list); $this->assertCount(count($rows), $list);
$this->assertCount(count($expectedIDs), $filteredList); $this->assertCount(count($expected), $filteredList);
// Validate that the filtered list has the CORRECT records // Validate that the filtered list has the CORRECT records
$this->iterate($list, $rows, array_column($rows, 'ID')); $this->iterate($list, $rows, array_column($rows, 'ID'));
} }
public function provideFilterAnyWithSearchFilters() public static function provideFilterAnyWithSearchFilters()
{ {
return [ return [
// test a couple of search filters // test a couple of search filters
@ -618,12 +611,12 @@ class EagerLoadedListTest extends SapphireTest
]; ];
} }
public function provideExcludeWithSearchfilters() public static function provideExcludeWithSearchfilters()
{ {
// If it's included in the filter test, then it's excluded in the exclude test, // If it's included in the filter test, then it's excluded in the exclude test,
// so we can just use the same scenarios and reverse the expected results. // so we can just use the same scenarios and reverse the expected results.
$rows = $this->getBasicRecordRows(); $rows = EagerLoadedListTest::getBasicRecordRows();
$scenarios = $this->provideFilterWithSearchfilters(); $scenarios = EagerLoadedListTest::provideFilterWithSearchfilters();
foreach ($scenarios as $name => $scenario) { foreach ($scenarios as $name => $scenario) {
$kept = []; $kept = [];
$excluded = []; $excluded = [];
@ -645,12 +638,10 @@ class EagerLoadedListTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideExcludeWithSearchfilters')]
* @dataProvider provideExcludeWithSearchfilters public function testExcludeWithSearchfilters(array $filter, array $expected): void
*/
public function testExcludeWithSearchfilters(array $filter, array $expectedIDs): void
{ {
$rows = $this->getBasicRecordRows(); $rows = EagerLoadedListTest::getBasicRecordRows();
$list = new EagerLoadedList(ValidatedObject::class, DataList::class); $list = new EagerLoadedList(ValidatedObject::class, DataList::class);
foreach ($rows as $row) { foreach ($rows as $row) {
$list->addRow($row); $list->addRow($row);
@ -659,18 +650,18 @@ class EagerLoadedListTest extends SapphireTest
// Validate that the unfiltered list still has all records, and the filtered list has the expected amount // Validate that the unfiltered list still has all records, and the filtered list has the expected amount
$this->assertCount(count($rows), $list); $this->assertCount(count($rows), $list);
$this->assertCount(count($expectedIDs), $filteredList); $this->assertCount(count($expected), $filteredList);
// Validate that the filtered list has the CORRECT records // Validate that the filtered list has the CORRECT records
$this->iterate($list, $rows, array_column($rows, 'ID')); $this->iterate($list, $rows, array_column($rows, 'ID'));
} }
public function provideExcludeAnyWithSearchfilters() public static function provideExcludeAnyWithSearchfilters()
{ {
// If it's included in the filterAny test, then it's excluded in the excludeAny test, // If it's included in the filterAny test, then it's excluded in the excludeAny test,
// so we can just use the same scenarios and reverse the expected results. // so we can just use the same scenarios and reverse the expected results.
$rows = $this->getBasicRecordRows(); $rows = EagerLoadedListTest::getBasicRecordRows();
$scenarios = $this->provideFilterAnyWithSearchfilters(); $scenarios = EagerLoadedListTest::provideFilterAnyWithSearchfilters();
foreach ($scenarios as $name => $scenario) { foreach ($scenarios as $name => $scenario) {
$kept = []; $kept = [];
$excluded = []; $excluded = [];
@ -687,12 +678,10 @@ class EagerLoadedListTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideExcludeAnyWithSearchfilters')]
* @dataProvider provideExcludeAnyWithSearchfilters public function testExcludeAnyWithSearchfilters(array $filter, array $expected): void
*/
public function testExcludeAnyWithSearchfilters(array $filter, array $expectedIDs): void
{ {
$rows = $this->getBasicRecordRows(); $rows = EagerLoadedListTest::getBasicRecordRows();
$list = new EagerLoadedList(ValidatedObject::class, DataList::class); $list = new EagerLoadedList(ValidatedObject::class, DataList::class);
foreach ($rows as $row) { foreach ($rows as $row) {
$list->addRow($row); $list->addRow($row);
@ -701,7 +690,7 @@ class EagerLoadedListTest extends SapphireTest
// Validate that the unfiltered list still has all records, and the filtered list has the expected amount // Validate that the unfiltered list still has all records, and the filtered list has the expected amount
$this->assertCount(count($rows), $list); $this->assertCount(count($rows), $list);
$this->assertCount(count($expectedIDs), $filteredList); $this->assertCount(count($expected), $filteredList);
// Validate that the filtered list has the CORRECT records // Validate that the filtered list has the CORRECT records
$this->iterate($list, $rows, array_column($rows, 'ID')); $this->iterate($list, $rows, array_column($rows, 'ID'));
@ -725,9 +714,7 @@ class EagerLoadedListTest extends SapphireTest
$list->filter(['Captain.ShirtNumber' => 'anything']); $list->filter(['Captain.ShirtNumber' => 'anything']);
} }
/** #[DataProvider('provideFilterByWrongNumArgs')]
* @dataProvider provideFilterByWrongNumArgs
*/
public function testFilterByWrongNumArgs(...$args) public function testFilterByWrongNumArgs(...$args)
{ {
$list = new EagerLoadedList(ValidatedObject::class, DataList::class); $list = new EagerLoadedList(ValidatedObject::class, DataList::class);
@ -737,7 +724,7 @@ class EagerLoadedListTest extends SapphireTest
$list->filter(...$args); $list->filter(...$args);
} }
public function provideFilterByWrongNumArgs() public static function provideFilterByWrongNumArgs()
{ {
return [ return [
0 => [], 0 => [],
@ -745,9 +732,7 @@ class EagerLoadedListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideLimitAndOffset')]
* @dataProvider provideLimitAndOffset
*/
public function testLimitAndOffset($length, $offset, $expectedCount, $expectException = false) public function testLimitAndOffset($length, $offset, $expectedCount, $expectException = false)
{ {
$list = $this->getListWithRecords(TeamComment::class); $list = $this->getListWithRecords(TeamComment::class);
@ -768,7 +753,7 @@ class EagerLoadedListTest extends SapphireTest
$this->assertCount($expectedCount, $list->limit($length, $offset)->toArray()); $this->assertCount($expectedCount, $list->limit($length, $offset)->toArray());
} }
public function provideLimitAndOffset(): array public static function provideLimitAndOffset(): array
{ {
return [ return [
'no limit' => [null, 0, 3], 'no limit' => [null, 0, 3],
@ -1127,9 +1112,7 @@ class EagerLoadedListTest extends SapphireTest
$list = $list->sort('Team.Title', 'ASC'); $list = $list->sort('Team.Title', 'ASC');
} }
/** #[DataProvider('provideSortInvalidParameters')]
* @dataProvider provideSortInvalidParameters
*/
public function testSortInvalidParameters(string $sort, string $type): void public function testSortInvalidParameters(string $sort, string $type): void
{ {
if ($type === 'valid') { if ($type === 'valid') {
@ -1162,7 +1145,7 @@ class EagerLoadedListTest extends SapphireTest
/** /**
* @see DataListTest::provideRawSqlSortException() * @see DataListTest::provideRawSqlSortException()
*/ */
public function provideSortInvalidParameters(): array public static function provideSortInvalidParameters(): array
{ {
return [ return [
['Title', 'valid'], ['Title', 'valid'],
@ -1189,9 +1172,7 @@ class EagerLoadedListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideSortDirectionValidationTwoArgs')]
* @dataProvider provideSortDirectionValidationTwoArgs
*/
public function testSortDirectionValidationTwoArgs(string $direction, string $type): void public function testSortDirectionValidationTwoArgs(string $direction, string $type): void
{ {
if ($type === 'valid') { if ($type === 'valid') {
@ -1203,7 +1184,7 @@ class EagerLoadedListTest extends SapphireTest
$this->getListWithRecords(Team::class)->sort('Title', $direction)->column('ID'); $this->getListWithRecords(Team::class)->sort('Title', $direction)->column('ID');
} }
public function provideSortDirectionValidationTwoArgs(): array public static function provideSortDirectionValidationTwoArgs(): array
{ {
return [ return [
['ASC', 'valid'], ['ASC', 'valid'],
@ -1216,9 +1197,8 @@ class EagerLoadedListTest extends SapphireTest
/** /**
* Test passing scalar values to sort() * Test passing scalar values to sort()
*
* @dataProvider provideSortScalarValues
*/ */
#[DataProvider('provideSortScalarValues')]
public function testSortScalarValues(mixed $emtpyValue, string $type): void public function testSortScalarValues(mixed $emtpyValue, string $type): void
{ {
$this->assertSame(['Subteam 1'], $this->getListWithRecords(Team::class)->limit(1)->column('Title')); $this->assertSame(['Subteam 1'], $this->getListWithRecords(Team::class)->limit(1)->column('Title'));
@ -1236,7 +1216,7 @@ class EagerLoadedListTest extends SapphireTest
$this->assertSame(['Subteam 1'], $list->limit(1)->column('Title')); $this->assertSame(['Subteam 1'], $list->limit(1)->column('Title'));
} }
public function provideSortScalarValues(): array public static function provideSortScalarValues(): array
{ {
return [ return [
['', 'empty-scalar'], ['', 'empty-scalar'],
@ -1261,7 +1241,7 @@ class EagerLoadedListTest extends SapphireTest
$this->assertSame($order, $list->column('ID')); $this->assertSame($order, $list->column('ID'));
} }
public function provideSortMatchesDataList() public static function provideSortMatchesDataList()
{ {
// These will be used to make fixtures // These will be used to make fixtures
// We don't use a fixtures yaml file here because we want a full DataList of only // We don't use a fixtures yaml file here because we want a full DataList of only
@ -1300,9 +1280,7 @@ class EagerLoadedListTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideSortMatchesDataList')]
* @dataProvider provideSortMatchesDataList
*/
public function testSortMatchesDataList(string $sortDir, string $field, array $values) public function testSortMatchesDataList(string $sortDir, string $field, array $values)
{ {
// Use explicit per-scenario fixtures // Use explicit per-scenario fixtures
@ -1500,7 +1478,7 @@ class EagerLoadedListTest extends SapphireTest
$list->filterAny(['Players.Count()' => 2]); $list->filterAny(['Players.Count()' => 2]);
} }
public function provideCantFilterByRelation() public static function provideCantFilterByRelation()
{ {
return [ return [
'many_many' => [ 'many_many' => [
@ -1518,9 +1496,7 @@ class EagerLoadedListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideCantFilterByRelation')]
* @dataProvider provideCantFilterByRelation
*/
public function testCantFilterByRelation(string $column) public function testCantFilterByRelation(string $column)
{ {
// Many to many // Many to many
@ -1530,9 +1506,7 @@ class EagerLoadedListTest extends SapphireTest
$list->filter($column, ['Captain', 'Captain 2']); $list->filter($column, ['Captain', 'Captain 2']);
} }
/** #[DataProvider('provideFilterByNull')]
* @dataProvider provideFilterByNull
*/
public function testFilterByNull(string $filterMethod, array $filter, array $expected) public function testFilterByNull(string $filterMethod, array $filter, array $expected)
{ {
// Force DataObjectTest_Fan/fan5::Email to empty string // Force DataObjectTest_Fan/fan5::Email to empty string
@ -1544,7 +1518,7 @@ class EagerLoadedListTest extends SapphireTest
$this->assertListEquals($expected, $filteredList); $this->assertListEquals($expected, $filteredList);
} }
public function provideFilterByNull() public static function provideFilterByNull()
{ {
return [ return [
'Filter by null email' => [ 'Filter by null email' => [
@ -1802,8 +1776,8 @@ class EagerLoadedListTest extends SapphireTest
/** /**
* Test that if an exclude() is applied to a filter(), the filter() is still preserved. * Test that if an exclude() is applied to a filter(), the filter() is still preserved.
* @dataProvider provideExcludeOnFilter
*/ */
#[DataProvider('provideExcludeOnFilter')]
public function testExcludeOnFilter(array $filter, array $exclude, array $expected) public function testExcludeOnFilter(array $filter, array $exclude, array $expected)
{ {
$list = $this->getListWithRecords(TeamComment::class); $list = $this->getListWithRecords(TeamComment::class);
@ -1812,7 +1786,7 @@ class EagerLoadedListTest extends SapphireTest
$this->assertListEquals($expected, $list->sort('Name')); $this->assertListEquals($expected, $list->sort('Name'));
} }
public function provideExcludeOnFilter() public static function provideExcludeOnFilter()
{ {
return [ return [
[ [
@ -2092,10 +2066,8 @@ class EagerLoadedListTest extends SapphireTest
$list->offsetUnset(0); $list->offsetUnset(0);
} }
/** #[DataProvider('provideRelation')]
* @dataProvider provideRelation public function testRelation(string $parentClass, string $relation, ?array $expected, array $eagerLoaded)
*/
public function testRelation(string $parentClass, string $relation, ?array $expected)
{ {
$relationList = $this->getListWithRecords($parentClass)->relation($relation); $relationList = $this->getListWithRecords($parentClass)->relation($relation);
if ($expected === null) { if ($expected === null) {
@ -2106,9 +2078,7 @@ class EagerLoadedListTest extends SapphireTest
} }
} }
/** #[DataProvider('provideRelation')]
* @dataProvider provideRelation
*/
public function testRelationEagerLoaded(string $parentClass, string $relation, ?array $expected, array $eagerLoaded) public function testRelationEagerLoaded(string $parentClass, string $relation, ?array $expected, array $eagerLoaded)
{ {
// Get an EagerLoadedList and add the relation data to it // Get an EagerLoadedList and add the relation data to it
@ -2139,7 +2109,7 @@ class EagerLoadedListTest extends SapphireTest
} }
} }
public function provideRelation() public static function provideRelation()
{ {
return [ return [
'many_many' => [ 'many_many' => [
@ -2150,7 +2120,7 @@ class EagerLoadedListTest extends SapphireTest
['Title' => 'Test 2'], ['Title' => 'Test 2'],
['Title' => 'Test 3'], ['Title' => 'Test 3'],
], ],
'eagerloaded' => [ 'eagerLoaded' => [
'test1' => [ 'test1' => [
['class' => RelationChildSecond::class, 'fixture' => 'test1', 'Title' => 'Test 1'], ['class' => RelationChildSecond::class, 'fixture' => 'test1', 'Title' => 'Test 1'],
['class' => RelationChildSecond::class, 'fixture' => 'test2', 'Title' => 'Test 2'], ['class' => RelationChildSecond::class, 'fixture' => 'test2', 'Title' => 'Test 2'],
@ -2167,7 +2137,7 @@ class EagerLoadedListTest extends SapphireTest
'expected' => [ 'expected' => [
['Title' => 'Subteam 1'], ['Title' => 'Subteam 1'],
], ],
'eagerloaded' => [ 'eagerLoaded' => [
'team1' => [ 'team1' => [
['class' => SubTeam::class, 'fixture' => 'subteam1', 'Title' => 'Subteam 1'], ['class' => SubTeam::class, 'fixture' => 'subteam1', 'Title' => 'Subteam 1'],
], ],
@ -2178,7 +2148,7 @@ class EagerLoadedListTest extends SapphireTest
'parentClass' => DataObjectTest\Company::class, 'parentClass' => DataObjectTest\Company::class,
'relation' => 'Owner', 'relation' => 'Owner',
'expected' => null, 'expected' => null,
'eagerloaded' => [ 'eagerLoaded' => [
'company1' => [ 'company1' => [
'class' => Player::class, 'fixture' => 'player1', 'Title' => 'Player 1', 'class' => Player::class, 'fixture' => 'player1', 'Title' => 'Player 1',
], ],
@ -2190,9 +2160,7 @@ class EagerLoadedListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideCreateDataObject')]
* @dataProvider provideCreateDataObject
*/
public function testCreateDataObject(string $dataClass, string $realClass, array $row) public function testCreateDataObject(string $dataClass, string $realClass, array $row)
{ {
$list = new EagerLoadedList($dataClass, DataList::class); $list = new EagerLoadedList($dataClass, DataList::class);
@ -2214,7 +2182,7 @@ class EagerLoadedListTest extends SapphireTest
} }
} }
public function provideCreateDataObject() public static function provideCreateDataObject()
{ {
return [ return [
'no ClassName' => [ 'no ClassName' => [
@ -2314,9 +2282,7 @@ class EagerLoadedListTest extends SapphireTest
$list->getExtraData('Teams', 'abc'); $list->getExtraData('Teams', 'abc');
} }
/** #[DataProvider('provideGetExtraDataBadListType')]
* @dataProvider provideGetExtraDataBadListType
*/
public function testGetExtraDataBadListType(string $listClass) public function testGetExtraDataBadListType(string $listClass)
{ {
$list = new EagerLoadedList(Player::class, $listClass, 99999); $list = new EagerLoadedList(Player::class, $listClass, 99999);
@ -2325,7 +2291,7 @@ class EagerLoadedListTest extends SapphireTest
$list->getExtraData('Teams', 1); $list->getExtraData('Teams', 1);
} }
public function provideGetExtraDataBadListType() public static function provideGetExtraDataBadListType()
{ {
return [ return [
[HasManyList::class], [HasManyList::class],

View File

@ -6,155 +6,156 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Filters\EndsWithFilter; use SilverStripe\ORM\Filters\EndsWithFilter;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\ORM\Filters\SearchFilter; use SilverStripe\ORM\Filters\SearchFilter;
use PHPUnit\Framework\Attributes\DataProvider;
class EndsWithFilterTest extends SapphireTest class EndsWithFilterTest extends SapphireTest
{ {
public function provideMatches() public static function provideMatches()
{ {
$scenarios = [ $scenarios = [
// without modifiers // without modifiers
'null ends with null' => [ 'null ends with null' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty ends with null' => [ 'empty ends with null' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'null ends with empty' => [ 'null ends with empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty ends with empty' => [ 'empty ends with empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty ends with false' => [ 'empty ends with false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'true doesnt end with empty' => [ 'true doesnt end with empty' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false doesnt end with empty' => [ 'false doesnt end with empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'true doesnt end with empty' => [ 'true doesnt end with empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'null ends with false' => [ 'null ends with false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'false doesnt end with null' => [ 'false doesnt end with null' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false doesnt end with true' => [ 'false doesnt end with true' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'true doesnt end with false' => [ 'true doesnt end with false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false doesnt end with false' => [ 'false doesnt end with false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'true doesnt end with true' => [ 'true doesnt end with true' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'number is cast to string' => [ 'number is cast to string' => [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => '1', 'matchValue' => '1',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'1 ends with 1' => [ '1 ends with 1' => [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => 1, 'matchValue' => 1,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'100 doesnt end with 1' => [ '100 doesnt end with 1' => [
'filterValue' => '1', 'filterValue' => '1',
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'100 ends with 0' => [ '100 ends with 0' => [
'filterValue' => '0', 'filterValue' => '0',
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'100 still ends with 0' => [ '100 still ends with 0' => [
'filterValue' => 0, 'filterValue' => 0,
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'SomeValue ends with SomeValue' => [ 'SomeValue ends with SomeValue' => [
'filterValue' => 'SomeValue', 'filterValue' => 'SomeValue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'SomeValue doesnt end with somevalue' => [ 'SomeValue doesnt end with somevalue' => [
'filterValue' => 'somevalue', 'filterValue' => 'somevalue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
'SomeValue doesnt end with meVal' => [ 'SomeValue doesnt end with meVal' => [
'filterValue' => 'meVal', 'filterValue' => 'meVal',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'SomeValue ends with Value' => [ 'SomeValue ends with Value' => [
'filterValue' => 'Value', 'filterValue' => 'Value',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'SomeValue doesnt with vAlUe' => [ 'SomeValue doesnt with vAlUe' => [
'filterValue' => 'vAlUe', 'filterValue' => 'vAlUe',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
@ -180,19 +181,19 @@ class EndsWithFilterTest extends SapphireTest
// Some multi-value tests // Some multi-value tests
[ [
'filterValue' => [123, 'somevalue', 'abc'], 'filterValue' => [123, 'somevalue', 'abc'],
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
[ [
'filterValue' => [123, 'Value', 'abc'], 'filterValue' => [123, 'Value', 'abc'],
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => [123, 'meVal', 'abc'], 'filterValue' => [123, 'meVal', 'abc'],
'objValue' => 'Some', 'matchValue' => 'Some',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
@ -200,38 +201,38 @@ class EndsWithFilterTest extends SapphireTest
// We're testing this scenario because ArrayList might contain arbitrary values // We're testing this scenario because ArrayList might contain arbitrary values
[ [
'filterValue' => new ArrayData(['SomeField' => 'some value']), 'filterValue' => new ArrayData(['SomeField' => 'some value']),
'objValue' => new ArrayData(['SomeField' => 'some value']), 'matchValue' => new ArrayData(['SomeField' => 'some value']),
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => new ArrayData(['SomeField' => 'SoMe VaLuE']), 'filterValue' => new ArrayData(['SomeField' => 'SoMe VaLuE']),
'objValue' => new ArrayData(['SomeField' => 'some value']), 'matchValue' => new ArrayData(['SomeField' => 'some value']),
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
// case insensitive // case insensitive
[ [
'filterValue' => 'somevalue', 'filterValue' => 'somevalue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'vAlUe', 'filterValue' => 'vAlUe',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'meval', 'filterValue' => 'meval',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => 'different', 'filterValue' => 'different',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => false, 'matches' => false,
], ],
@ -252,9 +253,7 @@ class EndsWithFilterTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideMatches')]
* @dataProvider provideMatches
*/
public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, ?bool $matches) public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, ?bool $matches)
{ {
// Test with explicit default case sensitivity rather than relying on the collation, so that database // Test with explicit default case sensitivity rather than relying on the collation, so that database

View File

@ -10,6 +10,7 @@ use SilverStripe\ORM\Tests\Filters\ExactMatchFilterTest\Project;
use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataList;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\ORM\Filters\SearchFilter; use SilverStripe\ORM\Filters\SearchFilter;
use PHPUnit\Framework\Attributes\DataProvider;
class ExactMatchFilterTest extends SapphireTest class ExactMatchFilterTest extends SapphireTest
{ {
@ -20,9 +21,7 @@ class ExactMatchFilterTest extends SapphireTest
Project::class, Project::class,
]; ];
/** #[DataProvider('provideUsePlaceholders')]
* @dataProvider provideUsePlaceholders
*/
public function testUsePlaceholders(?bool $expectedID, ?bool $expectedTitle, bool $config, callable $fn): void public function testUsePlaceholders(?bool $expectedID, ?bool $expectedTitle, bool $config, callable $fn): void
{ {
Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config); Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config);
@ -31,7 +30,7 @@ class ExactMatchFilterTest extends SapphireTest
$this->assertSame($expectedTitle, $titleQueryUsesPlaceholders); $this->assertSame($expectedTitle, $titleQueryUsesPlaceholders);
} }
public function provideUsePlaceholders(): array public static function provideUsePlaceholders(): array
{ {
$ids = [1, 2, 3]; $ids = [1, 2, 3];
$taskTitles = array_map(fn($i) => "Task $i", $ids); $taskTitles = array_map(fn($i) => "Task $i", $ids);
@ -96,115 +95,115 @@ class ExactMatchFilterTest extends SapphireTest
return [$idQueryUsesPlaceholders, $titleQueryUsesPlaceholders]; return [$idQueryUsesPlaceholders, $titleQueryUsesPlaceholders];
} }
public function provideMatches() public static function provideMatches()
{ {
$scenarios = [ $scenarios = [
// without modifiers // without modifiers
[ [
'filterValue' => null, 'filterValue' => null,
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => null, 'filterValue' => null,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => '', 'filterValue' => '',
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => '', 'filterValue' => '',
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => false, 'filterValue' => false,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => true, 'filterValue' => true,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => '', 'filterValue' => '',
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => '', 'filterValue' => '',
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => false, 'filterValue' => false,
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => null, 'filterValue' => null,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => true, 'filterValue' => true,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => false, 'filterValue' => false,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => true, 'filterValue' => true,
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'SomeValue', 'filterValue' => 'SomeValue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'somevalue', 'filterValue' => 'somevalue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
[ [
'filterValue' => 'SomeValue', 'filterValue' => 'SomeValue',
'objValue' => 'Some', 'matchValue' => 'Some',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => '1', 'matchValue' => '1',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => 1, 'matchValue' => 1,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
@ -230,25 +229,25 @@ class ExactMatchFilterTest extends SapphireTest
// Some multi-value tests // Some multi-value tests
[ [
'filterValue' => [123, 'somevalue', 'abc'], 'filterValue' => [123, 'somevalue', 'abc'],
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
[ [
'filterValue' => [123, 'SomeValue', 'abc'], 'filterValue' => [123, 'SomeValue', 'abc'],
'objValue' => 'Some', 'matchValue' => 'Some',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => [1, 2, 3], 'filterValue' => [1, 2, 3],
'objValue' => '1', 'matchValue' => '1',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => [4, 5, 6], 'filterValue' => [4, 5, 6],
'objValue' => 1, 'matchValue' => 1,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
@ -257,27 +256,27 @@ class ExactMatchFilterTest extends SapphireTest
// anything as its value // anything as its value
[ [
'filterValue' => new ArrayData(['SomeField' => 'some value']), 'filterValue' => new ArrayData(['SomeField' => 'some value']),
'objValue' => new ArrayData(['SomeField' => 'some value']), 'matchValue' => new ArrayData(['SomeField' => 'some value']),
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => new ArrayData(['SomeField' => 'SoMe VaLuE']), 'filterValue' => new ArrayData(['SomeField' => 'SoMe VaLuE']),
'objValue' => new ArrayData(['SomeField' => 'some value']), 'matchValue' => new ArrayData(['SomeField' => 'some value']),
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
// case insensitive // case insensitive
[ [
'filterValue' => 'somevalue', 'filterValue' => 'somevalue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => true, 'matches' => true,
], ],
// doesn't do partial matching even when case insensitive // doesn't do partial matching even when case insensitive
[ [
'filterValue' => 'some', 'filterValue' => 'some',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => false, 'matches' => false,
], ],
@ -298,10 +297,8 @@ class ExactMatchFilterTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideMatches')]
* @dataProvider provideMatches public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, ?bool $matches)
*/
public function testMatches(mixed $filterValue, mixed $objValue, array $modifiers, ?bool $matches)
{ {
// Test with explicit default case sensitivity rather than relying on the collation, so that database // Test with explicit default case sensitivity rather than relying on the collation, so that database
// settings don't interfere with the test // settings don't interfere with the test
@ -318,7 +315,7 @@ class ExactMatchFilterTest extends SapphireTest
$filter = new ExactMatchFilter(); $filter = new ExactMatchFilter();
$filter->setValue($filterValue); $filter->setValue($filterValue);
$filter->setModifiers($modifiers); $filter->setModifiers($modifiers);
$this->assertSame($matches ?? $nullMatch, $filter->matches($objValue)); $this->assertSame($matches ?? $nullMatch, $filter->matches($matchValue));
} }
} }
} }

View File

@ -5,11 +5,12 @@ namespace SilverStripe\ORM\Tests\Filters;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Filters\GreaterThanFilter; use SilverStripe\ORM\Filters\GreaterThanFilter;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use PHPUnit\Framework\Attributes\DataProvider;
class GreaterThanFilterTest extends SapphireTest class GreaterThanFilterTest extends SapphireTest
{ {
public function provideMatches() public static function provideMatches()
{ {
$scenarios = [ $scenarios = [
// without modifiers // without modifiers
@ -212,9 +213,7 @@ class GreaterThanFilterTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideMatches')]
* @dataProvider provideMatches
*/
public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, bool $matches) public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, bool $matches)
{ {
$filter = new GreaterThanFilter(); $filter = new GreaterThanFilter();

View File

@ -5,11 +5,12 @@ namespace SilverStripe\ORM\Tests\Filters;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Filters\GreaterThanOrEqualFilter; use SilverStripe\ORM\Filters\GreaterThanOrEqualFilter;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use PHPUnit\Framework\Attributes\DataProvider;
class GreaterThanOrEqualFilterTest extends SapphireTest class GreaterThanOrEqualFilterTest extends SapphireTest
{ {
public function provideMatches() public static function provideMatches()
{ {
$scenarios = [ $scenarios = [
// without modifiers // without modifiers
@ -212,9 +213,7 @@ class GreaterThanOrEqualFilterTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideMatches')]
* @dataProvider provideMatches
*/
public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, bool $matches) public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, bool $matches)
{ {
$filter = new GreaterThanOrEqualFilter(); $filter = new GreaterThanOrEqualFilter();

View File

@ -5,11 +5,12 @@ namespace SilverStripe\ORM\Tests\Filters;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Filters\LessThanFilter; use SilverStripe\ORM\Filters\LessThanFilter;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use PHPUnit\Framework\Attributes\DataProvider;
class LessThanFilterTest extends SapphireTest class LessThanFilterTest extends SapphireTest
{ {
public function provideMatches() public static function provideMatches()
{ {
$scenarios = [ $scenarios = [
// without modifiers // without modifiers
@ -212,9 +213,7 @@ class LessThanFilterTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideMatches')]
* @dataProvider provideMatches
*/
public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, bool $matches) public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, bool $matches)
{ {
$filter = new LessThanFilter(); $filter = new LessThanFilter();

View File

@ -5,11 +5,12 @@ namespace SilverStripe\ORM\Tests\Filters;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Filters\LessThanOrEqualFilter; use SilverStripe\ORM\Filters\LessThanOrEqualFilter;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use PHPUnit\Framework\Attributes\DataProvider;
class LessThanOrEqualFilterTest extends SapphireTest class LessThanOrEqualFilterTest extends SapphireTest
{ {
public function provideMatches() public static function provideMatches()
{ {
$scenarios = [ $scenarios = [
// without modifiers // without modifiers
@ -212,9 +213,7 @@ class LessThanOrEqualFilterTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideMatches')]
* @dataProvider provideMatches
*/
public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, bool $matches) public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, bool $matches)
{ {
$filter = new LessThanOrEqualFilter(); $filter = new LessThanOrEqualFilter();

View File

@ -6,149 +6,150 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Filters\PartialMatchFilter; use SilverStripe\ORM\Filters\PartialMatchFilter;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\ORM\Filters\SearchFilter; use SilverStripe\ORM\Filters\SearchFilter;
use PHPUnit\Framework\Attributes\DataProvider;
class PartialMatchFilterTest extends SapphireTest class PartialMatchFilterTest extends SapphireTest
{ {
public function provideMatches() public static function provideMatches()
{ {
$scenarios = [ $scenarios = [
// without modifiers // without modifiers
'null partially matches null' => [ 'null partially matches null' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'null partially matches empty' => [ 'null partially matches empty' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty partially matches null' => [ 'empty partially matches null' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty partially matches empty' => [ 'empty partially matches empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'false partially matches empty' => [ 'false partially matches empty' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'true doesnt partially match empty' => [ 'true doesnt partially match empty' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'empty partially matches false' => [ 'empty partially matches false' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty doesnt partially match true' => [ 'empty doesnt partially match true' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false partially matches null' => [ 'false partially matches null' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'null partially matches false' => [ 'null partially matches false' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'true doesnt partially match false' => [ 'true doesnt partially match false' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false doesnt partially match true' => [ 'false doesnt partially match true' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false partially matches false' => [ 'false partially matches false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'true partially matches true' => [ 'true partially matches true' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'number is cast to string' => [ 'number is cast to string' => [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => '1', 'matchValue' => '1',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'numeric match' => [ 'numeric match' => [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => 1, 'matchValue' => 1,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'partial numeric match' => [ 'partial numeric match' => [
'filterValue' => '1', 'filterValue' => '1',
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'partial numeric match2' => [ 'partial numeric match2' => [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'partial numeric match3' => [ 'partial numeric match3' => [
'filterValue' => 0, 'filterValue' => 0,
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'case sensitive match' => [ 'case sensitive match' => [
'filterValue' => 'SomeValue', 'filterValue' => 'SomeValue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'case sensitive mismatch' => [ 'case sensitive mismatch' => [
'filterValue' => 'somevalue', 'filterValue' => 'somevalue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
'case sensitive partial match' => [ 'case sensitive partial match' => [
'filterValue' => 'meVal', 'filterValue' => 'meVal',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'case sensitive partial mismatch' => [ 'case sensitive partial mismatch' => [
'filterValue' => 'meval', 'filterValue' => 'meval',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
@ -174,25 +175,25 @@ class PartialMatchFilterTest extends SapphireTest
// Some multi-value tests // Some multi-value tests
[ [
'filterValue' => [123, 'somevalue', 'abc'], 'filterValue' => [123, 'somevalue', 'abc'],
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
[ [
'filterValue' => [123, 'meVal', 'abc'], 'filterValue' => [123, 'meVal', 'abc'],
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => [123, 'meval', 'abc'], 'filterValue' => [123, 'meval', 'abc'],
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
[ [
'filterValue' => [4, 5, 6], 'filterValue' => [4, 5, 6],
'objValue' => 1, 'matchValue' => 1,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
@ -200,38 +201,38 @@ class PartialMatchFilterTest extends SapphireTest
// We're testing this scenario because ArrayList might contain arbitrary values // We're testing this scenario because ArrayList might contain arbitrary values
[ [
'filterValue' => new ArrayData(['SomeField' => 'some value']), 'filterValue' => new ArrayData(['SomeField' => 'some value']),
'objValue' => new ArrayData(['SomeField' => 'some value']), 'matchValue' => new ArrayData(['SomeField' => 'some value']),
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => new ArrayData(['SomeField' => 'SoMe VaLuE']), 'filterValue' => new ArrayData(['SomeField' => 'SoMe VaLuE']),
'objValue' => new ArrayData(['SomeField' => 'some value']), 'matchValue' => new ArrayData(['SomeField' => 'some value']),
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
// case insensitive // case insensitive
[ [
'filterValue' => 'somevalue', 'filterValue' => 'somevalue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'some', 'filterValue' => 'some',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'meval', 'filterValue' => 'meval',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'different', 'filterValue' => 'different',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => false, 'matches' => false,
], ],
@ -252,10 +253,8 @@ class PartialMatchFilterTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideMatches')]
* @dataProvider provideMatches public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, ?bool $matches)
*/
public function testMatches(mixed $filterValue, mixed $objValue, array $modifiers, ?bool $matches)
{ {
// Test with explicit default case sensitivity rather than relying on the collation, so that database // Test with explicit default case sensitivity rather than relying on the collation, so that database
// settings don't interfere with the test // settings don't interfere with the test
@ -272,7 +271,7 @@ class PartialMatchFilterTest extends SapphireTest
$filter = new PartialMatchFilter(); $filter = new PartialMatchFilter();
$filter->setValue($filterValue); $filter->setValue($filterValue);
$filter->setModifiers($modifiers); $filter->setModifiers($modifiers);
$this->assertSame($matches ?? $nullMatch, $filter->matches($objValue)); $this->assertSame($matches ?? $nullMatch, $filter->matches($matchValue));
} }
} }
} }

View File

@ -6,155 +6,156 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Filters\StartsWithFilter; use SilverStripe\ORM\Filters\StartsWithFilter;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\ORM\Filters\SearchFilter; use SilverStripe\ORM\Filters\SearchFilter;
use PHPUnit\Framework\Attributes\DataProvider;
class StartsWithFilterTest extends SapphireTest class StartsWithFilterTest extends SapphireTest
{ {
public function provideMatches() public static function provideMatches()
{ {
$scenarios = [ $scenarios = [
// without modifiers // without modifiers
'null starts with null' => [ 'null starts with null' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty starts with null' => [ 'empty starts with null' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'null starts with empty' => [ 'null starts with empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty starts with empty' => [ 'empty starts with empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'empty starts with false' => [ 'empty starts with false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'true doesnt start with empty' => [ 'true doesnt start with empty' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => '', 'matchValue' => '',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false doesnt start with empty' => [ 'false doesnt start with empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'true doesnt start with empty' => [ 'true doesnt start with empty' => [
'filterValue' => '', 'filterValue' => '',
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'null starts with false' => [ 'null starts with false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => null, 'matchValue' => null,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'false doesnt start with null' => [ 'false doesnt start with null' => [
'filterValue' => null, 'filterValue' => null,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false doesnt start with true' => [ 'false doesnt start with true' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'true doesnt start with false' => [ 'true doesnt start with false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'false doesnt start with false' => [ 'false doesnt start with false' => [
'filterValue' => false, 'filterValue' => false,
'objValue' => false, 'matchValue' => false,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'true doesnt start with true' => [ 'true doesnt start with true' => [
'filterValue' => true, 'filterValue' => true,
'objValue' => true, 'matchValue' => true,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'number is cast to string' => [ 'number is cast to string' => [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => '1', 'matchValue' => '1',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'1 starts with 1' => [ '1 starts with 1' => [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => 1, 'matchValue' => 1,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'100 starts with 1' => [ '100 starts with 1' => [
'filterValue' => '1', 'filterValue' => '1',
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'100 still starts with 1' => [ '100 still starts with 1' => [
'filterValue' => 1, 'filterValue' => 1,
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'100 doesnt start with 0' => [ '100 doesnt start with 0' => [
'filterValue' => 0, 'filterValue' => 0,
'objValue' => 100, 'matchValue' => 100,
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'SomeValue starts with SomeValue' => [ 'SomeValue starts with SomeValue' => [
'filterValue' => 'SomeValue', 'filterValue' => 'SomeValue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'SomeValue doesnt start with somevalue' => [ 'SomeValue doesnt start with somevalue' => [
'filterValue' => 'somevalue', 'filterValue' => 'somevalue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
'SomeValue doesnt start with meVal' => [ 'SomeValue doesnt start with meVal' => [
'filterValue' => 'meVal', 'filterValue' => 'meVal',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
'SomeValue starts with Some' => [ 'SomeValue starts with Some' => [
'filterValue' => 'Some', 'filterValue' => 'Some',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
'SomeValue doesnt start with with sOmE' => [ 'SomeValue doesnt start with with sOmE' => [
'filterValue' => 'sOmE', 'filterValue' => 'sOmE',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
@ -180,19 +181,19 @@ class StartsWithFilterTest extends SapphireTest
// Some multi-value tests // Some multi-value tests
[ [
'filterValue' => [123, 'somevalue', 'abc'], 'filterValue' => [123, 'somevalue', 'abc'],
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => null, 'matches' => null,
], ],
[ [
'filterValue' => [123, 'Some', 'abc'], 'filterValue' => [123, 'Some', 'abc'],
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => [123, 'meVal', 'abc'], 'filterValue' => [123, 'meVal', 'abc'],
'objValue' => 'Some', 'matchValue' => 'Some',
'modifiers' => [], 'modifiers' => [],
'matches' => false, 'matches' => false,
], ],
@ -200,38 +201,38 @@ class StartsWithFilterTest extends SapphireTest
// We're testing this scenario because ArrayList might contain arbitrary values // We're testing this scenario because ArrayList might contain arbitrary values
[ [
'filterValue' => new ArrayData(['SomeField' => 'some value']), 'filterValue' => new ArrayData(['SomeField' => 'some value']),
'objValue' => new ArrayData(['SomeField' => 'some value']), 'matchValue' => new ArrayData(['SomeField' => 'some value']),
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => new ArrayData(['SomeField' => 'SoMe VaLuE']), 'filterValue' => new ArrayData(['SomeField' => 'SoMe VaLuE']),
'objValue' => new ArrayData(['SomeField' => 'some value']), 'matchValue' => new ArrayData(['SomeField' => 'some value']),
'modifiers' => [], 'modifiers' => [],
'matches' => true, 'matches' => true,
], ],
// case insensitive // case insensitive
[ [
'filterValue' => 'somevalue', 'filterValue' => 'somevalue',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'sOmE', 'filterValue' => 'sOmE',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => true, 'matches' => true,
], ],
[ [
'filterValue' => 'meval', 'filterValue' => 'meval',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => false, 'matches' => false,
], ],
[ [
'filterValue' => 'different', 'filterValue' => 'different',
'objValue' => 'SomeValue', 'matchValue' => 'SomeValue',
'modifiers' => ['nocase'], 'modifiers' => ['nocase'],
'matches' => false, 'matches' => false,
], ],
@ -252,9 +253,7 @@ class StartsWithFilterTest extends SapphireTest
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideMatches')]
* @dataProvider provideMatches
*/
public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, ?bool $matches) public function testMatches(mixed $filterValue, mixed $matchValue, array $modifiers, ?bool $matches)
{ {
// Test with explicit default case sensitivity rather than relying on the collation, so that database // Test with explicit default case sensitivity rather than relying on the collation, so that database

View File

@ -10,6 +10,7 @@ use SilverStripe\ORM\Tests\HasManyListTest\CompanyCar;
use SilverStripe\ORM\Tests\HasManyListTest\Employee; use SilverStripe\ORM\Tests\HasManyListTest\Employee;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataList;
use PHPUnit\Framework\Attributes\DataProvider;
class HasManyListTest extends SapphireTest class HasManyListTest extends SapphireTest
{ {
@ -192,9 +193,7 @@ class HasManyListTest extends SapphireTest
$this->assertEquals([$remove->ID], $removedIds); $this->assertEquals([$remove->ID], $removedIds);
} }
/** #[DataProvider('provideForForeignIDPlaceholders')]
* @dataProvider provideForForeignIDPlaceholders
*/
public function testForForeignIDPlaceholders(bool $config, bool $useInt, bool $expected): void public function testForForeignIDPlaceholders(bool $config, bool $useInt, bool $expected): void
{ {
Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config); Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config);
@ -214,7 +213,7 @@ class HasManyListTest extends SapphireTest
$this->assertSame($expectedIDs, $newCommentsList->column('ID')); $this->assertSame($expectedIDs, $newCommentsList->column('ID'));
} }
public function provideForForeignIDPlaceholders(): array public static function provideForForeignIDPlaceholders(): array
{ {
return [ return [
'config false' => [ 'config false' => [

View File

@ -11,11 +11,12 @@ use SilverStripe\ORM\Tests\HierarchyTest\HideTestObject;
use SilverStripe\ORM\Tests\HierarchyTest\HideTestSubObject; use SilverStripe\ORM\Tests\HierarchyTest\HideTestSubObject;
use SilverStripe\ORM\Tests\HierarchyTest\HierarchyOnSubclassTestObject; use SilverStripe\ORM\Tests\HierarchyTest\HierarchyOnSubclassTestObject;
use SilverStripe\ORM\Tests\HierarchyTest\HierarchyOnSubclassTestSubObject; use SilverStripe\ORM\Tests\HierarchyTest\HierarchyOnSubclassTestSubObject;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* @internal Only test the right values are returned, not that the cache is actually used. * @internal Only test the right values are returned, not that the cache is actually used.
*/ */
class HierachyCacheTest extends SapphireTest class HierarchyCachingTest extends SapphireTest
{ {
protected static $fixture_file = 'HierarchyTest.yml'; protected static $fixture_file = 'HierarchyTest.yml';
@ -43,7 +44,7 @@ class HierachyCacheTest extends SapphireTest
); );
} }
public function cacheNumChildrenDataProvider() public static function cacheNumChildrenDataProvider()
{ {
return [ return [
[TestObject::class, 'obj1', false, 0, 'childless object should have a numChildren of 0'], [TestObject::class, 'obj1', false, 0, 'childless object should have a numChildren of 0'],
@ -60,9 +61,7 @@ class HierachyCacheTest extends SapphireTest
} }
/** #[DataProvider('cacheNumChildrenDataProvider')]
* @dataProvider cacheNumChildrenDataProvider
*/
public function testNumChildrenCache($className, $identifier, $cache, $expected, $message) public function testNumChildrenCache($className, $identifier, $cache, $expected, $message)
{ {
$node = $this->objFromFixture($className, $identifier); $node = $this->objFromFixture($className, $identifier);
@ -78,7 +77,7 @@ class HierachyCacheTest extends SapphireTest
} }
} }
public function prepopulateCacheNumChildrenDataProvider() public static function prepopulateCacheNumChildrenDataProvider()
{ {
return [ return [
[ [
@ -132,9 +131,7 @@ class HierachyCacheTest extends SapphireTest
]; ];
} }
/** #[DataProvider('prepopulateCacheNumChildrenDataProvider')]
* @dataProvider prepopulateCacheNumChildrenDataProvider
*/
public function testPrepopulatedNumChildrenCache( public function testPrepopulatedNumChildrenCache(
$className, $className,
$idList, $idList,

View File

@ -9,6 +9,7 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\ListDecorator; use SilverStripe\ORM\ListDecorator;
use SilverStripe\ORM\SS_List; use SilverStripe\ORM\SS_List;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* This test class is testing that ListDecorator correctly proxies its calls through to the underlying SS_List * This test class is testing that ListDecorator correctly proxies its calls through to the underlying SS_List
@ -30,7 +31,9 @@ class ListDecoratorTest extends SapphireTest
parent::setUp(); parent::setUp();
$this->list = $this->createMock(ArrayList::class); $this->list = $this->createMock(ArrayList::class);
$this->decorator = $this->getMockForAbstractClass(ListDecorator::class, [$this->list]); // ListDecorator is an abstract class so cannot be instantiated, though has no abstract methods
$this->decorator = new class ($this->list) extends ListDecorator {
};
} }
public function testGetIterator() public function testGetIterator()
@ -54,8 +57,8 @@ class ListDecoratorTest extends SapphireTest
/** /**
* @param array $input * @param array $input
* @dataProvider filterProvider
*/ */
#[DataProvider('filterProvider')]
public function testExclude($input) public function testExclude($input)
{ {
$this->list->expects($this->once())->method('exclude')->with($input)->willReturn('mock'); $this->list->expects($this->once())->method('exclude')->with($input)->willReturn('mock');
@ -64,8 +67,8 @@ class ListDecoratorTest extends SapphireTest
/** /**
* @param array $input * @param array $input
* @dataProvider filterProvider
*/ */
#[DataProvider('filterProvider')]
public function testFilter($input) public function testFilter($input)
{ {
$this->list->expects($this->once())->method('filter')->with($input)->willReturn('mock'); $this->list->expects($this->once())->method('filter')->with($input)->willReturn('mock');
@ -74,8 +77,8 @@ class ListDecoratorTest extends SapphireTest
/** /**
* @param array $input * @param array $input
* @dataProvider filterProvider
*/ */
#[DataProvider('filterProvider')]
public function testFilterAny($input) public function testFilterAny($input)
{ {
$this->list->expects($this->once())->method('filterAny')->with($input)->willReturn('mock'); $this->list->expects($this->once())->method('filterAny')->with($input)->willReturn('mock');
@ -84,8 +87,8 @@ class ListDecoratorTest extends SapphireTest
/** /**
* @param array $input * @param array $input
* @dataProvider filterProvider
*/ */
#[DataProvider('filterProvider')]
public function testSort($input) public function testSort($input)
{ {
$this->list->expects($this->once())->method('sort')->with($input)->willReturn('mock'); $this->list->expects($this->once())->method('sort')->with($input)->willReturn('mock');
@ -95,7 +98,7 @@ class ListDecoratorTest extends SapphireTest
/** /**
* @return array[] * @return array[]
*/ */
public function filterProvider() public static function filterProvider()
{ {
return [ return [
['Name', 'Bob'], ['Name', 'Bob'],

View File

@ -14,6 +14,7 @@ use SilverStripe\ORM\Tests\DataObjectTest\Team;
use SilverStripe\ORM\Tests\ManyManyListTest\ExtraFieldsObject; use SilverStripe\ORM\Tests\ManyManyListTest\ExtraFieldsObject;
use SilverStripe\ORM\Tests\ManyManyListTest\Product; use SilverStripe\ORM\Tests\ManyManyListTest\Product;
use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataList;
use PHPUnit\Framework\Attributes\DataProvider;
class ManyManyListTest extends SapphireTest class ManyManyListTest extends SapphireTest
{ {
@ -617,9 +618,7 @@ class ManyManyListTest extends SapphireTest
$this->assertEquals(sort($remove), sort($removedIds)); $this->assertEquals(sort($remove), sort($removedIds));
} }
/** #[DataProvider('provideForForeignIDPlaceholders')]
* @dataProvider provideForForeignIDPlaceholders
*/
public function testForForeignIDPlaceholders(bool $config, bool $useInt, bool $expected): void public function testForForeignIDPlaceholders(bool $config, bool $useInt, bool $expected): void
{ {
Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config); Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config);
@ -639,7 +638,7 @@ class ManyManyListTest extends SapphireTest
$this->assertEqualsCanonicalizing($expectedIDs, $newPlayersList->column('ID')); $this->assertEqualsCanonicalizing($expectedIDs, $newPlayersList->column('ID'));
} }
public function provideForForeignIDPlaceholders(): array public static function provideForForeignIDPlaceholders(): array
{ {
return [ return [
'config false' => [ 'config false' => [

View File

@ -16,6 +16,7 @@ use SilverStripe\ORM\Tests\ManyManyThroughListTest\Locale;
use SilverStripe\ORM\Tests\ManyManyThroughListTest\FallbackLocale; use SilverStripe\ORM\Tests\ManyManyThroughListTest\FallbackLocale;
use SilverStripe\ORM\Tests\ManyManyThroughListTest\TestObject; use SilverStripe\ORM\Tests\ManyManyThroughListTest\TestObject;
use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataList;
use PHPUnit\Framework\Attributes\DataProvider;
class ManyManyThroughListTest extends SapphireTest class ManyManyThroughListTest extends SapphireTest
{ {
@ -96,8 +97,8 @@ class ManyManyThroughListTest extends SapphireTest
/** /**
* @param string $sort * @param string $sort
* @param array $expected * @param array $expected
* @dataProvider sortingProvider
*/ */
#[DataProvider('sortingProvider')]
public function testSorting($sort, $expected) public function testSorting($sort, $expected)
{ {
/** @var ManyManyThroughListTest\TestObject $parent */ /** @var ManyManyThroughListTest\TestObject $parent */
@ -113,7 +114,7 @@ class ManyManyThroughListTest extends SapphireTest
/** /**
* @return array[] * @return array[]
*/ */
public function sortingProvider() public static function sortingProvider()
{ {
return [ return [
'nothing passed (default)' => [ 'nothing passed (default)' => [
@ -163,7 +164,7 @@ class ManyManyThroughListTest extends SapphireTest
]; ];
} }
public function provideAdd(): array public static function provideAdd(): array
{ {
return [ return [
[ [
@ -181,9 +182,7 @@ class ManyManyThroughListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideAdd')]
* @dataProvider provideAdd
*/
public function testAdd(string $parentClass, string $joinClass, string $joinProperty, string $relation) public function testAdd(string $parentClass, string $joinClass, string $joinProperty, string $relation)
{ {
$parent = $this->objFromFixture($parentClass, 'parent1'); $parent = $this->objFromFixture($parentClass, 'parent1');
@ -207,7 +206,7 @@ class ManyManyThroughListTest extends SapphireTest
$this->assertEquals('new join record', $newItem->$joinProperty->Title); $this->assertEquals('new join record', $newItem->$joinProperty->Title);
} }
public function provideRemove(): array public static function provideRemove(): array
{ {
return [ return [
[ [
@ -221,9 +220,7 @@ class ManyManyThroughListTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideRemove')]
* @dataProvider provideRemove
*/
public function testRemove(string $parentClass, string $relation) public function testRemove(string $parentClass, string $relation)
{ {
$parent = $this->objFromFixture($parentClass, 'parent1'); $parent = $this->objFromFixture($parentClass, 'parent1');
@ -554,9 +551,7 @@ class ManyManyThroughListTest extends SapphireTest
$this->assertEquals(sort($remove), sort($removedIds)); $this->assertEquals(sort($remove), sort($removedIds));
} }
/** #[DataProvider('provideForForeignIDPlaceholders')]
* @dataProvider provideForForeignIDPlaceholders
*/
public function testForForeignIDPlaceholders(bool $config, bool $useInt, bool $expected): void public function testForForeignIDPlaceholders(bool $config, bool $useInt, bool $expected): void
{ {
Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config); Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config);
@ -576,7 +571,7 @@ class ManyManyThroughListTest extends SapphireTest
$this->assertEqualsCanonicalizing($expectedIDs, $newItemsList->column('ID')); $this->assertEqualsCanonicalizing($expectedIDs, $newItemsList->column('ID'));
} }
public function provideForForeignIDPlaceholders(): array public static function provideForForeignIDPlaceholders(): array
{ {
return [ return [
'config false' => [ 'config false' => [

View File

@ -72,9 +72,6 @@ class MarkedSetTest extends SapphireTest
$this->assertEquals(['Obj 2', 'Obj 2a', 'Obj 2b'], $expanded); $this->assertEquals(['Obj 2', 'Obj 2a', 'Obj 2b'], $expanded);
} }
/**
* @covers \SilverStripe\ORM\Hierarchy\MarkedSet::markChildren()
*/
public function testMarkChildrenDoesntUnmarkPreviouslyMarked() public function testMarkChildrenDoesntUnmarkPreviouslyMarked()
{ {
$obj3 = $this->objFromFixture(HierarchyTest\TestObject::class, 'obj3'); $obj3 = $this->objFromFixture(HierarchyTest\TestObject::class, 'obj3');

View File

@ -10,6 +10,7 @@ use SilverStripe\ORM\Queries\SQLUpdate;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Connect\MySQLDatabase; use SilverStripe\ORM\Connect\MySQLDatabase;
use SilverStripe\ORM\Tests\MySQLSchemaManagerTest\MySQLDBDummy; use SilverStripe\ORM\Tests\MySQLSchemaManagerTest\MySQLDBDummy;
use PHPUnit\Framework\Attributes\DataProvider;
class MySQLDatabaseTest extends SapphireTest class MySQLDatabaseTest extends SapphireTest
{ {
@ -113,7 +114,7 @@ class MySQLDatabaseTest extends SapphireTest
$this->assertEquals(1, DB::affected_rows()); $this->assertEquals(1, DB::affected_rows());
} }
public function provideSupportsCte() public static function provideSupportsCte()
{ {
return [ return [
// mysql unsupported // mysql unsupported
@ -204,9 +205,7 @@ class MySQLDatabaseTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideSupportsCte')]
* @dataProvider provideSupportsCte
*/
public function testSupportsCte(string $version, bool $expected, bool $expectedRecursive) public function testSupportsCte(string $version, bool $expected, bool $expectedRecursive)
{ {
$database = new MySQLDBDummy($version); $database = new MySQLDBDummy($version);

View File

@ -9,10 +9,10 @@ use SilverStripe\ORM\Connect\DatabaseException;
use SilverStripe\ORM\DB; use SilverStripe\ORM\DB;
use SilverStripe\ORM\Tests\MySQLiConnectorTest\MySQLiConnector; use SilverStripe\ORM\Tests\MySQLiConnectorTest\MySQLiConnector;
use SilverStripe\Tests\ORM\Utf8\Utf8TestHelper; use SilverStripe\Tests\ORM\Utf8\Utf8TestHelper;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
/** #[RequiresPhpExtension('mysqli')]
* @requires extension mysqli
*/
class MySQLiConnectorTest extends SapphireTest implements TestOnly class MySQLiConnectorTest extends SapphireTest implements TestOnly
{ {
/** @var array project database settings configuration */ /** @var array project database settings configuration */
@ -50,9 +50,7 @@ class MySQLiConnectorTest extends SapphireTest implements TestOnly
$this->config = $config; $this->config = $config;
} }
/** #[DataProvider('charsetProvider')]
* @dataProvider charsetProvider
*/
public function testConnectionCharsetControl($charset, $defaultCollation) public function testConnectionCharsetControl($charset, $defaultCollation)
{ {
$connector = $this->getConnector($charset); $connector = $this->getConnector($charset);
@ -69,9 +67,7 @@ class MySQLiConnectorTest extends SapphireTest implements TestOnly
unset($cset, $connection, $connector, $config); unset($cset, $connection, $connector, $config);
} }
/** #[DataProvider('charsetProvider')]
* @dataProvider charsetProvider
*/
public function testConnectionCollationControl($charset, $defaultCollation, $customCollation) public function testConnectionCollationControl($charset, $defaultCollation, $customCollation)
{ {
$connector = $this->getConnector($charset, $customCollation); $connector = $this->getConnector($charset, $customCollation);
@ -107,7 +103,7 @@ class MySQLiConnectorTest extends SapphireTest implements TestOnly
unset($cset, $connection, $connector, $config); unset($cset, $connection, $connector, $config);
} }
public function charsetProvider() public static function charsetProvider()
{ {
return [ return [
['ascii', 'ascii_general_ci', 'ascii_bin'], ['ascii', 'ascii_general_ci', 'ascii_bin'],

View File

@ -63,10 +63,10 @@ class PaginatedListTest extends SapphireTest
$query = $this->getMockBuilder(SQLSelect::class)->getMock(); $query = $this->getMockBuilder(SQLSelect::class)->getMock();
$query->expects($this->once()) $query->expects($this->once())
->method('getLimit') ->method('getLimit')
->will($this->returnValue(['limit' => 15, 'start' => 30])); ->willReturn(['limit' => 15, 'start' => 30]);
$query->expects($this->once()) $query->expects($this->once())
->method('unlimitedRowCount') ->method('unlimitedRowCount')
->will($this->returnValue(100)); ->willReturn(100);
$list = new PaginatedList(new ArrayList()); $list = new PaginatedList(new ArrayList());
$list->setPaginationFromQuery($query); $list->setPaginationFromQuery($query);

View File

@ -14,6 +14,7 @@ use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\Connect\DatabaseException; use SilverStripe\ORM\Connect\DatabaseException;
use SilverStripe\ORM\Tests\SQLSelectTest\CteDatesObject; use SilverStripe\ORM\Tests\SQLSelectTest\CteDatesObject;
use SilverStripe\ORM\Tests\SQLSelectTest\CteRecursiveObject; use SilverStripe\ORM\Tests\SQLSelectTest\CteRecursiveObject;
use PHPUnit\Framework\Attributes\DataProvider;
class SQLSelectTest extends SapphireTest class SQLSelectTest extends SapphireTest
{ {
@ -74,7 +75,7 @@ class SQLSelectTest extends SapphireTest
} }
} }
public function provideIsEmpty() public static function provideIsEmpty()
{ {
return [ return [
[ [
@ -104,9 +105,7 @@ class SQLSelectTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideIsEmpty')]
* @dataProvider provideIsEmpty
*/
public function testIsEmpty(SQLSelect $query, $expected) public function testIsEmpty(SQLSelect $query, $expected)
{ {
$this->assertSame($expected, $query->isEmpty()); $this->assertSame($expected, $query->isEmpty());
@ -118,7 +117,7 @@ class SQLSelectTest extends SapphireTest
$this->assertSQLEquals('', $query->sql($parameters)); $this->assertSQLEquals('', $query->sql($parameters));
} }
public function provideSelectFrom() public static function provideSelectFrom()
{ {
return [ return [
[ [
@ -140,9 +139,7 @@ class SQLSelectTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideSelectFrom')]
* @dataProvider provideSelectFrom
*/
public function testSelectFrom(array $from, string $expected) public function testSelectFrom(array $from, string $expected)
{ {
$query = new SQLSelect(); $query = new SQLSelect();
@ -818,7 +815,7 @@ class SQLSelectTest extends SapphireTest
$this->assertEquals(10, $limit['start']); $this->assertEquals(10, $limit['start']);
} }
public function provideParameterisedJoinSQL() public static function provideParameterisedJoinSQL()
{ {
return [ return [
[ [
@ -836,9 +833,7 @@ class SQLSelectTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideParameterisedJoinSQL')]
* @dataProvider provideParameterisedJoinSQL
*/
public function testParameterisedJoinSQL($joinMethod, $joinType) public function testParameterisedJoinSQL($joinMethod, $joinType)
{ {
$query = new SQLSelect(); $query = new SQLSelect();
@ -865,7 +860,7 @@ class SQLSelectTest extends SapphireTest
$query->execute(); $query->execute();
} }
public function provideUnion() public static function provideUnion()
{ {
return [ return [
// Note that a default (null) UNION is identical to a DISTINCT UNION // Note that a default (null) UNION is identical to a DISTINCT UNION
@ -899,9 +894,7 @@ class SQLSelectTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideUnion')]
* @dataProvider provideUnion
*/
public function testUnion(SQLSelect $unionQuery, ?string $type, string|array $expected) public function testUnion(SQLSelect $unionQuery, ?string $type, string|array $expected)
{ {
if (is_string($expected)) { if (is_string($expected)) {
@ -954,7 +947,7 @@ class SQLSelectTest extends SapphireTest
); );
} }
public function provideWith() public static function provideWith()
{ {
// Each of these examples shows it working with aliased implicit columns, and with explicit CTE columns. // Each of these examples shows it working with aliased implicit columns, and with explicit CTE columns.
// Most of these examples are derived from https://dev.mysql.com/doc/refman/8.4/en/with.html // Most of these examples are derived from https://dev.mysql.com/doc/refman/8.4/en/with.html
@ -1247,9 +1240,7 @@ class SQLSelectTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideWith')]
* @dataProvider provideWith
*/
public function testWith( public function testWith(
string $name, string $name,
SQLSelect $query, SQLSelect $query,
@ -1328,7 +1319,7 @@ class SQLSelectTest extends SapphireTest
$select->addWith('cte', new SQLSelect()); $select->addWith('cte', new SQLSelect());
} }
public function subqueryProvider() public static function subqueryProvider()
{ {
return [ return [
'no-explicit-alias-string' => ['( SELECT DISTINCT "SQLSelectTest_DO"."ClassName" FROM "SQLSelectTest_DO") AS "FINAL"'], 'no-explicit-alias-string' => ['( SELECT DISTINCT "SQLSelectTest_DO"."ClassName" FROM "SQLSelectTest_DO") AS "FINAL"'],
@ -1338,9 +1329,7 @@ class SQLSelectTest extends SapphireTest
]; ];
} }
/** #[DataProvider('subqueryProvider')]
* @dataProvider subqueryProvider
*/
public function testSubqueries($subquery) public function testSubqueries($subquery)
{ {
$query = new SQLSelect('*', $subquery); $query = new SQLSelect('*', $subquery);
@ -1353,7 +1342,7 @@ class SQLSelectTest extends SapphireTest
); );
} }
public function addFromProvider() public static function addFromProvider()
{ {
return [ return [
'string' => [ 'string' => [
@ -1391,9 +1380,7 @@ class SQLSelectTest extends SapphireTest
]; ];
} }
/** #[DataProvider('addFromProvider')]
* @dataProvider addFromProvider
*/
public function testAddFrom($input, $out, $message = ""): void public function testAddFrom($input, $out, $message = ""): void
{ {
$query = new SQLSelect(); $query = new SQLSelect();

View File

@ -14,6 +14,7 @@ use SilverStripe\ORM\Filters\SearchFilter;
use SilverStripe\ORM\Filters\StartsWithFilter; use SilverStripe\ORM\Filters\StartsWithFilter;
use SilverStripe\ORM\Search\BasicSearchContext; use SilverStripe\ORM\Search\BasicSearchContext;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use PHPUnit\Framework\Attributes\DataProvider;
class BasicSearchContextTest extends SapphireTest class BasicSearchContextTest extends SapphireTest
{ {
@ -96,7 +97,7 @@ class BasicSearchContextTest extends SapphireTest
$this->assertEquals(1, $results->Count()); $this->assertEquals(1, $results->Count());
} }
public function provideApplySearchFilters() public static function provideApplySearchFilters()
{ {
$idFilter = new ExactMatchFilter('ID'); $idFilter = new ExactMatchFilter('ID');
$idFilter->setModifiers(['nocase']); $idFilter->setModifiers(['nocase']);
@ -130,9 +131,7 @@ class BasicSearchContextTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideApplySearchFilters')]
* @dataProvider provideApplySearchFilters
*/
public function testApplySearchFilters(array $searchParams, ?array $filters, array $expected) public function testApplySearchFilters(array $searchParams, ?array $filters, array $expected)
{ {
$context = new BasicSearchContext(ArrayData::class); $context = new BasicSearchContext(ArrayData::class);
@ -146,7 +145,7 @@ class BasicSearchContextTest extends SapphireTest
$this->assertSame($expected, $reflectionApplySearchFilters->invoke($context, $searchParams)); $this->assertSame($expected, $reflectionApplySearchFilters->invoke($context, $searchParams));
} }
public function provideGetGeneralSearchFilterTerm() public static function provideGetGeneralSearchFilterTerm()
{ {
return [ return [
'defaults to case-insensitive partial match' => [ 'defaults to case-insensitive partial match' => [
@ -172,9 +171,7 @@ class BasicSearchContextTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideGetGeneralSearchFilterTerm')]
* @dataProvider provideGetGeneralSearchFilterTerm
*/
public function testGetGeneralSearchFilterTerm(?string $filterType, ?SearchFilter $fieldFilter, string $expected) public function testGetGeneralSearchFilterTerm(?string $filterType, ?SearchFilter $fieldFilter, string $expected)
{ {
$context = new BasicSearchContext(ArrayData::class); $context = new BasicSearchContext(ArrayData::class);
@ -190,7 +187,7 @@ class BasicSearchContextTest extends SapphireTest
$this->assertSame($expected, $reflectionGetGeneralSearchFilterTerm->invoke($context, 'MyField')); $this->assertSame($expected, $reflectionGetGeneralSearchFilterTerm->invoke($context, 'MyField'));
} }
public function provideGetQuery() public static function provideGetQuery()
{ {
// Note that the search TERM is the same for both scenarios, // Note that the search TERM is the same for both scenarios,
// but because the search FIELD is different, we get different results. // but because the search FIELD is different, we get different results.
@ -226,9 +223,7 @@ class BasicSearchContextTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideGetQuery')]
* @dataProvider provideGetQuery
*/
public function testGetQuery(array $searchParams, array $expected) public function testGetQuery(array $searchParams, array $expected)
{ {
$list = $this->getList(); $list = $this->getList();

View File

@ -5,6 +5,7 @@ namespace SilverStripe\Tests\ORM\UniqueKey;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use PHPUnit\Framework\Attributes\DataProvider;
class ServiceTest extends SapphireTest class ServiceTest extends SapphireTest
{ {
@ -21,8 +22,8 @@ class ServiceTest extends SapphireTest
* @param string $class * @param string $class
* @param bool $extraKeys * @param bool $extraKeys
* @param string $expected * @param string $expected
* @dataProvider uniqueKeysProvider
*/ */
#[DataProvider('uniqueKeysProvider')]
public function testUniqueKey(int $id, string $class, bool $extraKeys, string $expected): void public function testUniqueKey(int $id, string $class, bool $extraKeys, string $expected): void
{ {
if ($extraKeys) { if ($extraKeys) {
@ -40,7 +41,7 @@ class ServiceTest extends SapphireTest
} }
} }
public function uniqueKeysProvider(): array public static function uniqueKeysProvider(): array
{ {
return [ return [
[1, River::class, false, 'River-1-8d3310e232f75a01f5a0c9344655263d'], [1, River::class, false, 'River-1-8d3310e232f75a01f5a0c9344655263d'],

View File

@ -21,9 +21,9 @@ class StorageTest extends SapphireTest
{ {
$session = $this->createMock(Session::class); $session = $this->createMock(Session::class);
$sessionCleaned = false; $sessionCleaned = false;
$session->method('clear')->will($this->returnCallback(static function ($namespace) use (&$sessionCleaned) { $session->method('clear')->willReturnCallback(static function ($namespace) use (&$sessionCleaned) {
$sessionCleaned = $namespace; $sessionCleaned = $namespace;
})); });
$storage = new Storage($session, 'test'); $storage = new Storage($session, 'test');
@ -42,9 +42,9 @@ class StorageTest extends SapphireTest
{ {
$session = $this->createMock(Session::class); $session = $this->createMock(Session::class);
$sessionCleaned = false; $sessionCleaned = false;
$session->method('clear')->will($this->returnCallback(static function ($namespace) use (&$sessionCleaned) { $session->method('clear')->willReturnCallback(static function ($namespace) use (&$sessionCleaned) {
$sessionCleaned = $namespace; $sessionCleaned = $namespace;
})); });
$storage = new Storage($session, 'test', false); $storage = new Storage($session, 'test', false);

View File

@ -34,14 +34,16 @@ class ChangePasswordHandlerTest extends SapphireTest
]); ]);
$request->setSession(new Session([])); $request->setSession(new Session([]));
/** @var ChangePasswordHandler $handler */ // not using a phpunit mock otherwise get the error
$handler = $this->getMockBuilder(ChangePasswordHandler::class) // Error: Typed property MockObject_ChangePasswordHandler_12f49d86::$__phpunit_state
->disableOriginalConstructor() // must not be accessed before initialization
->setMethods(null) $handler = new class() extends ChangePasswordHandler {
->getMock(); public function __construct()
{
}
};
$result = $handler->setRequest($request)->changepassword(); $result = $handler->setRequest($request)->changepassword();
$this->assertIsArray($result, 'An array is returned'); $this->assertIsArray($result, 'An array is returned');
$this->assertStringContainsString('Security/lostpassword', $result['Content'], 'Lost password URL is included'); $this->assertStringContainsString('Security/lostpassword', $result['Content'], 'Lost password URL is included');
$this->assertStringContainsString('Security/login', $result['Content'], 'Login URL is included'); $this->assertStringContainsString('Security/login', $result['Content'], 'Login URL is included');

View File

@ -35,6 +35,7 @@ use SilverStripe\Security\Security;
use SilverStripe\Security\Tests\MemberTest\FieldsExtension; use SilverStripe\Security\Tests\MemberTest\FieldsExtension;
use SilverStripe\SessionManager\Models\LoginSession; use SilverStripe\SessionManager\Models\LoginSession;
use ReflectionMethod; use ReflectionMethod;
use PHPUnit\Framework\Attributes\DataProvider;
class MemberTest extends FunctionalTest class MemberTest extends FunctionalTest
{ {
@ -1647,9 +1648,6 @@ class MemberTest extends FunctionalTest
$this->assertEquals($adminMember->ID, $userFromSession->ID); $this->assertEquals($adminMember->ID, $userFromSession->ID);
} }
/**
* @covers \SilverStripe\Security\Member::actAs()
*/
public function testActAsUserPermissions() public function testActAsUserPermissions()
{ {
$this->assertNull(Security::getCurrentUser()); $this->assertNull(Security::getCurrentUser());
@ -1686,9 +1684,6 @@ class MemberTest extends FunctionalTest
$this->assertTrue($checkAdmin); $this->assertTrue($checkAdmin);
} }
/**
* @covers \SilverStripe\Security\Member::actAs()
*/
public function testActAsUser() public function testActAsUser()
{ {
$this->assertNull(Security::getCurrentUser()); $this->assertNull(Security::getCurrentUser());
@ -1794,9 +1789,7 @@ class MemberTest extends FunctionalTest
$this->assertEmpty($result, 'Without LeftAndMain, no groups are CMS groups.'); $this->assertEmpty($result, 'Without LeftAndMain, no groups are CMS groups.');
} }
/** #[DataProvider('provideMapInCMSGroups')]
* @dataProvider provideMapInCMSGroups
*/
public function testMapInCMSGroups(array $groupFixtures, array $groupCodes, array $expectedUsers) public function testMapInCMSGroups(array $groupFixtures, array $groupCodes, array $expectedUsers)
{ {
if (!empty($groupFixtures) && !empty($groupCodes)) { if (!empty($groupFixtures) && !empty($groupCodes)) {
@ -1837,7 +1830,7 @@ class MemberTest extends FunctionalTest
$this->assertEqualsCanonicalizing($expectedUsers, $result->keys()); $this->assertEqualsCanonicalizing($expectedUsers, $result->keys());
} }
public function provideMapInCMSGroups() public static function provideMapInCMSGroups()
{ {
// Note: "ADMIN User" is not from the fixtures, that user is created by $this->logInWithPermission('ADMIN') // Note: "ADMIN User" is not from the fixtures, that user is created by $this->logInWithPermission('ADMIN')
return [ return [
@ -1860,7 +1853,7 @@ class MemberTest extends FunctionalTest
], ],
], ],
'single group in IDs array' => [ 'single group in IDs array' => [
'groups' => [ 'groupFixtures' => [
'staffgroup', 'staffgroup',
], ],
'groupCodes' => [], 'groupCodes' => [],

View File

@ -6,6 +6,7 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\Security\Tests\GroupTest\TestMember; use SilverStripe\Security\Tests\GroupTest\TestMember;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataList;
use PHPUnit\Framework\Attributes\DataProvider;
class Member_GroupSetTest extends SapphireTest class Member_GroupSetTest extends SapphireTest
{ {
@ -15,9 +16,7 @@ class Member_GroupSetTest extends SapphireTest
TestMember::class TestMember::class
]; ];
/** #[DataProvider('provideForForeignIDPlaceholders')]
* @dataProvider provideForForeignIDPlaceholders
*/
public function testForForeignIDPlaceholders(bool $config, bool $useInt, bool $expected): void public function testForForeignIDPlaceholders(bool $config, bool $useInt, bool $expected): void
{ {
Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config); Config::modify()->set(DataList::class, 'use_placeholders_for_integer_ids', $config);
@ -34,10 +33,12 @@ class Member_GroupSetTest extends SapphireTest
$expectedIDs = $useInt $expectedIDs = $useInt
? array_unique(array_merge($groups1->column('ID'), $groups2->column('ID'))) ? array_unique(array_merge($groups1->column('ID'), $groups2->column('ID')))
: []; : [];
$this->assertEqualsCanonicalizing($expectedIDs, $newGroupList->column('ID')); sort($expectedIDs);
$actual = $newGroupList->sort('ID')->column('ID');
$this->assertSame($expectedIDs, $actual);
} }
public function provideForForeignIDPlaceholders(): array public static function provideForForeignIDPlaceholders(): array
{ {
return [ return [
'config false' => [ 'config false' => [

View File

@ -33,7 +33,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
private function getMemberMock($isPasswordExpired) : Member private function getMemberMock($isPasswordExpired) : Member
{ {
$mock = $this->createMock(Member::class); $mock = $this->createMock(Member::class);
$mock->method('isPasswordExpired')->will($this->returnValue($isPasswordExpired)); $mock->method('isPasswordExpired')->willReturn($isPasswordExpired);
return $mock; return $mock;
} }
@ -61,8 +61,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
* Check a member with an expired password is allowed to process the request in * Check a member with an expired password is allowed to process the request in
* deauthorised mode (Security::getCurrentUser() === null) if there are no * deauthorised mode (Security::getCurrentUser() === null) if there are no
* change password redirects registered * change password redirects registered
*
* @depends test200
*/ */
public function testDeauthorised() public function testDeauthorised()
{ {
@ -87,8 +85,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Check a member with an expired password is redirected to a change password form * Check a member with an expired password is redirected to a change password form
* instead of processing its original request * instead of processing its original request
*
* @depends test200
*/ */
public function testRedirected() public function testRedirected()
{ {
@ -98,7 +94,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/'); $request = $this->buildRequestMock('/');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$a->setRedirect($session, '/redirect-address-custom'); $a->setRedirect($session, '/redirect-address-custom');
@ -120,8 +116,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Check we handle network locations correctly (the relative urls starting with //) * Check we handle network locations correctly (the relative urls starting with //)
*
* @depends testRedirected
*/ */
public function testNetworkLocationRedirect() public function testNetworkLocationRedirect()
{ {
@ -131,7 +125,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/'); $request = $this->buildRequestMock('/');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$a->setRedirect($session, '//localhost/custom-base/redirect-address-custom'); $a->setRedirect($session, '//localhost/custom-base/redirect-address-custom');
@ -153,9 +147,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Check we can allow the current request handling even with an expired password * Check we can allow the current request handling even with an expired password
*
* @depends test200
* @depends testDeauthorised
*/ */
public function testAllowRequest() public function testAllowRequest()
{ {
@ -183,8 +174,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Check a member with an expired password is redirected to a default change password form * Check a member with an expired password is redirected to a default change password form
* if a custom not set * if a custom not set
*
* @depends testRedirected
*/ */
public function testDefaultRedirect() public function testDefaultRedirect()
{ {
@ -196,7 +185,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/'); $request = $this->buildRequestMock('/');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$executed = false; $executed = false;
@ -217,8 +206,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Check a member with an expired password is redirected to a default change password form * Check a member with an expired password is redirected to a default change password form
* if a custom not set * if a custom not set
*
* @depends testDefaultRedirect
*/ */
public function testCustomRedirect() public function testCustomRedirect()
{ {
@ -230,7 +217,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/'); $request = $this->buildRequestMock('/');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$executed = false; $executed = false;
$activeMember = null; $activeMember = null;
@ -249,8 +236,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Check a custom redirect URL overrides the default one * Check a custom redirect URL overrides the default one
*
* @depends testCustomRedirect
*/ */
public function testCustomOverDefaultRedirect() public function testCustomOverDefaultRedirect()
{ {
@ -262,7 +247,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/'); $request = $this->buildRequestMock('/');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$a->setRedirect($session, '/redirect-address-custom'); $a->setRedirect($session, '/redirect-address-custom');
@ -283,8 +268,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Test we can allow URLs to be visited without redirections through config * Test we can allow URLs to be visited without redirections through config
*
* @depends testRedirected
*/ */
public function testAllowedUrlStartswithNegative() public function testAllowedUrlStartswithNegative()
{ {
@ -298,7 +281,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/not-allowed'); $request = $this->buildRequestMock('/not-allowed');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$a->setRedirect($session, '/redirect-address-custom'); $a->setRedirect($session, '/redirect-address-custom');
@ -320,8 +303,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Test we can allow URLs to be visited without redirections through config * Test we can allow URLs to be visited without redirections through config
*
* @depends testRedirected
*/ */
public function testAllowedUrlStartswithPositivePattern() public function testAllowedUrlStartswithPositivePattern()
{ {
@ -335,7 +316,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/allowed-address-configured/subsection1/subsection2/'); $request = $this->buildRequestMock('/allowed-address-configured/subsection1/subsection2/');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$a->setRedirect($session, '/redirect-address-custom'); $a->setRedirect($session, '/redirect-address-custom');
@ -364,7 +345,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/allowed-address-configured?foo=bar'); $request = $this->buildRequestMock('/allowed-address-configured?foo=bar');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$a->setRedirect($session, '/redirect-address-custom'); $a->setRedirect($session, '/redirect-address-custom');
@ -393,7 +374,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/allowed-address-configured?foo=bar'); $request = $this->buildRequestMock('/allowed-address-configured?foo=bar');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$a->setRedirect($session, 'redirect-address-custom'); $a->setRedirect($session, 'redirect-address-custom');
@ -412,8 +393,6 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
/** /**
* Test we can allow URLs to be visited without redirections through config * Test we can allow URLs to be visited without redirections through config
*
* @depends testRedirected
*/ */
public function testAllowedUrlStartswithPositiveExactUrl() public function testAllowedUrlStartswithPositiveExactUrl()
{ {
@ -427,7 +406,7 @@ class PasswordExpirationMiddlewareTest extends SapphireTest
$a = new PasswordExpirationMiddleware(); $a = new PasswordExpirationMiddleware();
$request = $this->buildRequestMock('/allowed-address-configured/'); $request = $this->buildRequestMock('/allowed-address-configured/');
$request->method('getAcceptMimetypes')->will($this->returnValue(['*/*'])); $request->method('getAcceptMimetypes')->willReturn(['*/*']);
$session = $request->getSession(); $session = $request->getSession();
$a->setRedirect($session, '/redirect-address-custom'); $a->setRedirect($session, '/redirect-address-custom');

View File

@ -7,6 +7,7 @@ use SilverStripe\Security\Member;
use SilverStripe\Security\RememberLoginHash; use SilverStripe\Security\RememberLoginHash;
use SilverStripe\SessionManager\Models\LoginSession; use SilverStripe\SessionManager\Models\LoginSession;
use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\Deprecation;
use PHPUnit\Framework\Attributes\DataProvider;
class RememberLoginHashTest extends SapphireTest class RememberLoginHashTest extends SapphireTest
{ {
@ -32,7 +33,7 @@ class RememberLoginHashTest extends SapphireTest
]; ];
} }
public function clearScenarios() public static function clearScenarios()
{ {
return [ return [
'logout across devices' => [true, 'current', ['secondary'], ['current', 'other']], 'logout across devices' => [true, 'current', ['secondary'], ['current', 'other']],
@ -47,8 +48,8 @@ class RememberLoginHashTest extends SapphireTest
* @param mixed $deviceId * @param mixed $deviceId
* @param array $expected * @param array $expected
* @param array $unexpected * @param array $unexpected
* @dataProvider clearScenarios
*/ */
#[DataProvider('clearScenarios')]
public function testClear(bool $logoutAcrossDevices, $deviceId, array $expected, array $unexpected) public function testClear(bool $logoutAcrossDevices, $deviceId, array $expected, array $unexpected)
{ {
// If session-manager module is installed then logout_across_devices is modified so skip // If session-manager module is installed then logout_across_devices is modified so skip
@ -98,9 +99,9 @@ class RememberLoginHashTest extends SapphireTest
} }
/** /**
* @dataProvider provideRenew
* @param bool $replaceToken * @param bool $replaceToken
*/ */
#[DataProvider('provideRenew')]
public function testRenew($replaceToken) public function testRenew($replaceToken)
{ {
// If session-manager module is installed it expects an active request during renewal // If session-manager module is installed it expects an active request during renewal
@ -132,7 +133,7 @@ class RememberLoginHashTest extends SapphireTest
} }
} }
public function provideRenew(): array public static function provideRenew(): array
{ {
return [ return [
[true], [true],

View File

@ -4,11 +4,11 @@ namespace SilverStripe\View\Tests;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\View\Tests\AttributesHTMLTest\DummyAttributesHTML; use SilverStripe\View\Tests\AttributesHTMLTest\DummyAttributesHTML;
use PHPUnit\Framework\Attributes\DataProvider;
class AttributesHTMLTest extends SapphireTest class AttributesHTMLTest extends SapphireTest
{ {
public static function provideGetAttribute(): array
public function provideGetAttribute(): array
{ {
return [ return [
'empty string' => ['test', '', 'Empty string is not converted to a different falsy value'], 'empty string' => ['test', '', 'Empty string is not converted to a different falsy value'],
@ -23,7 +23,7 @@ class AttributesHTMLTest extends SapphireTest
]; ];
} }
/** @dataProvider provideGetAttribute */ #[DataProvider('provideGetAttribute')]
public function testGetAttribute($name, $value, $message): void public function testGetAttribute($name, $value, $message): void
{ {
$dummy = new DummyAttributesHTML(); $dummy = new DummyAttributesHTML();

View File

@ -7,6 +7,7 @@ use SilverStripe\View\Parsers\HTMLValue;
use SilverStripe\ORM\FieldType\DBHTMLText; use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\View\Parsers\ShortcodeParser; use SilverStripe\View\Parsers\ShortcodeParser;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use PHPUnit\Framework\Attributes\DataProvider;
class HTMLValueTest extends SapphireTest class HTMLValueTest extends SapphireTest
{ {
@ -161,7 +162,7 @@ class HTMLValueTest extends SapphireTest
} }
} }
public function provideOnlyStripIntendedTags(): array public static function provideOnlyStripIntendedTags(): array
{ {
return [ return [
[ [
@ -179,9 +180,7 @@ class HTMLValueTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideOnlyStripIntendedTags')]
* @dataProvider provideOnlyStripIntendedTags
*/
public function testOnlyStripIntendedTags(string $input, string $expected): void public function testOnlyStripIntendedTags(string $input, string $expected): void
{ {
$value = new HTMLValue(); $value = new HTMLValue();

View File

@ -5,6 +5,8 @@ namespace SilverStripe\View\Tests\Parsers;
use SebastianBergmann\Diff\Differ; use SebastianBergmann\Diff\Differ;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\View\Parsers\HtmlDiff; use SilverStripe\View\Parsers\HtmlDiff;
use PHPUnit\Framework\Attributes\DataProvider;
use SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder;
class HtmlDiffTest extends SapphireTest class HtmlDiffTest extends SapphireTest
{ {
@ -49,7 +51,7 @@ class HtmlDiffTest extends SapphireTest
// Ensure that this test is valid and that those changes would include an end-of-line warning // Ensure that this test is valid and that those changes would include an end-of-line warning
// in a direct call to the underlying differ // in a direct call to the underlying differ
$differ = new Differ(); $differ = new Differ(new DiffOnlyOutputBuilder());
$expected = [ $expected = [
[ [
'#Warning: Strings contain different line endings!' . "\n", '#Warning: Strings contain different line endings!' . "\n",
@ -67,7 +69,7 @@ class HtmlDiffTest extends SapphireTest
$this->assertSame($expected, $differ->diffToArray($from, $to)); $this->assertSame($expected, $differ->diffToArray($from, $to));
} }
public function provideCompareHtml(): array public static function provideCompareHtml(): array
{ {
return [ return [
[ [
@ -148,9 +150,7 @@ class HtmlDiffTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideCompareHtml')]
* @dataProvider provideCompareHtml
*/
public function testCompareHTML(string|array $from, string|array $to, bool $escape, string $expected) public function testCompareHTML(string|array $from, string|array $to, bool $escape, string $expected)
{ {
$diff = HtmlDiff::compareHtml($from, $to, $escape); $diff = HtmlDiff::compareHtml($from, $to, $escape);

View File

@ -4,6 +4,7 @@ namespace SilverStripe\View\Tests\Parsers;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\View\Parsers\ShortcodeParser; use SilverStripe\View\Parsers\ShortcodeParser;
use PHPUnit\Framework\Attributes\DataProvider;
class ShortcodeParserTest extends SapphireTest class ShortcodeParserTest extends SapphireTest
{ {
@ -79,7 +80,7 @@ class ShortcodeParserTest extends SapphireTest
); );
} }
public function simpleTagDataProvider() public static function simpleTagDataProvider()
{ {
return [ return [
['[test_shortcode]'], ['[test_shortcode]'],
@ -92,9 +93,7 @@ class ShortcodeParserTest extends SapphireTest
]; ];
} }
/** #[DataProvider('simpleTagDataProvider')]
* @dataProvider simpleTagDataProvider
*/
public function testSimpleTag($test) public function testSimpleTag($test)
{ {
$this->parser->parse($test); $this->parser->parse($test);
@ -103,7 +102,7 @@ class ShortcodeParserTest extends SapphireTest
$this->assertEquals('test_shortcode', $this->tagName, $test); $this->assertEquals('test_shortcode', $this->tagName, $test);
} }
public function oneArgumentDataProvider() public static function oneArgumentDataProvider()
{ {
return [ return [
['[test_shortcode foo="bar"]'], ['[test_shortcode foo="bar"]'],
@ -117,9 +116,7 @@ class ShortcodeParserTest extends SapphireTest
]; ];
} }
/** #[DataProvider('oneArgumentDataProvider')]
* @dataProvider oneArgumentDataProvider
*/
public function testOneArgument($test) public function testOneArgument($test)
{ {
$this->parser->parse($test); $this->parser->parse($test);
@ -138,7 +135,7 @@ class ShortcodeParserTest extends SapphireTest
$this->assertEquals('test_shortcode', $this->tagName); $this->assertEquals('test_shortcode', $this->tagName);
} }
public function emptyArgumentsDataProvider() public static function emptyArgumentsDataProvider()
{ {
return [ return [
['[test_shortcode foo=""]'], ['[test_shortcode foo=""]'],
@ -147,9 +144,7 @@ class ShortcodeParserTest extends SapphireTest
]; ];
} }
/** #[DataProvider('emptyArgumentsDataProvider')]
* @dataProvider emptyArgumentsDataProvider
*/
public function testEmptyArguments($test) public function testEmptyArguments($test)
{ {
$this->parser->parse($test); $this->parser->parse($test);
@ -359,7 +354,7 @@ class ShortcodeParserTest extends SapphireTest
public function testNoParseAttemptIfNoCode() public function testNoParseAttemptIfNoCode()
{ {
$stub = $this->getMockBuilder(ShortcodeParser::class)->setMethods(['replaceElementTagsWithMarkers']) $stub = $this->getMockBuilder(ShortcodeParser::class)->onlyMethods(['replaceElementTagsWithMarkers'])
->getMock(); ->getMock();
$stub->register( $stub->register(
'test', 'test',
@ -369,7 +364,7 @@ class ShortcodeParserTest extends SapphireTest
); );
$stub->expects($this->never()) $stub->expects($this->never())
->method('replaceElementTagsWithMarkers')->will($this->returnValue(['', ''])); ->method('replaceElementTagsWithMarkers')->willReturn(['', '']);
$stub->parse('<p>test</p>'); $stub->parse('<p>test</p>');
} }

View File

@ -33,6 +33,8 @@ use SilverStripe\View\Tests\SSViewerTest\SSViewerTestModel;
use SilverStripe\View\Tests\SSViewerTest\SSViewerTestModelController; use SilverStripe\View\Tests\SSViewerTest\SSViewerTestModelController;
use SilverStripe\View\Tests\SSViewerTest\TestViewableData; use SilverStripe\View\Tests\SSViewerTest\TestViewableData;
use SilverStripe\View\ViewableData; use SilverStripe\View\ViewableData;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\DoesNotPerformAssertions;
class SSViewerTest extends SapphireTest class SSViewerTest extends SapphireTest
{ {
@ -208,7 +210,7 @@ class SSViewerTest extends SapphireTest
/** @var Requirements_Backend|MockObject $requirements */ /** @var Requirements_Backend|MockObject $requirements */
$requirements = $this $requirements = $this
->getMockBuilder(Requirements_Backend::class) ->getMockBuilder(Requirements_Backend::class)
->setMethods(["javascript", "css"]) ->onlyMethods(["javascript", "css"])
->getMock(); ->getMock();
$jsFile = FRAMEWORK_DIR . '/tests/forms/a.js'; $jsFile = FRAMEWORK_DIR . '/tests/forms/a.js';
$cssFile = FRAMEWORK_DIR . '/tests/forms/a.js'; $cssFile = FRAMEWORK_DIR . '/tests/forms/a.js';
@ -567,7 +569,7 @@ SS;
$this->assertEquals("SubKid1SubKid2Number6", $result, "Loop in current scope works"); $this->assertEquals("SubKid1SubKid2Number6", $result, "Loop in current scope works");
} }
public function provideArgumentTypes() public static function provideArgumentTypes()
{ {
return [ return [
[ [
@ -593,9 +595,7 @@ SS;
]; ];
} }
/** #[DataProvider('provideArgumentTypes')]
* @dataProvider provideArgumentTypes
*/
public function testArgumentTypes(string $expected, string $template) public function testArgumentTypes(string $expected, string $template)
{ {
$this->assertEquals($expected, $this->render($template, new TestViewableData())); $this->assertEquals($expected, $this->render($template, new TestViewableData()));
@ -706,7 +706,7 @@ after'
); );
} }
public function typePreservationDataProvider() public static function typePreservationDataProvider()
{ {
return [ return [
// Null // Null
@ -763,9 +763,7 @@ after'
]; ];
} }
/** #[DataProvider('typePreservationDataProvider')]
* @dataProvider typePreservationDataProvider
*/
public function testTypesArePreserved($expected, $templateArg) public function testTypesArePreserved($expected, $templateArg)
{ {
$data = new ArrayData([ $data = new ArrayData([
@ -775,9 +773,7 @@ after'
$this->assertEquals($expected, $this->render("\$Test.Type({$templateArg})", $data)); $this->assertEquals($expected, $this->render("\$Test.Type({$templateArg})", $data));
} }
/** #[DataProvider('typePreservationDataProvider')]
* @dataProvider typePreservationDataProvider
*/
public function testTypesArePreservedAsIncludeArguments($expected, $templateArg) public function testTypesArePreservedAsIncludeArguments($expected, $templateArg)
{ {
$data = new ArrayData([ $data = new ArrayData([
@ -1034,7 +1030,7 @@ after'
); );
} }
public function provideIfBlockWithIterable(): array public static function provideIfBlockWithIterable(): array
{ {
$scenarios = [ $scenarios = [
'empty array' => [ 'empty array' => [
@ -1057,9 +1053,7 @@ after'
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideIfBlockWithIterable')]
* @dataProvider provideIfBlockWithIterable
*/
public function testIfBlockWithIterable(iterable $iterable, bool $inScope): void public function testIfBlockWithIterable(iterable $iterable, bool $inScope): void
{ {
$expected = count($iterable) ? 'has value' : 'no value'; $expected = count($iterable) ? 'has value' : 'no value';
@ -1387,7 +1381,7 @@ after'
); );
} }
public function provideLoop(): array public static function provideLoop(): array
{ {
return [ return [
'nested array and iterator' => [ 'nested array and iterator' => [
@ -1422,16 +1416,14 @@ after'
]; ];
} }
/** #[DataProvider('provideLoop')]
* @dataProvider provideLoop
*/
public function testLoop(iterable $iterable, string $template, string $expected): void public function testLoop(iterable $iterable, string $template, string $expected): void
{ {
$data = new ArrayData(['Iterable' => $iterable]); $data = new ArrayData(['Iterable' => $iterable]);
$this->assertEqualIgnoringWhitespace($expected, $this->render($template, $data)); $this->assertEqualIgnoringWhitespace($expected, $this->render($template, $data));
} }
public function provideCountIterable(): array public static function provideCountIterable(): array
{ {
$scenarios = [ $scenarios = [
'empty array' => [ 'empty array' => [
@ -1454,9 +1446,7 @@ after'
return $scenarios; return $scenarios;
} }
/** #[DataProvider('provideCountIterable')]
* @dataProvider provideCountIterable
*/
public function testCountIterable(iterable $iterable, bool $inScope): void public function testCountIterable(iterable $iterable, bool $inScope): void
{ {
$expected = count($iterable); $expected = count($iterable);
@ -1878,9 +1868,6 @@ after'
); );
} }
/**
* @covers \SilverStripe\View\SSViewer::get_templates_by_class()
*/
public function testGetTemplatesByClass() public function testGetTemplatesByClass()
{ {
$this->useTestTheme( $this->useTestTheme(
@ -2369,10 +2356,15 @@ EOC;
); );
} }
#[DoesNotPerformAssertions]
public function testMe(): void public function testMe(): void
{ {
$mockArrayData = $this->getMockBuilder(ArrayData::class)->addMethods(['forTemplate'])->getMock(); $myArrayData = new class extends ArrayData {
$mockArrayData->expects($this->once())->method('forTemplate')->willReturn(''); public function forTemplate()
$this->render('$Me', $mockArrayData); {
return '';
}
};
$this->render('$Me', $myArrayData);
} }
} }

View File

@ -12,6 +12,7 @@ use SilverStripe\View\SSViewer;
use SilverStripe\View\Tests\ViewableDataTest\ViewableDataTestExtension; use SilverStripe\View\Tests\ViewableDataTest\ViewableDataTestExtension;
use SilverStripe\View\Tests\ViewableDataTest\ViewableDataTestObject; use SilverStripe\View\Tests\ViewableDataTest\ViewableDataTestObject;
use SilverStripe\View\ViewableData; use SilverStripe\View\ViewableData;
use PHPUnit\Framework\Attributes\DataProvider;
/** /**
* See {@link SSViewerTest->testCastingHelpers()} for more tests related to casting and ViewableData behaviour, * See {@link SSViewerTest->testCastingHelpers()} for more tests related to casting and ViewableData behaviour,
@ -284,7 +285,7 @@ class ViewableDataTest extends SapphireTest
$this->assertSame($obj, $viewableData->abc); $this->assertSame($obj, $viewableData->abc);
} }
public function provideWrapArrayInObj(): array public static function provideWrapArrayInObj(): array
{ {
return [ return [
'empty array' => [ 'empty array' => [
@ -301,9 +302,7 @@ class ViewableDataTest extends SapphireTest
]; ];
} }
/** #[DataProvider('provideWrapArrayInObj')]
* @dataProvider provideWrapArrayInObj
*/
public function testWrapArrayInObj(array $arr, string $expectedClass): void public function testWrapArrayInObj(array $arr, string $expectedClass): void
{ {
$viewableData = new ViewableData(); $viewableData = new ViewableData();

View File

@ -8,9 +8,6 @@ use Symfony\Component\Translation\Exception\InvalidResourceException;
class YamlReaderTest extends SapphireTest class YamlReaderTest extends SapphireTest
{ {
/**
*
*/
public function testRead() public function testRead()
{ {
$reader = new YamlReader(); $reader = new YamlReader();

View File

@ -12,6 +12,7 @@ use SilverStripe\i18n\Messages\MessageProvider;
use SilverStripe\i18n\Messages\Symfony\SymfonyMessageProvider; use SilverStripe\i18n\Messages\Symfony\SymfonyMessageProvider;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use PHPUnit\Framework\Attributes\DataProvider;
class i18nTest extends SapphireTest class i18nTest extends SapphireTest
{ {
@ -426,7 +427,7 @@ class i18nTest extends SapphireTest
); );
} }
public function pluralisationDataProvider() public static function pluralisationDataProvider()
{ {
return [ return [
// English - 2 plural forms // English - 2 plural forms
@ -451,11 +452,11 @@ class i18nTest extends SapphireTest
} }
/** /**
* @dataProvider pluralisationDataProvider()
* @param string $locale * @param string $locale
* @param int $count * @param int $count
* @param string $expected * @param string $expected
*/ */
#[DataProvider('pluralisationDataProvider')]
public function testPluralisation($locale, $count, $expected) public function testPluralisation($locale, $count, $expected)
{ {
i18n::set_locale($locale); i18n::set_locale($locale);

View File

@ -6,10 +6,12 @@ use SilverStripe\Assets\Filesystem;
use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Core\Manifest\ModuleLoader;
use SilverStripe\Core\Manifest\ModuleManifest; use SilverStripe\Core\Manifest\ModuleManifest;
use SilverStripe\Core\Path; use SilverStripe\Core\Path;
use SilverStripe\Dev\Exceptions\ExpectedNoticeException;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\i18n\i18n; use SilverStripe\i18n\i18n;
use SilverStripe\i18n\Messages\YamlWriter; use SilverStripe\i18n\Messages\YamlWriter;
use SilverStripe\i18n\Tests\i18nTextCollectorTest\Collector; use SilverStripe\i18n\Tests\i18nTextCollectorTest\Collector;
use SilverStripe\i18n\Tests\i18nTextCollectorTest\i18nTextCollectorTestException;
use SilverStripe\i18n\TextCollection\i18nTextCollector; use SilverStripe\i18n\TextCollection\i18nTextCollector;
class i18nTextCollectorTest extends SapphireTest class i18nTextCollectorTest extends SapphireTest
@ -74,6 +76,8 @@ PHP;
public function testCollectFromNewTemplateSyntaxUsingParserSubclass() public function testCollectFromNewTemplateSyntaxUsingParserSubclass()
{ {
$this->enableErrorHandler();
$c = i18nTextCollector::create(); $c = i18nTextCollector::create();
$c->setWarnOnEmptyDefault(false); $c->setWarnOnEmptyDefault(false);
$mymodule = ModuleLoader::inst()->getManifest()->getModule('i18ntestmodule'); $mymodule = ModuleLoader::inst()->getManifest()->getModule('i18ntestmodule');
@ -115,8 +119,8 @@ SS;
// Test warning is raised on empty default // Test warning is raised on empty default
$c->setWarnOnEmptyDefault(true); $c->setWarnOnEmptyDefault(true);
$this->expectNotice(); $this->expectException(ExpectedNoticeException::class);
$this->expectNoticeMessage('Missing localisation default for key i18nTestModule.INJECTIONS_3'); $this->expectExceptionMessage('Missing localisation default for key i18nTestModule.INJECTIONS_3');
$c->collectFromTemplate($html, null, $mymodule); $c->collectFromTemplate($html, null, $mymodule);
} }
@ -153,6 +157,7 @@ SS;
public function testCollectFromTemplateAdvanced() public function testCollectFromTemplateAdvanced()
{ {
$this->enableErrorHandler();
$c = i18nTextCollector::create(); $c = i18nTextCollector::create();
$c->setWarnOnEmptyDefault(false); $c->setWarnOnEmptyDefault(false);
$mymodule = ModuleLoader::inst()->getManifest()->getModule('i18ntestmodule'); $mymodule = ModuleLoader::inst()->getManifest()->getModule('i18ntestmodule');
@ -190,8 +195,8 @@ SS;
// Test warning is raised on empty default // Test warning is raised on empty default
$c->setWarnOnEmptyDefault(true); $c->setWarnOnEmptyDefault(true);
$this->expectNotice(); $this->expectException(ExpectedNoticeException::class);
$this->expectNoticeMessage('Missing localisation default for key Test.PRIOANDCOMMENT'); $this->expectExceptionMessage('Missing localisation default for key Test.PRIOANDCOMMENT');
$c->collectFromTemplate($html, 'Test', $mymodule); $c->collectFromTemplate($html, 'Test', $mymodule);
} }
@ -479,6 +484,7 @@ PHP;
*/ */
public function testCollectFromCodeNewSignature() public function testCollectFromCodeNewSignature()
{ {
$this->enableErrorHandler();
$c = i18nTextCollector::create(); $c = i18nTextCollector::create();
$c->setWarnOnEmptyDefault(false); // Disable warnings for tests $c->setWarnOnEmptyDefault(false); // Disable warnings for tests
$mymodule = ModuleLoader::inst()->getManifest()->getModule('i18ntestmodule'); $mymodule = ModuleLoader::inst()->getManifest()->getModule('i18ntestmodule');
@ -523,8 +529,8 @@ PHP;
$this->assertEquals($expectedArray, $collectedTranslatables); $this->assertEquals($expectedArray, $collectedTranslatables);
// Test warning is raised on empty default // Test warning is raised on empty default
$this->expectNotice(); $this->expectException(ExpectedNoticeException::class);
$this->expectNoticeMessage('Missing localisation default for key i18nTestModule.INJECTIONS4'); $this->expectExceptionMessage('Missing localisation default for key i18nTestModule.INJECTIONS4');
$php = <<<PHP $php = <<<PHP
_t('i18nTestModule.INJECTIONS4', ["name"=>"Cat", "greeting"=>"meow", "goodbye"=>"meow"]); _t('i18nTestModule.INJECTIONS4', ["name"=>"Cat", "greeting"=>"meow", "goodbye"=>"meow"]);