class StorageCopyTraitTest

Same name in other branches
  1. 8.9.x core/tests/Drupal/Tests/Core/Config/StorageCopyTraitTest.php \Drupal\Tests\Core\Config\StorageCopyTraitTest
  2. 10 core/tests/Drupal/Tests/Core/Config/StorageCopyTraitTest.php \Drupal\Tests\Core\Config\StorageCopyTraitTest
  3. 11.x core/tests/Drupal/Tests/Core/Config/StorageCopyTraitTest.php \Drupal\Tests\Core\Config\StorageCopyTraitTest

@coversDefaultClass \Drupal\Core\Config\StorageCopyTrait @group Config

Hierarchy

Expanded class hierarchy of StorageCopyTraitTest

File

core/tests/Drupal/Tests/Core/Config/StorageCopyTraitTest.php, line 18

Namespace

Drupal\Tests\Core\Config
View source
class StorageCopyTraitTest extends UnitTestCase {
    use StorageCopyTrait;
    
    /**
     * @covers ::replaceStorageContents
     *
     * @dataProvider providerTestReplaceStorageContents
     */
    public function testReplaceStorageContents($source_collections, $target_collections) {
        $source = new MemoryStorage();
        $target = new MemoryStorage();
        // Empty the storage should be the same.
        $this->assertEquals(self::toArray($source), self::toArray($target));
        // When the source is populated, they are not the same any more.
        $this->generateRandomData($source, $source_collections);
        $this->assertNotEquals(self::toArray($source), self::toArray($target));
        // When the target is filled with random data they are also not the same.
        $this->generateRandomData($target, $target_collections);
        $this->assertNotEquals(self::toArray($source), self::toArray($target));
        // Set the active collection to a random one on both source and target.
        if ($source_collections) {
            $collections = $source->getAllCollectionNames();
            $source = $source->createCollection($collections[array_rand($collections)]);
        }
        if ($target_collections) {
            $collections = $target->getAllCollectionNames();
            $target = $target->createCollection($collections[array_rand($collections)]);
        }
        $source_data = self::toArray($source);
        $source_name = $source->getCollectionName();
        // After copying they are the same, this asserts that items not present
        // in the source get removed from the target.
        self::replaceStorageContents($source, $target);
        $this->assertEquals($source_data, self::toArray($target));
        // Assert that the copy method did indeed not change the source.
        $this->assertEquals($source_data, self::toArray($source));
        // Assert that the active collection is the same as the original source.
        $this->assertEquals($source_name, $source->getCollectionName());
        $this->assertEquals($source_name, $target->getCollectionName());
    }
    
    /**
     * Provides data for testCheckRequirements().
     */
    public function providerTestReplaceStorageContents() {
        $data = [];
        $data[] = [
            TRUE,
            TRUE,
        ];
        $data[] = [
            TRUE,
            FALSE,
        ];
        $data[] = [
            FALSE,
            TRUE,
        ];
        $data[] = [
            FALSE,
            FALSE,
        ];
        return $data;
    }
    
    /**
     * Get the protected config data out of a MemoryStorage.
     *
     * @param \Drupal\Core\Config\MemoryStorage $storage
     *   The config storage to extract the data from.
     *
     * @return array
     */
    protected static function toArray(MemoryStorage $storage) {
        $reflection = new \ReflectionObject($storage);
        $property = $reflection->getProperty('config');
        $property->setAccessible(TRUE);
        return $property->getValue($storage)
            ->getArrayCopy();
    }
    
    /**
     * Generate random data in a config storage.
     *
     * @param \Drupal\Core\Config\StorageInterface $storage
     *   The storage to populate with random data.
     * @param bool $collections
     *   Add random collections or not.
     */
    protected function generateRandomData(StorageInterface $storage, $collections = TRUE) {
        $generator = $this->getRandomGenerator();
        for ($i = 0; $i < rand(2, 10); $i++) {
            $storage->write($this->randomMachineName(), (array) $generator->object());
        }
        if ($collections) {
            for ($i = 0; $i < rand(1, 5); $i++) {
                $collection = $storage->createCollection($this->randomMachineName());
                for ($i = 0; $i < rand(2, 10); $i++) {
                    $collection->write($this->randomMachineName(), (array) $generator->object());
                }
            }
        }
    }
    
    /**
     * Tests replaceStorageContents() with config with an invalid configuration.
     *
     * @covers ::replaceStorageContents
     */
    public function testWithInvalidConfiguration() {
        $source = new TestStorage();
        $this->generateRandomData($source);
        // Get a name from the source config storage and set the config value to
        // false. It mimics a config storage read return value when that config
        // storage has an invalid configuration.
        $names = $source->listAll();
        $test_name = reset($names);
        $source->setValue($test_name, FALSE);
        $logger_factory = $this->prophesize(LoggerChannelFactoryInterface::class);
        $container = new ContainerBuilder();
        $container->set('logger.factory', $logger_factory->reveal());
        \Drupal::setContainer($container);
        // Reading a config storage with an invalid configuration logs a notice.
        $channel = $this->prophesize(LoggerChannelInterface::class);
        $logger_factory->get('config')
            ->willReturn($channel->reveal());
        $channel->notice('Missing required data for configuration: %config', Argument::withEntry('%config', $test_name))
            ->shouldBeCalled();
        // Copy the config from the source storage to the target storage.
        $target = new TestStorage();
        self::replaceStorageContents($source, $target);
        // Test that all configuration is copied correctly and that the value of the
        // config with the invalid configuration has not been copied to the target
        // storage.
        foreach ($names as $name) {
            if ($name === $test_name) {
                $this->assertFalse($source->read($name));
                $this->assertFalse($target->exists($name));
            }
            else {
                $this->assertEquals($source->read($name), $target->read($name));
            }
        }
        // Test that the invalid configuration's name is in the source config
        // storage, but not the target config storage. This ensures that it was not
        // copied.
        $this->assertContains($test_name, $source->listAll());
        $this->assertNotContains($test_name, $target->listAll());
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overrides
PhpUnitWarnings::$deprecationWarnings private static property Deprecation warnings from PHPUnit to raise with @trigger_error().
PhpUnitWarnings::addWarning public function Converts PHPUnit deprecation warnings to E_USER_DEPRECATED.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
StorageCopyTraitTest::generateRandomData protected function Generate random data in a config storage.
StorageCopyTraitTest::providerTestReplaceStorageContents public function Provides data for testCheckRequirements().
StorageCopyTraitTest::testReplaceStorageContents public function @covers ::replaceStorageContents
StorageCopyTraitTest::testWithInvalidConfiguration public function Tests replaceStorageContents() with config with an invalid configuration.
StorageCopyTraitTest::toArray protected static function Get the protected config data out of a MemoryStorage.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals Deprecated protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.
UnitTestCase::setUp protected function 338
UnitTestCase::setUpBeforeClass public static function

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.