You are here

public function UniqueQueueTest::testQueueIsUnique in Queue Unique 8.2

Test that queues correctly add only unique data.

File

tests/src/Kernel/UniqueQueueTest.php, line 33

Class

UniqueQueueTest
Unique queue kernel test.

Namespace

Drupal\Tests\queue_unique\Kernel

Code

public function testQueueIsUnique() {
  $queue_factory = $this->container
    ->get('queue_unique.database');

  /* @var \Drupal\Core\Queue\QueueInterface $queue */
  $queue = $queue_factory
    ->get('queue');
  self::assertInstanceOf(UniqueDatabaseQueue::class, $queue);
  $examples = [
    1,
    '1',
    [
      'a' => 1,
      'b' => [
        'x',
      ],
    ],
    (object) [
      'a' => 1,
      'b' => [
        'x',
      ],
    ],
  ];
  $other_data = [
    'z',
  ];
  foreach ($examples as $data) {

    // Add an item to the empty unique queue.
    $item_id = $queue
      ->createItem($data);
    self::assertNotFalse($item_id);
    self::assertEquals(1, $queue
      ->numberOfItems());

    // When we try to add the item again we should not get an item id as the
    // item has not been readded and the number of items on the queue should
    // stay the same.
    $duplicate_id = $queue
      ->createItem($data);
    self::assertFalse($duplicate_id);
    self::assertEquals(1, $queue
      ->numberOfItems());

    // Claim and delete the item from the queue simulating an item being
    // processed.
    $item = $queue
      ->claimItem();
    $queue
      ->deleteItem($item);

    // With the original item being gone we should be able to re-add an item
    // with the same data.
    $item_id = $queue
      ->createItem($data);
    self::assertNotFalse($item_id);
    self::assertEquals(1, $queue
      ->numberOfItems());

    // Using some other data adds a new item.
    $item_id = $queue
      ->createItem($other_data);
    self::assertNotFalse($item_id);
    self::assertEquals(2, $queue
      ->numberOfItems());
    $queue
      ->deleteQueue();
  }

  // Every item in the examples has a different serialized string.
  foreach ($examples as $data) {
    $item_id = $queue
      ->createItem($data);
    self::assertNotFalse($item_id);
  }
  self::assertEquals(count($examples), $queue
    ->numberOfItems());
}