Problem/Motivation
When writing a test site setup script for Nightwatch that implements \Drupal\TestSite\TestSetupInterface
, it is desirable to use traits such as \Drupal\Tests\user\Traits\UserCreationTrait
to automate environment setup tasks (like user creation) in PHP rather than through the UI, to improve the speed and robustness of tests.
Currently, this is not possible because:
UserCreationTrait
and similar traits in Drupal core require the test class to also extend or implement \PHPUnit\Framework\Assert
.
- If the class both implements
TestSetupInterface
and extends \PHPUnit\Framework\Assert
, then the sanity check in \Drupal\TestSite\Commands\TestSiteInstallCommand::getSetupClass()
fails. It checks the interface implementation on the wrong class, leading to a false negative and preventing the setup script from being used as intended.
Steps to reproduce
- Create a Nightwatch site setup PHP file where your class implements
TestSetupInterface
and uses UserCreationTrait
.
- Attempt to execute the setup command via the Nightwatch CLI.
- Observe that the command fails with an error, even if the class implements the required interface, due to the interface check happening on the wrong class.
Relevant code
The problematic logic is in TestSiteInstallCommand::getSetupClass()
:
protected function getSetupClass($file) {
// ...
$class = array_pop($new_classes);
if (!is_subclass_of($class, TestSetupInterface::class) && !is_subclass_of($class, TestPreinstallInterface::class)) {
throw new \InvalidArgumentException("The class $class contained in $file needs to implement \Drupal\TestSite\TestSetupInterface or \Drupal\TestSite\TestPreinstallInterface");
}
return $class;
}
Currently, it uses array_pop($new_classes)
, so the last declared class in the file is picked, which may be the wrong one when traits or other supporting classes are present.
Proposed resolution
Change from:
$class = array_pop($new_classes);
To:
$class = array_shift($new_classes);
This would reliably select the main declared class (usually the first), ensuring interface checks operate as expected. This makes it possible to use traits like UserCreationTrait
in setup scripts, enabling more efficient PHP-based environment setup.
Desired outcome
- It becomes possible to use user and content creation traits in test setup scripts for Nightwatch and similar tools.
- Avoids unnecessary UI-based setup, leading to faster, more reliable tests.
Additional information
- This problem affects developers who want to leverage existing test traits in Drupal's core while setting up database state programmatically, and not through slow web-based UI automation.
- Fixing this will simplify and speed up end-to-end and functional test suites.