From 426ea50861fcc49573c1ddbb66d68fad79429616 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 dc9082795ba..a9c5f317f89 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 a12c5deaab0..0633b21dc00 100644 --- a/lib/tests/behat/behat_general.php +++ b/lib/tests/behat/behat_general.php @@ -1225,7 +1225,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. @@ -1259,8 +1260,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() ); }