Skip to content

Commit

Permalink
Merge branch 'mr/pmderodat/pattern-substitute-callback' into 'master'
Browse files Browse the repository at this point in the history
PatternSubstitute: update annotations to accept replacement callbacks

See merge request it/e3-testsuite!37
  • Loading branch information
pmderodat committed Aug 23, 2024
2 parents 50a1ecd + 2159288 commit 7cbd3ed
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
27.0 (Not released yet)
=======================

* `PatternSubstitute`: update annotations to accept replacement callbacks.
* `e3.testsuite.report.xunit`: add a `XUnitImportApp` class to make it possible
to create customized versions of the `e3-convert-xunit` script without code
duplication.
Expand Down
21 changes: 18 additions & 3 deletions src/e3/testsuite/driver/diff.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
from __future__ import annotations

import os
import re
from typing import AnyStr, Generic, List, Optional, Pattern, Tuple, Union
from typing import (
AnyStr,
Callable,
Generic,
List,
Optional,
Pattern,
Tuple,
Union,
)

from e3.diff import diff
from e3.os.fs import unixpath
Expand Down Expand Up @@ -98,7 +109,9 @@ class PatternSubstitute(OutputRefiner, Generic[AnyStr]):
"""Replace patterns in outputs."""

def __init__(
self, pattern: AnyStr, replacement: Optional[AnyStr] = None
self,
pattern: AnyStr,
replacement: AnyStr | Callable[[re.Match], AnyStr] | None = None,
) -> None:
"""
Initialize a PatternSubstitute instance.
Expand All @@ -109,7 +122,9 @@ def __init__(
string).
"""
self.regexp: Pattern[AnyStr] = re.compile(pattern)
self.replacement: AnyStr = replacement or type(pattern)()
self.replacement: AnyStr | Callable[[re.Match], AnyStr] = (
replacement or type(pattern)()
)

def refine(self, output: AnyStr) -> AnyStr:
return self.regexp.sub(self.replacement, output)
Expand Down
11 changes: 11 additions & 0 deletions tests/tests/test_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,14 @@ def test_line_by_line():

assert subst.refine(output) == b"first some-content line\n"
assert lbl_subst.refine(output) == b"first line\nsome-content line\n"


def test_pattern_substitute_callback():
"""Check that PatternSubstute accept replacement callbacks."""

def repl(m):
return m.group(1)

refiner = diff.PatternSubstitute(r"[a-z]*\((.*)\)", repl)

assert refiner.refine("foo(1, 2)") == "1, 2"

0 comments on commit 7cbd3ed

Please sign in to comment.