class ProviderRepositoryTest

Same name in this branch
  1. 11.x core/modules/media/tests/src/Functional/ProviderRepositoryTest.php \Drupal\Tests\media\Functional\ProviderRepositoryTest
  2. 11.x core/modules/media/tests/src/Kernel/ProviderRepositoryTest.php \Drupal\Tests\media\Kernel\ProviderRepositoryTest
Same name in other branches
  1. 9 core/modules/media/tests/src/Unit/ProviderRepositoryTest.php \Drupal\Tests\media\Unit\ProviderRepositoryTest
  2. 9 core/modules/media/tests/src/Kernel/ProviderRepositoryTest.php \Drupal\Tests\media\Kernel\ProviderRepositoryTest
  3. 9 core/modules/media/tests/src/Functional/ProviderRepositoryTest.php \Drupal\Tests\media\Functional\ProviderRepositoryTest
  4. 8.9.x core/modules/media/tests/src/Functional/ProviderRepositoryTest.php \Drupal\Tests\media\Functional\ProviderRepositoryTest
  5. 10 core/modules/media/tests/src/Unit/ProviderRepositoryTest.php \Drupal\Tests\media\Unit\ProviderRepositoryTest
  6. 10 core/modules/media/tests/src/Functional/ProviderRepositoryTest.php \Drupal\Tests\media\Functional\ProviderRepositoryTest
  7. 10 core/modules/media/tests/src/Kernel/ProviderRepositoryTest.php \Drupal\Tests\media\Kernel\ProviderRepositoryTest

@coversDefaultClass \Drupal\media\OEmbed\ProviderRepository

@group media

Hierarchy

Expanded class hierarchy of ProviderRepositoryTest

File

core/modules/media/tests/src/Unit/ProviderRepositoryTest.php, line 22

Namespace

Drupal\Tests\media\Unit
View source
class ProviderRepositoryTest extends UnitTestCase {
    
    /**
     * The provider repository under test.
     *
     * @var \Drupal\media\OEmbed\ProviderRepository
     */
    private $repository;
    
    /**
     * The HTTP client handler which will serve responses.
     *
     * @var \GuzzleHttp\Handler\MockHandler
     */
    private $responses;
    
    /**
     * The key-value store.
     *
     * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
     */
    private $keyValue;
    
    /**
     * The time that the current test began.
     *
     * @var int
     */
    private $currentTime;
    
    /**
     * The mocked logger channel.
     *
     * @var \Psr\Log\LoggerInterface|\Prophecy\Prophecy\ObjectProphecy
     */
    private $logger;
    
    /**
     * {@inheritdoc}
     */
    protected function setUp() : void {
        parent::setUp();
        $config_factory = $this->getConfigFactoryStub([
            'media.settings' => [
                'oembed_providers_url' => 'https://oembed.com/providers.json',
            ],
        ]);
        $key_value_factory = new KeyValueMemoryFactory();
        $this->keyValue = $key_value_factory->get('media');
        $this->currentTime = time();
        $time = $this->prophesize('\\Drupal\\Component\\Datetime\\TimeInterface');
        $time->getCurrentTime()
            ->willReturn($this->currentTime);
        $this->logger = $this->prophesize('\\Psr\\Log\\LoggerInterface');
        $logger_factory = $this->prophesize(LoggerChannelFactoryInterface::class);
        $logger_factory->get('media')
            ->willReturn($this->logger);
        $this->responses = new MockHandler();
        $client = new Client([
            'handler' => HandlerStack::create($this->responses),
        ]);
        $this->repository = new ProviderRepository($client, $config_factory, $time->reveal(), $key_value_factory, $logger_factory->reveal());
    }
    
    /**
     * Tests that a successful fetch stores the provider database in key-value.
     */
    public function testSuccessfulFetch() : void {
        $body = <<<END
[
  {
    "provider_name": "YouTube",
    "provider_url": "https:\\/\\/www.youtube.com\\/",
    "endpoints": [
      {
        "schemes": [
          "https:\\/\\/*.youtube.com\\/watch*",
          "https:\\/\\/*.youtube.com\\/v\\/*"
        ],
        "url": "https:\\/\\/www.youtube.com\\/oembed",
        "discovery": true
      }
    ]
  }
]
END;
        $response = new Response(200, [], $body);
        $this->responses
            ->append($response);
        $provider = $this->repository
            ->get('YouTube');
        $stored_data = [
            'data' => [
                'YouTube' => $provider,
            ],
            'expires' => $this->currentTime + 604800,
        ];
        $this->assertSame($stored_data, $this->keyValue
            ->get('oembed_providers'));
    }
    
    /**
     * Tests handling of invalid JSON when fetching the provider database.
     *
     * @param int $expiration_offset
     *   An offset to add to the current time to determine when the primed data,
     *   if any, expires.
     *
     * @dataProvider providerInvalidResponse
     */
    public function testInvalidResponse(int $expiration_offset) : void {
        $provider = $this->prophesize('\\Drupal\\media\\OEmbed\\Provider')
            ->reveal();
        // This stored data should be returned, irrespective of whether it's fresh.
        $this->keyValue
            ->set('oembed_providers', [
            'data' => [
                'YouTube' => $provider,
            ],
            'expires' => $this->currentTime + $expiration_offset,
        ]);
        $response = new Response(200, [], "This certainly isn't valid JSON.");
        $this->responses
            ->append($response, $response);
        $this->assertSame($provider, $this->repository
            ->get('YouTube'));
        // When there is no stored data, we should get an exception.
        $this->keyValue
            ->delete('oembed_providers');
        $this->expectException(ProviderException::class);
        $this->repository
            ->get('YouTube');
    }
    
    /**
     * Data provider for ::testInvalidResponse().
     *
     * @return array[]
     *   Sets of arguments to pass to the test method.
     */
    public static function providerInvalidResponse() : array {
        return [
            'expired' => [
                -86400,
            ],
            'fresh' => [
                86400,
            ],
        ];
    }
    
    /**
     * Tests handling of exceptions when fetching the provider database.
     */
    public function testRequestException() : void {
        $provider = $this->prophesize('\\Drupal\\media\\OEmbed\\Provider')
            ->reveal();
        // This data is expired (stale), but it should be returned anyway.
        $this->keyValue
            ->set('oembed_providers', [
            'data' => [
                'YouTube' => $provider,
            ],
            'expires' => $this->currentTime - 86400,
        ]);
        $response = new Response(503);
        $this->responses
            ->append($response, $response);
        $this->assertSame($provider, $this->repository
            ->get('YouTube'));
        // When there is no stored data, we should get an exception.
        $this->keyValue
            ->delete('oembed_providers');
        $this->expectException(ProviderException::class);
        $this->repository
            ->get('YouTube');
    }
    
    /**
     * Tests a successful fetch but with a single corrupt item.
     */
    public function testCorruptProviderIgnored() : void {
        $body = <<<END
[
  {
    "provider_name": "YouTube",
    "provider_url": "https:\\/\\/www.youtube.com\\/",
    "endpoints": [
      {
        "schemes": [
          "https:\\/\\/*.youtube.com\\/watch*",
          "https:\\/\\/*.youtube.com\\/v\\/*"
        ],
        "url": "https:\\/\\/www.youtube.com\\/oembed",
        "discovery": true
      }
    ]
  },
  {
    "provider_name": "Uncle Rico's football videos",
    "provider_url": "not a real url",
    "endpoints": []
  }
]
END;
        $response = new Response(200, [], $body);
        $this->responses
            ->append($response);
        // The corrupt provider should cause a warning to be logged.
        $this->logger
            ->warning("Provider Uncle Rico's football videos does not define a valid external URL.")
            ->shouldBeCalled();
        $youtube = $this->repository
            ->get('YouTube');
        // The corrupt provider should not be stored.
        $stored_data = [
            'data' => [
                'YouTube' => $youtube,
            ],
            'expires' => $this->currentTime + 604800,
        ];
        $this->assertSame($stored_data, $this->keyValue
            ->get('oembed_providers'));
        $this->expectException('InvalidArgumentException');
        $this->repository
            ->get("Uncle Rico's football videos");
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title
ExpectDeprecationTrait::expectDeprecation public function Adds an expected deprecation.
ExpectDeprecationTrait::getCallableName private static function Returns a callable as a string suitable for inclusion in a message.
ExpectDeprecationTrait::setUpErrorHandler public function Sets up the test error handler.
ExpectDeprecationTrait::tearDownErrorHandler public function Tears down the test error handler.
ProviderRepositoryTest::$currentTime private property The time that the current test began.
ProviderRepositoryTest::$keyValue private property The key-value store.
ProviderRepositoryTest::$logger private property The mocked logger channel.
ProviderRepositoryTest::$repository private property The provider repository under test.
ProviderRepositoryTest::$responses private property The HTTP client handler which will serve responses.
ProviderRepositoryTest::providerInvalidResponse public static function Data provider for ::testInvalidResponse().
ProviderRepositoryTest::setUp protected function Overrides UnitTestCase::setUp
ProviderRepositoryTest::testCorruptProviderIgnored public function Tests a successful fetch but with a single corrupt item.
ProviderRepositoryTest::testInvalidResponse public function Tests handling of invalid JSON when fetching the provider database.
ProviderRepositoryTest::testRequestException public function Tests handling of exceptions when fetching the provider database.
ProviderRepositoryTest::testSuccessfulFetch public function Tests that a successful fetch stores the provider database in key-value.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
UnitTestCase::$root protected property The app root.
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::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::setUpBeforeClass public static function

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