From f48d31f0d4238cdec2fa6fdc2c314c47735b70a0 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Wed, 2 Nov 2022 10:52:32 +0800 Subject: [PATCH] MDL-76169 behat: Normalise exception message in should (not) steps These steps have accepted a NodeElement instance as an argument for some time, but were trying to cast it to string when formulating exception messages, making it harder to debug and, in the case of the 'should see' step, not work at all. This patch introduces a new function to produce a consistent naming for them. --- lib/behat/classes/behat_session_trait.php | 16 ++++++++++++++++ lib/tests/behat/behat_general.php | 7 +++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/behat/classes/behat_session_trait.php b/lib/behat/classes/behat_session_trait.php index 4af590c97d8..4bb115163c7 100644 --- a/lib/behat/classes/behat_session_trait.php +++ b/lib/behat/classes/behat_session_trait.php @@ -224,6 +224,22 @@ trait behat_session_trait { ]; } + /** + * Get a description of the selector and locator to use in an exception message. + * + * @param string $selector The type of locator + * @param mixed $locator The locator text + * @return string + */ + protected function get_selector_description(string $selector, $locator): string { + if ($selector === 'NodeElement') { + $description = $locator->getText(); + return "'{$description}' {$selector}"; + } + + return "'{$locator}' {$selector}"; + } + /** * Send key presses straight to the currently active element. * diff --git a/lib/tests/behat/behat_general.php b/lib/tests/behat/behat_general.php index 4b0334a353c..c8a3e9fb6e9 100644 --- a/lib/tests/behat/behat_general.php +++ b/lib/tests/behat/behat_general.php @@ -1154,7 +1154,8 @@ EOF; $containernode = $this->find($containerselectortype, $containerelement); // Specific exception giving info about where can't we find the element. - $locatorexceptionmsg = "{$element} in the {$containerelement} {$containerselectortype}"; + $containerdescription = $this->get_selector_description($containerselectortype, $containerelement); + $locatorexceptionmsg = "{$element} not found in the {$containerdescription}}"; $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg); // Looks for the requested node inside the container node. @@ -1188,8 +1189,10 @@ EOF; } // The element was found and should not have been. Throw an exception. + $elementdescription = $this->get_selector_description($selectortype, $element); + $containerdescription = $this->get_selector_description($containerselectortype, $containerelement); throw new ExpectationException( - "The '{$element}' '{$selectortype}' exists in the '{$containerelement}' '{$containerselectortype}'", + "The {$elementdescription} exists in the {$containerdescription}", $this->getSession() ); }