如何在pytest中模拟对HTML文件中链接的请求?

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

How to mock a request to a link in an HTML file in pytest?

问题

我正在根据HTML文件渲染PDF。
我需要测试PDF的内容。
HTML文件中有指向https://example.com的href链接,我需要模拟对该链接的请求以测试PDF的内容。所以,我实际上不关心该请求的响应,我只需要模拟请求。
所以在我的测试中,我尝试了以下requests_mock库的用法:

with requests_mock.mock() as mock:
    mock.get(
        url="https://example.com",
        status_code=200,
    )
    # 渲染pdf
    # 检查内容

但没有成功。有人能帮我解决这个问题吗?

英文:

I am rendering a PDF based on a html file.
I need to test the context of the PDF.
There is href link to https://example.com in the HTML file and I need to mock the request to the link to test the PDF context. So, I actually don't care about the response of that request, I just need to mock the request.
So in my test I tried requests_mock library as following:

with requests_mock.mock() as mock:
    mock.get(
        url="https://example.com",
        status_code=200,
    )
    # render pdf
    # check the context

But didn't work out. Could anyone help me how to solve this?

答案1

得分: 1

你可以使用“responses”包模拟HTTP调用

pip安装响应

导入响应

@responses.activate
def测试调用示例():
    响应获得(“https://example.com”,状态=200)
英文:

you can use "responses" package to mock http calls

> pip install responses

import responses

@responses.activate
def test_call_example():
    responses.get("https://example.com", status=200)

huangapple
  • 本文由 发表于 2023年4月19日 23:01:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056041.html
匿名

发表评论

匿名网友

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

确定