惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tailwind CSS Blog
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
L
LangChain Blog
博客园_首页
Recent Announcements
Recent Announcements
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
博客园 - 叶小钗
博客园 - 【当耐特】
The Cloudflare Blog
J
Java Code Geeks
G
Google Developers Blog
云风的 BLOG
云风的 BLOG
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
How to Filter Warnings in Python/pytest
2025-03-06 · via jdhao's digital space

When we are using 3rd packages in Python, we may see some warning messages. For example, when you use the package BeautifulSoup and provide it with an url:

import bs4

def use_bs():
    bs4.BeautifulSoup('https://google.com')

if __name__ == "__main__":
    use_bs()

you will see the warning below:

MarkupResemblesLocatorWarning: The input looks more like a URL than markup. You may want to use an HTTP client like requests to get the document
 behind the URL, and feed that document to Beautiful Soup.
  bs4.BeautifulSoup('https://google.com').txt

In this post, I am not going to discuss whether you should suppress this warning. It is discussed already here and here. I only want to summarize how you can actually disable the warning if you want.

disable warning for normal running of code#

In normal python code, you can use the warnings.filterwarnings method from the Python standard library.

import warnings

import bs4

warnings.filterwarnings(
    action='ignore',
    category=bs4.MarkupResemblesLocatorWarning
)

def use_bs():
    bs4.BeautifulSoup('https://google.com')

if __name__ == "__main__":
    use_bs()

disable warnings when running pytest#

However, even if you disable the warning in your code, when you import the module and run test with pytest, the warning will still be shown. That is because pytest has its own mechanism to deal with the warnings.

To ignore warnings, we can set up the filterwarnings option for pytest in pyproject.toml:

[tool.pytest.ini_options]
filterwarnings = [
    "ignore::bs4.MarkupResemblesLocatorWarning",
]

The above warning filter format is from the standard warning package:

# note the module here refers to the module that is producing the warning itself,
# not calling module.
action:message:category:module:line

What is worth noting is that, when you specify the category that is python builtin, you need to specify the full path. Otherwise, pytest is trying import the warning from Python builtin warning, and will result in an error:

ERROR: while parsing the following warning configuration:

  ignore::MyWarning

This error occurred:

Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniconda/base/lib/python3.10/site-packages/_pytest/config/__init__.py", line 1690, in parse_warning_filter
    category: Type[Warning] = _resolve_warning_category(category_)
  File "/opt/homebrew/Caskroom/miniconda/base/lib/python3.10/site-packages/_pytest/config/__init__.py", line 1729, in _resolve_warning_category
    cat = getattr(m, klass)
AttributeError: module 'builtins' has no attribute 'MyWarning'. Did you mean: 'Warning'?

The same issue has also been described in this post.

Also note that due to the timing of how pytest adds the current working directory to sys.path, if you use category for a warning filter, you might still experience error when pytest tries to parse the filter. See the problem describe here.

References#