From f3e8fc10a99b7c62ae0b1f72fcc17cd1bb8a970c Mon Sep 17 00:00:00 2001 From: Son Date: Sat, 11 Dec 2021 19:38:22 +0100 Subject: [PATCH] use re instead of re2 if error "Argument 'pattern' has incorrect type (expected bytes, got PythonRePattern)" --- app/dashboard/views/domain_detail.py | 21 +++++++++++++++++---- tests/dashboard/test_domain_detail.py | 9 +++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 tests/dashboard/test_domain_detail.py diff --git a/app/dashboard/views/domain_detail.py b/app/dashboard/views/domain_detail.py index 6f47923f..3a831950 100644 --- a/app/dashboard/views/domain_detail.py +++ b/app/dashboard/views/domain_detail.py @@ -1,5 +1,7 @@ +import re + import arrow -import re2 as re +import re2 from flask import render_template, request, redirect, url_for, flash from flask_login import login_required, current_user from flask_wtf import FlaskForm @@ -501,9 +503,7 @@ def domain_detail_auto_create(custom_domain_id): auto_create_test_local = local for rule in custom_domain.auto_create_rules: - rule: AutoCreateRule - regex = re.compile(rule.regex) - if re.fullmatch(regex, local): + if regex_match(rule.regex, local): auto_create_test_result = ( f"{local}@{custom_domain.domain} passes rule #{rule.order}" ) @@ -519,3 +519,16 @@ def domain_detail_auto_create(custom_domain_id): ) return render_template("dashboard/domain_detail/auto-create.html", **locals()) + + +def regex_match(rule_regex: str, local): + regex = re2.compile(rule_regex) + try: + if re2.fullmatch(regex, local): + return True + except TypeError: # re2 bug "Argument 'pattern' has incorrect type (expected bytes, got PythonRePattern)" + LOG.w("use re instead of re2 for %s %s", rule_regex, local) + regex = re.compile(rule_regex) + if re.fullmatch(regex, local): + return True + return False diff --git a/tests/dashboard/test_domain_detail.py b/tests/dashboard/test_domain_detail.py new file mode 100644 index 00000000..280a96bd --- /dev/null +++ b/tests/dashboard/test_domain_detail.py @@ -0,0 +1,9 @@ +from app.dashboard.views.domain_detail import regex_match + + +def test_regex_match(flask_client): + assert regex_match("prefix.*", "prefix-abcd") + + # this generates re2 error "Argument 'pattern' has incorrect type (expected bytes, got PythonRePattern)" + # fallback to re + assert not regex_match("(?!abcd)s(\\.|-)?([a-z0-9]{4,6})", "abcd")