A compiled match expression as used by -k and -m. The expression can be evaluated against different matchers.
| 188 | |
| 189 | |
| 190 | class Expression: |
| 191 | """A compiled match expression as used by -k and -m. |
| 192 | |
| 193 | The expression can be evaluated against different matchers. |
| 194 | """ |
| 195 | |
| 196 | __slots__ = ("code",) |
| 197 | |
| 198 | def __init__(self, code: types.CodeType) -> None: |
| 199 | self.code = code |
| 200 | |
| 201 | @classmethod |
| 202 | def compile(self, input: str) -> "Expression": |
| 203 | """Compile a match expression. |
| 204 | |
| 205 | :param input: The input expression - one line. |
| 206 | """ |
| 207 | astexpr = expression(Scanner(input)) |
| 208 | code: types.CodeType = compile( |
| 209 | astexpr, |
| 210 | filename="<pytest match expression>", |
| 211 | mode="eval", |
| 212 | ) |
| 213 | return Expression(code) |
| 214 | |
| 215 | def evaluate(self, matcher: Callable[[str], bool]) -> bool: |
| 216 | """Evaluate the match expression. |
| 217 | |
| 218 | :param matcher: |
| 219 | Given an identifier, should return whether it matches or not. |
| 220 | Should be prepared to handle arbitrary strings as input. |
| 221 | |
| 222 | :returns: Whether the expression matches or not. |
| 223 | """ |
| 224 | ret: bool = eval(self.code, {"__builtins__": {}}, MatcherAdapter(matcher)) |
| 225 | return ret |