diff --git a/lizmap_server/get_legend_graphic.py b/lizmap_server/get_legend_graphic.py index e337be91..d011dd31 100644 --- a/lizmap_server/get_legend_graphic.py +++ b/lizmap_server/get_legend_graphic.py @@ -7,6 +7,7 @@ import json import re +from typing import Optional from qgis.core import Qgis, QgsDataSourceUri, QgsProject from qgis.server import QgsServerFilter @@ -21,6 +22,13 @@ class GetLegendGraphicFilter(QgsServerFilter): only works for single LAYER and STYLE(S) and json format. """ + FEATURE_COUNT_REGEXP = r"(.*) \[≈?(?:\d+|N/A)\]" + + @classmethod + def match_label_feature_count(cls, symbol_label: str) -> Optional[re.Match]: + """Regexp for extracting the feature count from the label. """ + return re.match(cls.FEATURE_COUNT_REGEXP, symbol_label) + @exception_handler def responseComplete(self): @@ -129,11 +137,13 @@ def responseComplete(self): symbol = symbols[idx] symbol_label = symbol['title'] if show_feature_count: - match_label = re.match(r"(.*) \[≈?(?:\d+|N/A)\]", symbol_label) + match_label = self.match_label_feature_count(symbol_label) if match_label: symbol_label = match_label.group(1) else: - logger.info("GetLegendGraphic JSON: symbol label does not match '(.*) \\[≈?(?:\\d+|N/A)\\]' '{}'".format(symbol['title'])) + logger.info( + "GetLegendGraphic JSON: symbol label does not match '{}' '{}'".format( + self.FEATURE_COUNT_REGEXP, symbol['title'])) try: category = categories[symbol_label] symbol['ruleKey'] = category['ruleKey'] diff --git a/test/test_legend.py b/test/test_legend.py index 5005f1c5..aa3d7bac 100644 --- a/test/test_legend.py +++ b/test/test_legend.py @@ -1,6 +1,7 @@ import logging from test.utils import _build_query_string, _check_request +from lizmap_server.get_legend_graphic import GetLegendGraphicFilter from qgis.core import Qgis @@ -137,3 +138,15 @@ def test_simple_rule_based_feature_count(client): assert symbols[0]['expression'] == expected, symbols[0]['expression'] assert b['title'] == '' assert b['nodes'][0]['title'] == 'rule_based [4]', b['nodes'][0]['title'] + + +def test_regexp_feature_count(): + """ Test the regexp about the feature count. """ + result = GetLegendGraphicFilter.match_label_feature_count("A label [22]") + assert result.group(1) == "A label", result.group(1) + + result = GetLegendGraphicFilter.match_label_feature_count("A label [≈2]") + assert result.group(1) == "A label", result.group(1) + + result = GetLegendGraphicFilter.match_label_feature_count("A label") + assert result is None