Skip to content

Commit

Permalink
Merge pull request #409 from creative-commoners/pulls/3/sapphire-test…
Browse files Browse the repository at this point in the history
…-nine

API phpunit9 support
  • Loading branch information
Maxime Rainville authored Nov 1, 2021
2 parents 7fa8afd + 55b598d commit 930fa51
Show file tree
Hide file tree
Showing 30 changed files with 127 additions and 128 deletions.
5 changes: 2 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"type": "silverstripe-vendormodule",
"license": "BSD-3-Clause",
"require": {
"silverstripe/framework": "^4.2",
"silverstripe/framework": "^4.10",
"silverstripe/vendor-plugin": "^1.0",
"webonyx/graphql-php": "~0.12.6"
},
Expand All @@ -17,8 +17,7 @@
"dnadesign/silverstripe-elemental": "<4.6"
},
"require-dev": {
"sminnee/phpunit": "^5.7",
"sminnee/phpunit-mock-objects": "^3.4.5",
"phpunit/phpunit": "^9.5",
"squizlabs/php_codesniffer": "^3.0"
},
"autoload": {
Expand Down
8 changes: 5 additions & 3 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<phpunit bootstrap="vendor/silverstripe/framework/tests/bootstrap.php" colors="true">

<testsuite name="Default">
<directory>tests</directory>
</testsuite>
<testsuites>
<testsuite name="Default">
<directory>tests</directory>
</testsuite>
</testsuites>

<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
Expand Down
17 changes: 7 additions & 10 deletions tests/Auth/HandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class HandlerTest extends SapphireTest
/**
* {@inheritDoc}
*/
public function setUp()
protected function setUp(): void
{
parent::setUp();
Handler::config()->remove('authenticators');
Expand Down Expand Up @@ -65,12 +65,11 @@ public function testGetAuthenticator()

/**
* Test that an exception is thrown if an authenticator is configured that doesn't implement the interface
*
* @expectedException \SilverStripe\ORM\ValidationException
* @expectedExceptionMessage stdClass must implement SilverStripe\GraphQL\Auth\AuthenticatorInterface!
*/
public function testExceptionThrownWhenAuthenticatorDoesNotImplementAuthenticatorInterface()
{
$this->expectException(\SilverStripe\ORM\ValidationException::class);
$this->expectExceptionMessage('stdClass must implement SilverStripe\GraphQL\Auth\AuthenticatorInterface!');
Handler::config()->update('authenticators', [
['class' => 'stdClass']
]);
Expand Down Expand Up @@ -131,12 +130,11 @@ public function prioritisedAuthenticatorProvider()

/**
* Ensure that an failed authentication attempt throws an exception
*
* @expectedException \SilverStripe\ORM\ValidationException
* @expectedExceptionMessage Never!
*/
public function testFailedAuthenticationThrowsException()
{
$this->expectException(\SilverStripe\ORM\ValidationException::class);
$this->expectExceptionMessage('Never!');
Handler::config()->update('authenticators', [
['class' => BrutalAuthenticatorFake::class]
]);
Expand All @@ -148,12 +146,11 @@ public function testFailedAuthenticationThrowsException()
* Ensure that when a falsy value is returned from an authenticator (when it should throw
* an exception on failure) that a sensible default message is used in a ValidationException
* instead.
*
* @expectedException \SilverStripe\ORM\ValidationException
* @expectedExceptionMessage Authentication failed.
*/
public function testFailedAuthenticationWithFalsyReturnValueThrowsDefaultException()
{
$this->expectException(\SilverStripe\ORM\ValidationException::class);
$this->expectExceptionMessage('Authentication failed');
Handler::config()->update('authenticators', [
['class' => FalsyAuthenticatorFake::class]
]);
Expand Down
4 changes: 2 additions & 2 deletions tests/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class ConnectionTest extends SapphireTest
*/
private $manager;

public function setUp()
protected function setUp(): void
{
parent::setUp();

Expand Down Expand Up @@ -158,7 +158,7 @@ public function testResolveListSortWithCustomMapping()

public function testSortByInvalidColumnThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->expectException(\InvalidArgumentException::class);

$list = DataObjectFake::get();

Expand Down
30 changes: 16 additions & 14 deletions tests/ControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

use Exception;
use GraphQL\Type\Definition\Type;
use PHPUnit_Framework_MockObject_MockBuilder;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\MockObject\MockBuilder;
use SilverStripe\Assets\Dev\TestAssetStore;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
Expand All @@ -30,7 +31,7 @@ class ControllerTest extends SapphireTest
{
protected $usesDatabase = true;

public function setUp()
protected function setUp(): void
{
parent::setUp();

Expand All @@ -43,7 +44,7 @@ public function setUp()
TestAssetStore::activate('GraphQLController');
}

public function tearDown()
protected function tearDown(): void
{
TestAssetStore::reset();
parent::tearDown();
Expand Down Expand Up @@ -83,7 +84,7 @@ public function testIndexWithException()
$kernel = Injector::inst()->get(Kernel::class);
$kernel->setEnvironment(Kernel::LIVE);

/** @var Manager|PHPUnit_Framework_MockObject_MockBuilder $managerMock */
/** @var Manager|MockBuilder $managerMock */
$managerMock = $this->getMockBuilder(Manager::class)
->setMethods(['query'])
->getMock();
Expand All @@ -103,7 +104,7 @@ public function testIndexWithException()

public function testIndexWithExceptionIncludesTraceInDevMode()
{
/** @var Manager|PHPUnit_Framework_MockObject_MockBuilder $managerMock */
/** @var Manager|MockBuilder $managerMock */
$managerMock = $this->getMockBuilder(Manager::class)
->setMethods(['query'])
->getMock();
Expand Down Expand Up @@ -148,9 +149,12 @@ public function testAuthenticationProtectionOnQueries($authenticator, $shouldFai
$manager->addQuery($this->getQuery($manager), 'myquery');

$response = $controller->index(new HTTPRequest('GET', ''));
$assertion = ($shouldFail) ? 'assertContains' : 'assertNotContains';
// See Fake\BrutalAuthenticatorFake::authenticate for failure message
$this->{$assertion}('Never!', $response->getBody());
if ($shouldFail) {
Assert::assertStringContainsString('Never!', $response->getBody());
} else {
Assert::assertStringNotContainsString('Never!', $response->getBody());
}
}

/**
Expand All @@ -170,11 +174,9 @@ public function authenticatorProvider()
];
}

/**
* @expectedException \SilverStripe\Control\HTTPResponse_Exception
*/
public function testAddCorsHeadersOriginDisallowed()
{
$this->expectException(HTTPResponse_Exception::class);
Config::modify()->set(Controller::class, 'cors', [
'Enabled' => true,
'Allow-Origin' => null,
Expand Down Expand Up @@ -394,7 +396,7 @@ public function testCorsOverride()
public function testTypeCaching()
{
$expectedSchemaPath = TestAssetStore::base_path() . '/testSchema.types.graphql';
$this->assertFileNotExists($expectedSchemaPath, 'Schema is not automatically cached');
$this->assertFileDoesNotExist($expectedSchemaPath, 'Schema is not automatically cached');

Config::modify()->set(Controller::class, 'cache_types_in_filesystem', true);
$controller = Controller::create(new Manager('testSchema'));
Expand All @@ -410,7 +412,7 @@ public function testTypeCaching()
Controller::create(new Manager('testSchema'))->processTypeCaching();

// Static cache should be removed when caching is disabled
$this->assertFileNotExists($expectedSchemaPath, 'Schema is not cached');
$this->assertFileDoesNotExist($expectedSchemaPath, 'Schema is not cached');
}

public function testIntrospectionProvider()
Expand Down Expand Up @@ -562,7 +564,7 @@ protected function assertQueryError(Controller $controller, HTTPRequest $request
$data = json_decode($controller->handleRequest($request)->getBody(), true);
$this->assertArrayHasKey('errors', $data);
$this->assertCount(1, $data['errors']);
$this->assertRegExp($regExp, $data['errors'][0]['message']);
$this->assertMatchesRegularExpression($regExp, $data['errors'][0]['message']);
}

protected function assertQuerySuccess(Controller $controller, HTTPRequest $request, $operation)
Expand Down Expand Up @@ -657,7 +659,7 @@ protected function getQuery(Manager $manager)
}

/**
* @return \PHPUnit_Framework_MockObject_MockObject
* @return \MockObject
*/
protected function getStaticSchemaMock()
{
Expand Down
14 changes: 7 additions & 7 deletions tests/ManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
class ManagerTest extends SapphireTest
{

protected function setUp()
protected function setUp(): void
{
parent::setUp();
/** @var IdentityStore $store */
Expand Down Expand Up @@ -135,18 +135,18 @@ public function testSchemaKey()
$manager->setSchemaKey('test');
$this->assertEquals('test', $manager->getSchemaKey());

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('/must be a string/');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/must be a string/');
$manager->setSchemaKey(['test']);
$this->assertEquals('test', $manager->getSchemaKey());

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('/cannnot be empty/');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/cannnot be empty/');
$manager->setSchemaKey('');
$this->assertEquals('test', $manager->getSchemaKey());

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('/alphanumeric/');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/alphanumeric/');
$manager->setSchemaKey('completely % invalid #key');
$this->assertEquals('test', $manager->getSchemaKey());
}
Expand Down
4 changes: 2 additions & 2 deletions tests/Middleware/CSRFMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function testItDoesntDoAnythingIfNotAMutation()
public function testItThrowsIfNoTokenIsProvided()
{
$this->expectException(Exception::class);
$this->expectExceptionMessageRegExp('/must provide a CSRF token/');
$this->expectExceptionMessageMatches('/must provide a CSRF token/');
$result = $this->simulateMiddlewareProcess(
new CSRFMiddleware(),
' mutation someMutation { tester }'
Expand Down Expand Up @@ -69,7 +69,7 @@ public function testItThrowsIfNoTokenIsProvided()
public function testItThrowsIfTokenIsInvalid()
{
$this->expectException(Exception::class);
$this->expectExceptionMessageRegExp('/Invalid CSRF token/');
$this->expectExceptionMessageMatches('/Invalid CSRF token/');
$result = $this->simulateMiddlewareProcess(
new CSRFMiddleware(),
' mutation someMutation { tester }',
Expand Down
4 changes: 2 additions & 2 deletions tests/Middleware/HTTPMethodMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function testItDoesntDoAnythingIfNotAMutation()
public function testItThrowsIfNotPOSTorGET()
{
$this->expectException(Exception::class);
$this->expectExceptionMessageRegExp('/must be POST or GET/');
$this->expectExceptionMessageMatches('/must be POST or GET/');
$result = $this->simulateMiddlewareProcess(
new HTTPMethodMiddleware(),
' query someQuery { tester }',
Expand All @@ -36,7 +36,7 @@ public function testItThrowsIfNotPOSTorGET()
public function testItThrowsIfMutationIsNotPOST()
{
$this->expectException(Exception::class);
$this->expectExceptionMessageRegExp('/Mutations must use the POST/');
$this->expectExceptionMessageMatches('/Mutations must use the POST/');
$result = $this->simulateMiddlewareProcess(
new HTTPMethodMiddleware(),
' mutation someMutation { tester }',
Expand Down
2 changes: 1 addition & 1 deletion tests/Middleware/MiddlewareProcessTestBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ abstract class MiddlewareProcessTestBase extends SapphireTest
*/
protected $defaultCallback;

protected function setUp()
protected function setUp(): void
{
parent::setUp();
$this->defaultCallback = function () {
Expand Down
2 changes: 1 addition & 1 deletion tests/PersistedQuery/HTTPProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public function testURLValidation()
{
/* @var HTTPProvider $provider */
$provider = Injector::inst()->create(HTTPProvider::class);
$this->expectException(InvalidArgumentException::class);
$this->expectException(\InvalidArgumentException::class);
$provider->setSchemaMapping(['default' => 'not a url']);
}

Expand Down
2 changes: 1 addition & 1 deletion tests/PersistedQuery/JSONStringProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function testJSONValidation()
{
/* @var PersistedQueryMappingProvider $provider */
$provider = new JSONStringProvider();
$this->expectException(InvalidArgumentException::class);
$this->expectException(\InvalidArgumentException::class);
$provider->setSchemaMapping(['default' => 'not a JSON string']);
}

Expand Down
2 changes: 1 addition & 1 deletion tests/QueryFilter/ReadTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class ReadTest extends SapphireTest
DataObjectFake::class,
];

protected function setUp()
protected function setUp(): void
{
parent::setUp();
// Make sure we're only testing the native features
Expand Down
2 changes: 1 addition & 1 deletion tests/Scaffolding/Scaffolders/ArgumentScaffolderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public function testNonInternalType()

public function testNonInternalTypeNoManager()
{
$this->expectException(InvalidArgumentException::class);
$this->expectException(\InvalidArgumentException::class);
$scaffolder = new ArgumentScaffolder('Test', 'MyType');
$scaffolder->toArray();
}
Expand Down
6 changes: 3 additions & 3 deletions tests/Scaffolding/Scaffolders/CRUD/CreateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class CreateTest extends SapphireTest
RestrictedDataObjectFake::class,
];

protected function setUp()
protected function setUp(): void
{
parent::setUp();
StaticSchema::inst()->setTypeNames([]);
Expand All @@ -35,7 +35,7 @@ protected function setUp()
}
}

protected function tearDown()
protected function tearDown(): void
{
StaticSchema::inst()->setTypeNames([]);
parent::tearDown();
Expand Down Expand Up @@ -142,7 +142,7 @@ public function testCreateOperationPermissionCheck()
$scaffold = $create->scaffold($manager);

$this->expectException(Exception::class);
$this->expectExceptionMessageRegExp('/Cannot create/');
$this->expectExceptionMessageMatches('/Cannot create/');

$scaffold['resolve'](
null,
Expand Down
4 changes: 2 additions & 2 deletions tests/Scaffolding/Scaffolders/CRUD/DeleteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class DeleteTest extends SapphireTest
RestrictedDataObjectFake::class,
];

protected function setUp()
protected function setUp(): void
{
parent::setUp();
// Make sure we're only testing the native features
Expand Down Expand Up @@ -124,7 +124,7 @@ public function testDeleteOperationPermissionCheck()
$scaffold = $delete->scaffold($manager);

$this->expectException(Exception::class);
$this->expectExceptionMessageRegExp('/Cannot delete/');
$this->expectExceptionMessageMatches('/Cannot delete/');

$scaffold['resolve'](
$restrictedDataobject,
Expand Down
2 changes: 1 addition & 1 deletion tests/Scaffolding/Scaffolders/CRUD/ReadOneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class ReadOneTest extends SapphireTest
RestrictedDataObjectFake::class,
];

protected function setUp()
protected function setUp(): void
{
parent::setUp();
// Make sure we're only testing the native features
Expand Down
2 changes: 1 addition & 1 deletion tests/Scaffolding/Scaffolders/CRUD/ReadTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ReadTest extends SapphireTest
RestrictedDataObjectFake::class,
];

protected function setUp()
protected function setUp(): void
{
parent::setUp();
// Make sure we're only testing the native features
Expand Down
Loading

0 comments on commit 930fa51

Please sign in to comment.