-2

Is it possible to ignore one fragment of f-string in python assertion, eg.

assert results.to_dict() == {
            "comment": f"Retrying in 3600 seconds (1/5)",
        }

How to make that any of tries 1-5 was assert as true in this line? Maybe some regex?

assert results.to_dict() == {
            "comment": f"Retrying in 3600 seconds ({some_regex}/5)",
        }
lukos06
  • 187
  • 1
  • 4
  • 20
  • Did you try to write a [regex](https://realpython.com/regex-python/) to solve this? Matching numbers is pretty straightforward. – jarmod Apr 17 '23 at 13:17
  • An f-string is just a particular syntax for defining a string dynamically. Regardless of how the string is constructed, the *result* is used the same in a string comparison: are corresponding characters in the two strings equal? – chepner Apr 17 '23 at 13:25

1 Answers1

2

I'd just do

comment = results.to_dict()["comment"]
assert comment.startswith("Retrying in 3600 seconds")

though the effect is slightly different, as you're not checking whether "comment" is the only key in the dict anymore. If you need that, you could

result = results.to_dict()
comment = result.pop("comment")
# (Pop out more keys)
assert not result  # nothing left unread
assert comment.startswith("Retrying in 3600 seconds")

And, then, of course, if you really do want to test whether there really is a retry counter,

assert re.match(r"Retrying in 3600 seconds \(\d+/\d+\)", comment)

Finally, you could wrap all of this into a helper with a predicate function for each key you want to check:

from itertools import partial

def verify_dict_contents(victim, matchers):
    for key, matcher in matchers.items():
        assert key in victim
        assert matcher(victim[key])
    return True

# ...

result = results.to_dict()
assert verify_dict_contents(result, {
  "comment": partial(re.match, r"Retrying in 3600 seconds \(\d+/\d+\)"),
  "number": lambda x: x >= 42
})
AKX
  • 152,115
  • 15
  • 115
  • 172