用pytest正确测试

Correctly test with pytest

所以我想开始在我的 python 程序中使用 pytest 进行测试。

编辑: 我只是想测试响应,因为它似乎是最容易测试的东西。我现在知道有多种方法可以测试响应,但我更希望对构建测试和使用它们有一个大致的了解。

我首先测试使用请求调用页面时是否会出现正确的响应。

像这样:

**main.py**

def get_page(search_url):
  page = requests.get(search_url)
  return page

url = "https://www.google.com/search?q=weather+results&oq=weather+results&aqs=chrome..69i57.4626j0j1&sourceid=chrome&ie=UTF-8"

get_page(url)

这是我用来测试响应的测试代码。这是我编写的第一个测试

**test_main.py**

from main import get_page

def test_page_response():

   test_url = "https://www.google.com/search?q=weather+results&oq=weather+results&aqs=chrome..69i57.4626j0j1&sourceid=chrome&ie=UTF-8"

   assert str(get_page(test_url2)) == "<Response [200]>"

我这样做对吗?当我取出 url 来打破它并触发测试时,它会显示大量文本。当然,这是它的全部荣耀中的错误,但是测试不应该让这个 更容易阅读和理解什么坏了?

这让我相信我的做法是错误的。

编辑 2: 这是输出:http://pastebin.com/kTgc5bsR

您的目标是编写单元测试吗?

如果是这样,测试 requests.get 已经被 requests 中的测试覆盖。重新检查 Python 或你的图书馆已经为你测试过的东西被认为是非 pythonic 的(而且是多余的)。相反,您应该专注于测试应用的独特部分。

比如模拟requests的使用。一种方法是使用库 requests-mock,当然还有更多的方法。

假设您已经模拟了请求,我为 get_page(...) 编写单元测试的方法是断言它 returns 是预期的响应主体。您还可以测试状态代码,但如果您模拟请求,这可能不会增加很多价值。

您也可以考虑在集成测试中测试检索网页本身。

我很乐意在此处添加代码示例,如果这样会更清楚的话。

### test_main.py ###

from main import get_page

def test_page_response():
   test_url = "https://www.google.com/search?q=weather+results&oq=weather+results&aqs=chrome..69i57.4626j0j1&sourceid=chrome&ie=UTF-8"

    response = get_page(test_url2)  # get_page() returns a response object
    assert response.status_code == 200

    # also here reponse.text will contain the html string.
    # You can parse it and have more assertions.
    # This will be your real test to see if you got search results you expected.

阅读有关如何使用 python-requests 的更多信息:

http://docs.python-requests.org/en/master/

你的url基本上就是你的测试输入,你可以修改url来生成测试。 我建议通过 py.test 个基本示例:

http://pytest.org/latest/example/index.html

并且还学习了一般测试入门知识。