From 14f128be3dd3de8b8b432c6515b35fadfa178ac9 Mon Sep 17 00:00:00 2001 From: Chris Dent Date: Sat, 2 Mar 2024 15:02:37 +0000 Subject: [PATCH] Add support for regex in response_strings Very similar to what is used for headers. Fixes #326 --- gabbi/handlers/core.py | 16 +++++++++++-- gabbi/tests/gabbits_intercept/regex.yaml | 29 +++++++++++++++++++++++- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/gabbi/handlers/core.py b/gabbi/handlers/core.py index 97a1d87..6dfcc3d 100644 --- a/gabbi/handlers/core.py +++ b/gabbi/handlers/core.py @@ -22,8 +22,20 @@ class StringResponseHandler(base.ResponseHandler): test_key_value = [] def action(self, test, expected, value=None): - expected = test.replace_template(expected) - test.assert_in_or_print_output(expected, test.output) + is_regex = (expected.startswith('/') and + expected.endswith('/') and + len(expected) > 1) + expected = test.replace_template(expected, escape_regex=is_regex) + + if is_regex: + # Trim off / + expected = expected[1:-1] + test.assertRegex( + test.output, expected, + 'Expect resonse body %s to match /%s/' % + (test.output, expected)) + else: + test.assert_in_or_print_output(expected, test.output) class ForbiddenHeadersResponseHandler(base.ResponseHandler): diff --git a/gabbi/tests/gabbits_intercept/regex.yaml b/gabbi/tests/gabbits_intercept/regex.yaml index 9a0c055..1c01c63 100644 --- a/gabbi/tests/gabbits_intercept/regex.yaml +++ b/gabbi/tests/gabbits_intercept/regex.yaml @@ -1,4 +1,4 @@ -# Confirm regex handling in response and json path headers +# Confirm regex handling in response headers, strings and json path handlers tests: - name: regex header test url: /cow?alpha=1 @@ -19,3 +19,30 @@ tests: $.alpha: /ow$/ $.beta: /(?!cow).*/ $.gamma: /\d+/ + +- name: regex string test json + PUT: /cow + request_headers: + content-type: application/json + data: + alpha: cow + beta: pig + gamma: 1 + response_strings: + - '/"alpha": "cow",/' + +- name: regex string test multiline + GET: /presenter + response_strings: + - '/Hello World/' + - '/dolor sit/' + +- name: regex string test splat + GET: /presenter + response_strings: + - '/dolor.*amet/' + +- name: regex string test mix + GET: /presenter + response_strings: + - '/[Hh]el{2}o [Ww]orld/'