官术网_书友最值得收藏!

How does pytest do it?

By default, Python's assert statement does not provide any details when it fails, but as we just saw, pytest shows a lot of information about the variables and expressions involved in a failed assertion. So how does pytest do it?

Pytest is able to provide useful exceptions because it implements a mechanism called assertion rewriting.

Assertion rewriting works by installing a custom import hook that intercepts the standard Python import mechanism. When pytest detects that a test file (or plugin) is about to be imported, instead of loading the module, it first compiles the source code into an abstract syntax tree (AST) using the built-in ast module. Then, it searches for any assert statements and rewrites them so that the variables used in the expression are kept so that they can be used to show more helpful messages if the assertion fails. Finally, it saves the rewritten pyc file to disk for caching.

This all might seem very magical, but the process is actually simple, deterministic, and, best of all, completely transparent.

If you want more details, refer to  http://pybites.blogspot.com.br/2011/07/behind-scenes-of-pytests-new-assertion.html, written by the original developer of this feature, Benjamin Peterson. The pytest-ast-back-to-python plugin shows exactly what the AST of your test files looks like after the rewriting process. Refer to:  https://github.com/tomviner/pytest-ast-back-to-python.
主站蜘蛛池模板: 鱼台县| 平凉市| 北川| 集安市| 扶风县| 芦山县| 南京市| 宜昌市| 五指山市| 武川县| 达拉特旗| 松原市| 东丰县| 尖扎县| 特克斯县| 大化| 荥阳市| 泰宁县| 枣强县| 高要市| 孝义市| 道孚县| 萝北县| 嘉黎县| 义乌市| 清涧县| 望奎县| 开江县| 德令哈市| 彰化县| 宁阳县| 杨浦区| 唐河县| 申扎县| 康乐县| 河北省| 左权县| 公主岭市| 靖安县| 抚远县| 明溪县|