From 47b40dbf7e74a074361ba7295a48092ecae0d824 Mon Sep 17 00:00:00 2001 From: vincent porte Date: Wed, 25 Sep 2024 11:36:07 +0200 Subject: [PATCH] replace current date in a soup for snapshot, given a specified format --- lacommunaute/utils/testing.py | 16 +++++++++++++++- lacommunaute/utils/tests/tests_utils.py | 7 +++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lacommunaute/utils/testing.py b/lacommunaute/utils/testing.py index 8757a714c..5025daa2e 100644 --- a/lacommunaute/utils/testing.py +++ b/lacommunaute/utils/testing.py @@ -1,4 +1,5 @@ import importlib +from datetime import datetime from bs4 import BeautifulSoup from django.db import connection @@ -19,7 +20,14 @@ def disable(self): setattr(self._module, key, value) -def parse_response_to_soup(response, selector=None, no_html_body=False, replace_in_href=None, replace_img_src=False): +def parse_response_to_soup( + response, + selector=None, + no_html_body=False, + replace_in_href=None, + replace_img_src=False, + replace_current_date_format=False, +): soup = BeautifulSoup(response.content, "html5lib", from_encoding=response.charset or "utf-8") if no_html_body: # If the provided HTML does not contain tags @@ -50,6 +58,12 @@ def parse_response_to_soup(response, selector=None, no_html_body=False, replace_ for attr in ["src"]: for links in soup.find_all("img", attrs={attr: True}): links.attrs.update({attr: "[img src]"}) + if replace_current_date_format: + current_date_str = datetime.now().strftime(replace_current_date_format) + for text_node in soup.find_all(string=True): + if current_date_str in text_node: + new_text = text_node.replace(current_date_str, "[CURRENT DATE]") + text_node.replace_with(new_text) return soup diff --git a/lacommunaute/utils/tests/tests_utils.py b/lacommunaute/utils/tests/tests_utils.py index 913dff897..96addac01 100644 --- a/lacommunaute/utils/tests/tests_utils.py +++ b/lacommunaute/utils/tests/tests_utils.py @@ -602,6 +602,13 @@ def test_replace_img_src(self): soup = parse_response_to_soup(response, replace_img_src=True) assert str(soup) == '' + def test_replace_current_date(self): + response = HttpResponse( + f'
Today is {datetime.now().strftime("%d/%m/%Y")}
' + ) + soup = parse_response_to_soup(response, replace_current_date_format="%d/%m/%Y") + assert str(soup) == "
Today is [CURRENT DATE]
" + def test_replace_in_href_mixing_tuple_and_object(self): topic = TopicFactory() response = HttpResponse(