You are here

public function LibraryPolicyBuilderTest::testLibraryWithSources in Content-Security-Policy 8

Test that a library's external sources are discovered.

@covers ::getSources @covers ::getExtensionSources @covers ::getLibrarySources @covers ::getHostFromUri

File

tests/src/Unit/LibraryPolicyBuilderTest.php, line 110

Class

LibraryPolicyBuilderTest
@coversDefaultClass \Drupal\csp\LibraryPolicyBuilder @group csp

Namespace

Drupal\Tests\csp\Unit

Code

public function testLibraryWithSources() {
  $this->moduleHandler
    ->expects($this
    ->any())
    ->method('getModuleList')
    ->willReturn([]);
  $this->themeHandler
    ->expects($this
    ->any())
    ->method('listInfo')
    ->willReturn([
    'stark' => (object) [
      'name' => 'stark',
    ],
  ]);
  $extensionMap = [
    [
      'core',
      [],
    ],
    [
      'stark',
      [
        'test' => [],
      ],
    ],
  ];
  $this->libraryDiscovery
    ->expects($this
    ->any())
    ->method('getLibrariesByExtension')
    ->willReturnMap($extensionMap);

  // Test a few behaviours:
  // - local files are ignored.
  // - script domains are sorted.
  // - duplicate style domains are filtered.
  $libraryInfo = [
    'js' => [
      [
        'type' => 'file',
        'data' => 'js/script.js',
      ],
      [
        'type' => 'external',
        'data' => 'http://js.example.org/js/script.js',
      ],
      [
        'type' => 'external',
        'data' => 'http://js.example.com/js/script.js',
      ],
    ],
    'css' => [
      [
        'type' => 'external',
        'data' => 'http://css.example.com/css/style1.css',
      ],
      [
        'type' => 'external',
        'data' => 'http://css.example.com/css/style2.css',
      ],
    ],
  ];
  $this->libraryDiscovery
    ->expects($this
    ->atLeastOnce())
    ->method('getLibraryByName')
    ->with('stark', 'test')
    ->willReturn($libraryInfo);
  $libraryPolicy = new LibraryPolicyBuilder($this->cache, $this->moduleHandler, $this->themeHandler, $this->libraryDiscovery);
  $this
    ->assertEquals([
    'script-src' => [
      'js.example.com',
      'js.example.org',
    ],
    'script-src-elem' => [
      'js.example.com',
      'js.example.org',
    ],
    'style-src' => [
      'css.example.com',
    ],
    'style-src-elem' => [
      'css.example.com',
    ],
  ], $libraryPolicy
    ->getSources());
}