class ValidationResultTest

@coversDefaultClass \Drupal\package_manager\ValidationResult
@group package_manager @internal

Hierarchy

Expanded class hierarchy of ValidationResultTest

File

core/modules/package_manager/tests/src/Unit/ValidationResultTest.php, line 17

Namespace

Drupal\Tests\package_manager\Unit
View source
class ValidationResultTest extends UnitTestCase {
  
  /**
   * @covers ::createWarning
   *
   * @dataProvider providerValidConstructorArguments
   */
  public function testCreateWarningResult(array $messages, ?string $summary) : void {
    // phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString, DrupalPractice.Objects.GlobalFunction
    $summary = $summary ? t($summary) : NULL;
    $result = ValidationResult::createWarning($messages, $summary);
    $this->assertResultValid($result, $messages, $summary, RequirementSeverity::Warning->value);
  }
  
  /**
   * @covers ::getOverallSeverity
   */
  public function testOverallSeverity() : void {
    // An error and a warning should be counted as an error.
    $results = [
      // phpcs:disable DrupalPractice.Objects.GlobalFunction
ValidationResult::createError([
        t('Boo!'),
      ]),
      ValidationResult::createWarning([
        t('Moo!'),
      ]),
    ];
    $this->assertSame(RequirementSeverity::Error->value, ValidationResult::getOverallSeverity($results));
    // If there are no results, but no errors, the results should be counted as
    // a warning.
    array_shift($results);
    $this->assertSame(RequirementSeverity::Warning->value, ValidationResult::getOverallSeverity($results));
    // If there are just plain no results, we should get
    // RequirementSeverity::OK.
    array_shift($results);
    $this->assertSame(RequirementSeverity::OK->value, ValidationResult::getOverallSeverity($results));
  }
  
  /**
   * @covers ::createError
   *
   * @dataProvider providerValidConstructorArguments
   */
  public function testCreateErrorResult(array $messages, ?string $summary) : void {
    // phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString, DrupalPractice.Objects.GlobalFunction
    $summary = $summary ? t($summary) : NULL;
    $result = ValidationResult::createError($messages, $summary);
    $this->assertResultValid($result, $messages, $summary, RequirementSeverity::Error->value);
  }
  
  /**
   * @covers ::createWarning
   *
   * @param string[] $messages
   *   The warning messages of the validation result.
   * @param string $expected_exception_message
   *   The expected exception message.
   *
   * @dataProvider providerCreateExceptions
   */
  public function testCreateWarningResultException(array $messages, string $expected_exception_message) : void {
    $this->expectException(\InvalidArgumentException::class);
    $this->expectExceptionMessage($expected_exception_message);
    ValidationResult::createWarning($messages, NULL);
  }
  
  /**
   * @covers ::createError
   *
   * @param string[] $messages
   *   The error messages of the validation result.
   * @param string $expected_exception_message
   *   The expected exception message.
   *
   * @dataProvider providerCreateExceptions
   */
  public function testCreateErrorResultException(array $messages, string $expected_exception_message) : void {
    $this->expectException(\InvalidArgumentException::class);
    $this->expectExceptionMessage($expected_exception_message);
    ValidationResult::createError($messages, NULL);
  }
  
  /**
   * Tests that the messages are asserted to be translatable.
   *
   * @testWith ["createError"]
   *   ["createWarning"]
   */
  public function testMessagesMustBeTranslatable(string $method) : void {
    // When creating an error from a throwable, the message does not need to be
    // translatable.
    ValidationResult::createErrorFromThrowable(new \Exception('Burn it down.'));
    $this->expectException(\AssertionError::class);
    $this->expectExceptionMessageMatches('/instanceof TranslatableMarkup/');
    ValidationResult::$method([
      'Not translatable!',
    ]);
  }
  
  /**
   * Data provider for test methods that test create exceptions.
   *
   * @return array[]
   *   The test cases.
   */
  public static function providerCreateExceptions() : array {
    return [
      '2 messages, no summary' => [
        [
          t('Something is wrong'),
          t('Something else is also wrong'),
        ],
        'If more than one message is provided, a summary is required.',
      ],
      'no messages' => [
        [],
        'At least one message is required.',
      ],
    ];
  }
  
  /**
   * Data provider for testCreateWarningResult().
   *
   * @return mixed[]
   *   The test cases.
   */
  public static function providerValidConstructorArguments() : array {
    return [
      '1 message no summary' => [
        'messages' => [
          t('Something is wrong'),
        ],
        'summary' => NULL,
      ],
      '2 messages has summary' => [
        'messages' => [
          t('Something is wrong'),
          t('Something else is also wrong'),
        ],
        'summary' => 'This sums it up.',
      ],
    ];
  }
  
  /**
   * Asserts a check result is valid.
   *
   * @param \Drupal\package_manager\ValidationResult $result
   *   The validation result to check.
   * @param array $expected_messages
   *   The expected messages.
   * @param \Drupal\Core\StringTranslation\TranslatableMarkup|null $summary
   *   The expected summary or NULL if not summary is expected.
   * @param int $severity
   *   The severity.
   */
  protected function assertResultValid(ValidationResult $result, array $expected_messages, ?TranslatableMarkup $summary, int $severity) : void {
    $this->assertSame($expected_messages, $result->messages);
    if ($summary === NULL) {
      $this->assertNull($result->summary);
    }
    else {
      $this->assertSame($summary->getUntranslatedString(), $result->summary
        ->getUntranslatedString());
    }
    $this->assertSame($severity, $result->severity);
  }

}

Members

Title Sort descending Modifiers Object type Summary Overrides
ExpectDeprecationTrait::expectDeprecation public function Adds an expected deprecation.
ExpectDeprecationTrait::setUpErrorHandler public function Sets up the test error handler.
ExpectDeprecationTrait::tearDownErrorHandler public function Tears down the test error handler.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
UnitTestCase::$root protected property The app root.
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::setDebugDumpHandler public static function Registers the dumper CLI handler when the DebugDump extension is enabled.
UnitTestCase::setUp protected function 375
UnitTestCase::setupMockIterator protected function Set up a traversable class mock to return specific items when iterated.
ValidationResultTest::assertResultValid protected function Asserts a check result is valid.
ValidationResultTest::providerCreateExceptions public static function Data provider for test methods that test create exceptions.
ValidationResultTest::providerValidConstructorArguments public static function Data provider for testCreateWarningResult().
ValidationResultTest::testCreateErrorResult public function @covers ::createError[[api-linebreak]]
ValidationResultTest::testCreateErrorResultException public function @covers ::createError[[api-linebreak]]
ValidationResultTest::testCreateWarningResult public function @covers ::createWarning[[api-linebreak]]
ValidationResultTest::testCreateWarningResultException public function @covers ::createWarning[[api-linebreak]]
ValidationResultTest::testMessagesMustBeTranslatable public function Tests that the messages are asserted to be translatable.
ValidationResultTest::testOverallSeverity public function @covers ::getOverallSeverity[[api-linebreak]]

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.