From 2ff1827b6ea06968a189151092fa9df0435c4cfa Mon Sep 17 00:00:00 2001 From: Kunal Mehta Date: Sat, 12 Jan 2019 11:35:02 -0800 Subject: [PATCH] registration: Allow overriding attributes in tests ExtensionRegistry is a rather special singleton that can't use the normal MediaWikiServices reset due to its early initialization, so introduce a ->setAttributeForTest method to override attributes that are typically loaded from extension.json. Bug: T200013 Change-Id: I9e62a02ed2044c847e9ab2dcdfab094001f88986 --- includes/registration/ExtensionRegistry.php | 32 ++++++++++++++++++- .../registration/ExtensionRegistryTest.php | 26 +++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/includes/registration/ExtensionRegistry.php b/includes/registration/ExtensionRegistry.php index e462a0bc85..e3bd54289c 100644 --- a/includes/registration/ExtensionRegistry.php +++ b/includes/registration/ExtensionRegistry.php @@ -1,6 +1,7 @@ attributes[$name] ?? []; + return $this->testAttributes[$name] ?? + $this->attributes[$name] ?? []; + } + + /** + * Force override the value of an attribute during tests + * + * @param string $name Name of attribute to override + * @param array $value Value to set + * @return ScopedCallback to reset + * @since 1.33 + */ + public function setAttributeForTest( $name, array $value ) { + if ( !defined( 'MW_PHPUNIT_TEST' ) ) { + throw new RuntimeException( __METHOD__ . ' can only be used in tests' ); + } + if ( isset( $this->testAttributes[$name] ) ) { + throw new Exception( "The attribute '$name' has already been overridden" ); + } + $this->testAttributes[$name] = $value; + return new ScopedCallback( function () use ( $name ) { + unset( $this->testAttributes[$name] ); + } ); } /** diff --git a/tests/phpunit/includes/registration/ExtensionRegistryTest.php b/tests/phpunit/includes/registration/ExtensionRegistryTest.php index 1baa79c160..5de1b0cb4b 100644 --- a/tests/phpunit/includes/registration/ExtensionRegistryTest.php +++ b/tests/phpunit/includes/registration/ExtensionRegistryTest.php @@ -1,5 +1,7 @@ queue( "{$this->dataDir}/good.json" ); + $registry->loadFromQueue(); + // Sanity check that it worked + $this->assertSame( [ 'test' ], $registry->getAttribute( 'FooBarAttr' ) ); + $reset = $registry->setAttributeForTest( 'FooBarAttr', [ 'override' ] ); + // overridden properly + $this->assertSame( [ 'override' ], $registry->getAttribute( 'FooBarAttr' ) ); + ScopedCallback::consume( $reset ); + // reset properly + $this->assertSame( [ 'test' ], $registry->getAttribute( 'FooBarAttr' ) ); + } + + /** + * @expectedException Exception + * @expectedExceptionMessage The attribute 'foo' has already been overridden + */ + public function testSetAttributeForTestDuplicate() { + $registry = new ExtensionRegistry(); + $reset1 = $registry->setAttributeForTest( 'foo', [ 'val1' ] ); + $reset2 = $registry->setAttributeForTest( 'foo', [ 'val2' ] ); + } } -- 2.20.1