From e43d7f49a4edc3f4eb7b2dfb009fa330632a5071 Mon Sep 17 00:00:00 2001 From: Mikel Madariaga Date: Thu, 10 Aug 2023 19:00:19 +0200 Subject: [PATCH] Added matchers to allow value comparisons like: match:type(asd adasd asd) match:type(5) match:regexp(/\d{2}\/\d{2}\/\d{4}/) --- Behat/Context/JsonContext.php | 38 ++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/Behat/Context/JsonContext.php b/Behat/Context/JsonContext.php index 6d8c56e..ed84121 100644 --- a/Behat/Context/JsonContext.php +++ b/Behat/Context/JsonContext.php @@ -10,6 +10,7 @@ use Behatch\HttpCall\Request; use Behatch\Json\Json; use Behatch\Json\JsonInspector; +use http\Exception\RuntimeException; /** * Defines application features from the specific context. @@ -174,7 +175,19 @@ private function assertAlike($expected, $actual) return; } - if ($expected !== '~') { + $matchingRules = preg_match( + '/match:(\w+)\((.+)\)/', //'/match:(\w)\((\w)\)/', + $expected, + $matches + ); + + if ($matchingRules) { + [, $matcher, $value] = $matches; + $this->applyMatcher($matcher, $value, $actual); + + return; + + } elseif ($expected !== '~') { $this->assert( $expected === $actual, "The element '$actual' is not equal to '$expected'" @@ -190,4 +203,27 @@ private function assertAlike($expected, $actual) ); } } + + private function applyMatcher(string $matcher, $expected, $actual) + { + switch($matcher) { + case 'type': + $castedExpectedVariable = $expected; + settype($castedExpectedVariable, gettype($actual)); + + $this->assert( + $castedExpectedVariable === $actual, + "Type of element '$actual' is not equal to '$expected'" + ); + break; + case 'regexp': + $this->assert( + preg_match($expected, (string) $actual), + "The element '$actual' does not match regexp '$expected'" + ); + break; + default: + throw new RuntimeException('Unknown matcher type ' . $matcher); + } + } }