You are here

public function CouponCodeGeneratorTest::testCouponGenerator in Commerce Core 8.2

Tests the code generator.

@covers ::generateCodes

File

modules/promotion/tests/src/Kernel/CouponCodeGeneratorTest.php, line 112

Class

CouponCodeGeneratorTest
Tests the coupon code generator.

Namespace

Drupal\Tests\commerce_promotion\Kernel

Code

public function testCouponGenerator() {

  // Test numeric type pattern, length 10, 1 code.
  $pattern = new CouponCodePattern('numeric', '', '', 10);
  $result = $this->couponCodeGenerator
    ->generateCodes($pattern, 1);
  $this
    ->assertNotEmpty($result);
  $this
    ->assertTrue(ctype_digit($result[0]));
  $this
    ->assertEquals(strlen($result[0]), 10);

  // Test alphabetic type pattern, length 100, 10 codes.
  $pattern = new CouponCodePattern('alphabetic', '', '', 100);
  $result = $this->couponCodeGenerator
    ->generateCodes($pattern, 10);
  $this
    ->assertEquals(count($result), 10);
  $this
    ->assertTrue(ctype_alpha($result[0]));
  $this
    ->assertEquals(strlen($result[0]), 100);

  // Test alphanumeric type pattern, length 50, 25 codes.
  $pattern = new CouponCodePattern('alphanumeric', '', '', 50);
  $result = $this->couponCodeGenerator
    ->generateCodes($pattern, 25);
  $this
    ->assertEquals(count($result), 25);
  $this
    ->assertTrue(ctype_alnum($result[0]));
  $this
    ->assertEquals(strlen($result[0]), 50);

  // Test prefix and suffix options.
  $pattern = new CouponCodePattern('numeric', 'save', 'XX', 2);
  $result = $this->couponCodeGenerator
    ->generateCodes($pattern, 1);
  $this
    ->assertNotEmpty($result);
  $this
    ->assertEquals(substr($result[0], 0, 4), 'save');
  $this
    ->assertTrue(ctype_digit(substr($result[0], 4, 2)));
  $this
    ->assertEquals(substr($result[0], 6), 'XX');

  // Test coupon code conflict.
  $pattern = new CouponCodePattern('numeric', 'COUPON', '', 1);
  $result = $this->couponCodeGenerator
    ->generateCodes($pattern, 1);
  $this
    ->assertEmpty($result);
}