You are here

public function ServiceTestTrait::assertIterator in Purge 8.3

Assert that a \Iterator implementation functions as expected.

Parameters

string[] $expected_plugins: Plugins that can be expected to be returned by the iterator.

null|string $type: Check if the service is also of the given type (class name).

4 calls to ServiceTestTrait::assertIterator()
ServiceTest::testIteration in tests/src/Kernel/Processor/ServiceTest.php
Tests the \Iterator implementation.
ServiceTest::testIteration in tests/src/Kernel/TagsHeader/ServiceTest.php
Tests the \Iterator implementation.
ServiceTest::testIteration in tests/src/Kernel/Queuer/ServiceTest.php
Tests the \Iterator implementation.
ServiceTest::testIteration in tests/src/Kernel/DiagnosticCheck/ServiceTest.php
Tests the \Iterator implementation.

File

tests/src/Traits/ServiceTestTrait.php, line 78

Class

ServiceTestTrait
Properties and methods for services.yml exposed classes.

Namespace

Drupal\Tests\purge\Traits

Code

public function assertIterator(array $expected_plugins, $type = NULL) : void {

  // Assert that the service implements PHP's \Iterator interface.
  $this
    ->assertTrue($this->service instanceof \Iterator);

  // Iterate the service, count all items and typecheck the instances.
  $items = 0;
  foreach ($this->service as $instance) {
    if ($type) {
      $this
        ->assertTrue($instance instanceof $type, var_export($instance
        ->getPluginId(), TRUE));
    }
    $items++;
  }
  $this
    ->assertEquals(count($expected_plugins), $items);

  // Assert the default states for ::current(), ::valid() and rewind().
  $this
    ->assertFalse($this->service
    ->current(), '::current returns FALSE');
  $this
    ->assertFalse($this->service
    ->valid(), '::valid returns FALSE');
  $this
    ->assertNull($this->service
    ->rewind(), '::rewind returns NULL');

  // Assert that hand iteration works as expected.
  $count_expected_plugins = count($expected_plugins);
  for ($i = 0; $i < $count_expected_plugins; $i++) {
    $this
      ->assertTrue($this->service
      ->valid(), '$this->service->valid() returns TRUE');
    $k = array_search($this->service
      ->current()
      ->getPluginId(), $expected_plugins);
    $this
      ->assertTrue(is_int($k) && isset($expected_plugins[$k]), 'is_int($k) && isset($expected_plugins[$k]) returns TRUE');
    unset($expected_plugins[$k]);
    $this
      ->assertNull($this->service
      ->next(), '$this->service->next() returns NULL');
  }
  $this
    ->assertTrue(empty($expected_plugins));
}