wiki.techinc.nl/tests/phpunit/includes/session/CsrfTokenSetTest.php
Daimona Eaytoy 485e47ff10 tests: Avoid database usage when possible
We would like to remove DB access in non-database PHPUnit tests. As a
first step, avoid database usage in tested code when possible. In
particular:
- In NameTableStoreFactory, avoid domain ID normalization if the
  provided ID is already false.
- In SpecialDoubleRedirects, do not acquire a DB connection until it's
  needed (which is just one place).
- Use editPage() in TitleDefTest instead of a DIY implementation, and
  add `@group Database` accordingly.
- Avoid parsing titles in ContentHandler tests that don't need to parse
  titles. Among the many dependencies of parsing titles is the interwiki
  lookup, which requires DB access.
- Also remove test cases that used the "Gadget" namespace; it doesn't
  exist in core, so these pages were actually in the mainspace.
- Mock the database in CategoriesRdfTest. The only two methods that use
  the database were already being mocked.
- Add `@group Database` to test classes that are intentionally using the
  Database, mainly via getTestUser().

Bug: T155147
Change-Id: I9385fe14cfeb6b7b7378cc322d510034c4ee0711
2023-07-31 00:46:13 +00:00

50 lines
1.8 KiB
PHP

<?php
namespace MediaWiki\Tests\Session;
use MediaWiki\Session\CsrfTokenSet;
use MediaWiki\Session\SessionManager;
use MediaWikiIntegrationTestCase;
use User;
use WebRequest;
/**
* @covers \MediaWiki\Session\CsrfTokenSet
* @package MediaWiki\Tests\Unit\Session
* @group Database
*/
class CsrfTokenSetTest extends MediaWikiIntegrationTestCase {
private function makeRequest( bool $userRegistered ): WebRequest {
$webRequest = new WebRequest();
$session1 = SessionManager::singleton()->getEmptySession( $webRequest );
$session1->setUser( $userRegistered ? $this->getTestUser()->getUser() : new User() );
return $webRequest;
}
public function testCSRFTokens_anon() {
$webRequest1 = $this->makeRequest( false );
$tokenRepo1 = new CsrfTokenSet( $webRequest1 );
$token = $tokenRepo1->getToken()->toString();
$webRequest2 = $this->makeRequest( false );
$tokenRepo2 = new CsrfTokenSet( $webRequest2 );
$this->assertTrue( $tokenRepo2->matchToken( $token ) );
$webRequest2->setVal( 'wpBlabla', $token );
$this->assertTrue( $tokenRepo2->matchTokenField( 'wpBlabla' ) );
}
public function testCSRFTokens_registered() {
$webRequest1 = $this->makeRequest( true );
$tokenRepo1 = new CsrfTokenSet( $webRequest1 );
$token = $tokenRepo1->getToken()->toString();
$this->assertTrue( $tokenRepo1->matchToken( $token ) );
$this->assertFalse( $tokenRepo1->matchTokenField( 'wpBlabla' ) );
$webRequest1->setVal( 'wpBlabla', $token );
$this->assertTrue( $tokenRepo1->matchTokenField( 'wpBlabla' ) );
$webRequest2 = $this->makeRequest( true );
$webRequest2->setVal( 'wpBlabla', $token );
$tokenRepo2 = new CsrfTokenSet( $webRequest2 );
$this->assertFalse( $tokenRepo2->matchTokenField( 'wpBlabla' ) );
$this->assertFalse( $tokenRepo2->matchToken( $token ) );
}
}