Problem/Motivation

AssertLegacyTrait allowed us to use SimpleTest assertions in PHPUnit. Now SimpleTest has been removed, we should modernise all assertions.

This issue deals with \Drupal\KernelTests\AssertLegacyTrait::assert().

Proposed resolution

Replace \Drupal\KernelTests\AssertLegacyTrait::assert() with PHPUnit's assertTrue() or perhaps a more specific method in some cases.

Remaining tasks

Do the replacements.
Deprecate \Drupal\KernelTests\AssertLegacyTrait::assert() with trigger_error().

User interface changes

API changes

Data model changes

Release notes snippet

Comments

longwave created an issue. See original summary.

longwave’s picture

Status: Active » Needs review
StatusFileSize
new40.9 KB

First pass at this. Squeezed in a few bonus refactors where it makes sense, such as getting rid of return values (PHPUnit assertions do not return anything) and SimpleTest groups (PHPUnit does not support message groups either).

I have left alone Drupal\Tests\WebAssert as the assert() method there is unrelated, and also Drupal\KernelTests\AssertContentTrait as I am not convinced these methods are fully tested nor perhaps even used anywhere.

Deleted this entirely, as it wasn't even testing anything:

-        $this->assert(TRUE, new FormattableMarkup('View @view will be executed.', ['@view' => $view->storage->id()]));
martin107’s picture

Status: Needs review » Needs work

I have visually scanned this patch

All the conversions look good.... I found one minor flaw.

--- a/core/modules/migrate/tests/src/Kernel/MigrateTestBase.php
+++ b/core/modules/migrate/tests/src/Kernel/MigrateTestBase.php
@@ -205,7 +205,7 @@ public function display($message, $type = 'status') {
       $this->migrateMessages[$type][] = $message;
     }
     else {
-      $this->assert($type == 'status', $message, 'migrate');
+      $this->assertEquals('status', $type);
     }
   }

While I don't find the migrate message very helpful. There is no need to drop it.

In terms of the standard review ..

A) I agree with all the reasoning behind the need for this issue.
B) Looking at the test artefacts there are no additional errors.

longwave’s picture

Status: Needs work » Needs review
StatusFileSize
new40.91 KB
new553 bytes

Addressed #3.

Do you think $this->assertTrue(isset(...)) should be replaced with $this->assertNotEmpty(...)? Technically they are not quite the same (where the value is falsey) but I think for most cases in this patch at least it feels a bit clearer to use "not empty"?

martin107’s picture

Status: Needs review » Reviewed & tested by the community
$view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']);
-    $this->assert(isset($view_link), 'The message area contains a link to a contact form.');
+    $this->assertTrue(isset($view_link), 'The message area contains a link to a contact form.');

$view_link is FALSE if the query is malformed or errors occurred,

I think the isset() in combination with assertTrue() is perfectly readable justifiable code.

mondrake’s picture

+++ b/core/tests/Drupal/FunctionalTests/Bootstrap/UncaughtExceptionTest.php
@@ -285,7 +285,7 @@ public function testLoggerException() {
     $expected_line = 59;
     $expected_entry = "Failed to log error: Exception: Deforestation in Drupal\\error_service_test\\MonkeysInTheControlRoom->handle() (line ${expected_line} of ${expected_path})";
-    $this->assert(strpos($errors[0], $expected_entry) !== FALSE, 'Original error logged to the PHP error log when an exception is thrown by a logger');
+    $this->assertTrue(strpos($errors[0], $expected_entry) !== FALSE, 'Original error logged to the PHP error log when an exception is thrown by a logger');
 
     // The exception is expected. Do not interpret it as a test failure. Not

This can be an assertStringCointainsString.

Also we should deprecate the assert method, and add a deprecation test. Better postpone on #3114617: Properly deprecate methods in Drupal\FunctionalTests\AssertLegacyTrait and Drupal\KernelTests\AssertLegacyTrait, while still keeping deprecations silenced?

longwave’s picture

Status: Reviewed & tested by the community » Needs work

I think the deprecation can be done separately with no need to postpone here but the strpos in #6 is a good catch so back to needs work for that.

sja112’s picture

Status: Needs work » Needs review
Issue tags: +Needs reroll
StatusFileSize
new32.15 KB

Patch re-rolled. Includes some new changes. Change mentioned in #6 not required anymore.

sja112’s picture

StatusFileSize
new26.74 KB

Updated patch. Change in WebAssert.php file was not required.

tdnshah’s picture

Found a duplicate issue marked as child to this issues already has been resolved in #9

jungle’s picture

Thanks @sja112!

  1. +++ b/core/modules/views/tests/src/Functional/Handler/HandlerTest.php
    @@ -230,18 +230,13 @@ public function testHandlerWeights() {
    +    $this->assertTrue($expected == $handler->value, $message);
    

    use assertEquals()?

  2. +++ b/core/tests/Drupal/KernelTests/Core/Cache/GenericCacheBackendUnitTestBase.php
    @@ -311,10 +311,10 @@ public function testGetMultiple() {
    +    $this->assertTrue(isset($ret['test2']), "Existing cache id test2 is set.");
    +    $this->assertTrue(isset($ret['test3']), "Existing cache id test3 is set.");
    +    $this->assertTrue(isset($ret['test6']), "Existing cache id test6 is set.");
    +    $this->assertTrue(isset($ret['test7']), "Existing cache id test7 is set.");
    
    @@ -345,9 +345,9 @@ public function testGetMultiple() {
    +    $this->assertTrue(isset($ret['test2']), "Existing cache id test2 is set");
    +    $this->assertTrue(isset($ret['test7']), "Existing cache id test7 is set");
    +    $this->assertTrue(isset($ret['test19']), "Added cache id test19 is set");
    

    use assertArrayHasKey()?

sja112’s picture

Assigned: Unassigned » sja112
sja112’s picture

Assigned: sja112 » Unassigned
jungle’s picture

Issue tags: +Deprecated assertions

Adding the "Deprecated assertions" tag to add this into the kanban board https://contribkanban.com/board/Deprecatedassertions

mondrake’s picture

StatusFileSize
new1.58 KB

Let's see where it fails, now.

mondrake’s picture

StatusFileSize
new28.32 KB

#9 + #17

mondrake’s picture

Assigned: Unassigned » mondrake
Status: Postponed » Active

On this.

mondrake’s picture

Title: Replace AssertLegacyTrait::assert() with assertTrue() or better » Replace usages of deprecated AssertLegacyTrait::assert()
Assigned: mondrake » Unassigned
Priority: Normal » Major
Status: Active » Needs review
Issue tags: -Needs reroll +Needs followup
StatusFileSize
new38.39 KB

New patch, taking into the refactoring also discussions from #3131807-90: [meta] Replace assertions involving calls to isset() with more appropriate assertions onwards.

I noticed that in cases of constructs like

    $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'aggregator/sources/']);
    $this->assert(isset($view_link), 'The message area contains a link to a feed');

we are in fact failing to test appropriately: $this->xpath returns an empty array here, since the xpath selector is //div[@class="messages"] and in fact since the test was written the class changed to 'messages-list'. But an empty array is set as a variable, so the test passes anyway. I corrected by changing the selector to //div[@data-drupal-messages], and using the WebAssert::elementExists method. This led to nice findings. There are probably many more cases of this, bot oos here, needs follow up. Bumping to major because we are fixing a test mishmash here.

Removed deprecation silencer and added deprecation test.

Interdiff not relevant.

mondrake’s picture

StatusFileSize
new977 bytes
new38.4 KB

One more.

longwave’s picture

  1. +++ b/core/modules/aggregator/tests/src/Functional/AggregatorRenderingTest.php
    @@ -61,13 +61,17 @@ public function testBlockLinks() {
    +    $xpath = $this->assertSession()->buildXPathQuery('//a[@href = :href]', [
    +      ':href' => reset($items)->getLink(),
    +    ]);
    +    $this->assertSession()->elementExists('xpath', $xpath);
    

    $this->assertSession()->linkByHrefExists() instead?

  2. +++ b/core/modules/aggregator/tests/src/Functional/AggregatorRenderingTest.php
    @@ -61,13 +61,17 @@ public function testBlockLinks() {
    +    $xpath = $this->assertSession()->buildXPathQuery('//a[@href = :href]', [
    +      ':href' => $href,
    +    ]);
    +    $this->assertSession()->elementExists('xpath', $xpath);
    

    Same

  3. +++ b/core/modules/views/tests/src/Functional/SearchIntegrationTest.php
    @@ -146,12 +145,14 @@ public function testSearchIntegration() {
    +    $xpath = $this->assertSession()->buildXPathQuery('//a[normalize-space(text())=:label]', [
    +      ':label' => $label,
    +    ]);
    +    $this->assertSession()->elementsCount('xpath', $xpath, 1);
    

    $this->assertSession()->linkExists() instead?

anu.a_95’s picture

Apllied patch #21 successfully

Usages of deprecated AssertLegacyTrait::assert() is replaced with assertTrue(), assertSession() and some specific methods in specific cases etc..

Reviewed overall navigation of the Drupal instance and couldn't find any issue with the application of the patch. The code replacement didn't affect the functionality

anu.a_95’s picture

Status: Needs review » Reviewed & tested by the community
mondrake’s picture

Status: Reviewed & tested by the community » Needs work

Thank you for reviews, NW for #22.

mondrake’s picture

Status: Needs work » Needs review
StatusFileSize
new1.33 KB
new38.15 KB

#22:

1. done
2. done
3. not done - we need to ensure that exactly one link exists here, it's within an assert helper. linkExists would return multiple instances if there are.

longwave’s picture

Status: Needs review » Reviewed & tested by the community

Review points addressed, RTBC if tests pass.

mondrake’s picture

mondrake’s picture

StatusFileSize
new38.09 KB
new950 bytes

Rerolled.

  • catch committed 43fdb59 on 9.1.x
    Issue #3129002 by mondrake, longwave, sja112, martin107, jungle: Replace...
catch’s picture

Status: Reviewed & tested by the community » Fixed

Committed 43fdb59 and pushed to 9.1.x. Thanks!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.