忽略 Python 断言中的 f-string 片段。

huangapple go评论66阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2023年4月17日 21:14:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035572.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定