mediawiki-extensions-AbuseF.../tests/phpunit/AbuseFilterCreateAccountTestTrait.php
Matěj Suchánek 702d77e3ce Create real integration test for variables
For fixing bugs like T65632, T105325, or T264104, we will need
to update code in more than one place at once. To prevent
regressions, create an integration test which tests the whole
pipeline, from the request submission to variable evaluation.
Edits are simulated using action=edit API call because the hook
AbuseFilter uses is run from EditPage.

To increase confidence in test coverage, remove some annotations
from AbuseFilterConsequencesTest or make them less greedy.
Ideally, it would only test consequences.

This patch includes refactoring of AbuseFilterCreateAccountTestTrait
which now only inserts the user into the database if it really
should be created.
It also restores test coverage of some other classes.

Change-Id: I661f4e0e2bcac4770e499708fca4e4e153f31fed
2022-11-26 18:51:38 +01:00

62 lines
2 KiB
PHP

<?php
use MediaWiki\Extension\AbuseFilter\AbuseFilterPreAuthenticationProvider;
use MediaWiki\Extension\AbuseFilter\AbuseFilterServices;
use MediaWiki\MediaWikiServices;
use MediaWiki\Page\PageReferenceValue;
/**
* This trait can be used to create accounts in integration tests.
* NOTE: The implementing classes MUST extend MediaWikiIntegrationTestCase
* @todo This might be moved to MediaWikiIntegrationTestCase
*/
trait AbuseFilterCreateAccountTestTrait {
/**
* @param string $accountName
* @param bool $autocreate
* @param User|null $creator Defaults to the newly created user
* @return StatusValue
*/
protected function createAccount(
string $accountName,
bool $autocreate = false,
User $creator = null
): StatusValue {
$userFactory = MediaWikiServices::getInstance()->getUserFactory();
$user = $userFactory->newFromName( $accountName );
$creator = $creator ?? $user;
$provider = new AbuseFilterPreAuthenticationProvider(
AbuseFilterServices::getVariableGeneratorFactory(),
AbuseFilterServices::getFilterRunnerFactory(),
new NullStatsdDataFactory(),
$userFactory
);
if ( $autocreate ) {
$status = $provider->testUserForCreation( $user, $autocreate );
} else {
$status = $provider->testForAccountCreation( $user, $creator, [] );
}
if ( $status->isGood() ) {
// A creatable username must exist to be passed to $logEntry->setPerformer(),
// so create the account.
$user->addToDatabase();
// FIXME This is a bit hacky, but AuthManager doesn't expose any methods for logging
$subType = $autocreate ? 'autocreate' : 'create2';
$logEntry = new ManualLogEntry( 'newusers', $subType );
$logEntry->setPerformer( $creator );
$logEntry->setTarget( PageReferenceValue::localReference( NS_USER, $accountName ) );
$logEntry->setComment( 'Fooobarcomment' );
$logEntry->setParameters( [
'4::userid' => $user->getId(),
] );
$logid = $logEntry->insert();
$logEntry->publish( $logid );
$status->value = $logid;
}
return $status;
}
}