英文:
How to ignore fragment of f-string in python assert
问题
这个部分无法直接翻译,因为它包含代码,我只能返回原文。
英文:
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)",
}
答案1
得分: 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
})
英文:
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
})
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论