You are here

public function EncryptServiceTest::testEncryptDecrypt in Encrypt 8.3

Tests the encrypt & decrypt method.

@covers ::__construct @covers ::encrypt @covers ::decrypt @covers ::validate

@dataProvider encryptionDataProvider

File

tests/src/Unit/EncryptServiceTest.php, line 130

Class

EncryptServiceTest
Unit tests for EncryptService class.

Namespace

Drupal\Tests\encrypt\Unit

Code

public function testEncryptDecrypt($key, $valid_key) {

  // Set up expectations for Key.
  $this->key
    ->getKeyValue()
    ->willReturn($key);

  // This method can decrypt.
  $this->encryptionMethod
    ->canDecrypt()
    ->willReturn(TRUE);
  if ($valid_key) {

    // Set up expectations for encryption method.
    $this->encryptionMethod
      ->encrypt('text_to_encrypt', 'validkey')
      ->willReturn('encrypted_text');
    $this->encryptionMethod
      ->decrypt('text_to_decrypt', 'validkey')
      ->willReturn('decrypted_text');

    // Set up expectations for encryption profile.
    $this->encryptionProfile
      ->getEncryptionKey()
      ->willReturn($this->key);
    $this->encryptionProfile
      ->getEncryptionMethod()
      ->willReturn($this->encryptionMethod);
    $this->encryptionProfile
      ->validate('text_to_encrypt')
      ->willReturn([]);
    $this->encryptionProfile
      ->validate('text_to_decrypt')
      ->willReturn([]);
  }
  else {

    // Set up expectations for encryption profile.
    $this->encryptionProfile
      ->getEncryptionKey()
      ->shouldNotBeCalled();
    $this->encryptionProfile
      ->getEncryptionMethod()
      ->shouldNotBeCalled();
    $this->encryptionProfile
      ->validate('text_to_encrypt')
      ->willReturn([
      'Validation',
    ]);
    $this->encryptionProfile
      ->validate('text_to_decrypt')
      ->willReturn([
      'Validation',
    ]);
    $this
      ->expectException('\\Drupal\\encrypt\\Exception\\EncryptException');
  }
  $service = new EncryptService($this->encryptManager
    ->reveal(), $this->keyRepository
    ->reveal(), $this
    ->getConfigFactoryStub($this->defaultConfig));
  $encrypted_text = $service
    ->encrypt("text_to_encrypt", $this->encryptionProfile
    ->reveal());
  $decrypted_text = $service
    ->decrypt("text_to_decrypt", $this->encryptionProfile
    ->reveal());
  if ($valid_key) {
    $this
      ->assertEquals("encrypted_text", $encrypted_text);
    $this
      ->assertEquals("decrypted_text", $decrypted_text);
  }
}