diff --git a/tests/phpunit/integration/OATHUserRepositoryTest.php b/tests/phpunit/integration/OATHUserRepositoryTest.php new file mode 100644 index 00000000..ea6ed7ec --- /dev/null +++ b/tests/phpunit/integration/OATHUserRepositoryTest.php @@ -0,0 +1,106 @@ + + * @group Database + * @coversDefaultClass \MediaWiki\Extension\OATHAuth\OATHUserRepository + */ +class OATHUserRepositoryTest extends MediaWikiIntegrationTestCase { + /** + * @covers ::findByUser + * @covers ::createKey + * @covers ::remove + */ + public function testLookupCreateRemoveKey(): void { + $user = $this->getTestUser()->getUser(); + + $dbProvider = $this->createMock( IConnectionProvider::class ); + $dbProvider->method( 'getPrimaryDatabase' )->with( 'virtual-oathauth' )->willReturn( $this->db ); + $dbProvider->method( 'getReplicaDatabase' )->with( 'virtual-oathauth' )->willReturn( $this->db ); + + $moduleRegistry = OATHAuthServices::getInstance( $this->getServiceContainer() )->getModuleRegistry(); + $module = $moduleRegistry->getModuleByKey( 'totp' ); + + $lookup = $this->createMock( CentralIdLookup::class ); + $lookup->method( 'centralIdFromLocalUser' ) + ->with( $user ) + ->willReturn( 12345 ); + $lookupFactory = $this->createMock( CentralIdLookupFactory::class ); + $lookupFactory->method( 'getLookup' )->willReturn( $lookup ); + + $logger = $this->createMock( LoggerInterface::class ); + + $repository = new OATHUserRepository( + $dbProvider, + new EmptyBagOStuff(), + $moduleRegistry, + $lookupFactory, + $logger + ); + + $oathUser = $repository->findByUser( $user ); + $this->assertEquals( 12345, $oathUser->getCentralId() ); + $this->assertEquals( [], $oathUser->getKeys() ); + $this->assertNull( $oathUser->getModule() ); + + $key = $repository->createKey( + $oathUser, + $module, + TOTPKey::newFromRandom()->jsonSerialize(), + '127.0.0.1' + ); + + $this->assertNotEmpty( + $this->db->newSelectQueryBuilder() + ->select( '1' ) + ->from( 'oathauth_devices' ) + ->where( [ 'oad_user' => $oathUser->getCentralId() ] ) + ); + + $this->assertArrayEquals( [ $key ], $oathUser->getKeys() ); + $this->assertEquals( $module, $oathUser->getModule() ); + + // Test looking it up again from the database + $this->assertArrayEquals( [ $key ], $repository->findByUser( $user )->getKeys() ); + + $repository->remove( + $oathUser, + '127.0.0.1', + true + ); + + $this->assertEquals( [], $oathUser->getKeys() ); + $this->assertNull( $oathUser->getModule() ); + $this->assertEquals( [], $repository->findByUser( $user )->getKeys() ); + } +}