【问题标题】:Writing Python Test Cases to check links in Python编写 Python 测试用例以检查 Python 中的链接
【发布时间】:2021-05-08 18:18:27
【问题描述】:

这是我的队友用来检查 HTML 页面中的链接以查看其是否损坏的功能。该函数搜索每个链接并将它们存储在 array[] g 中。我的工作是为此功能创建测试用例,但我不完全确定如何开始。我是 Python 初学者,想学习如何创建更有效的测试用例。

import urllib.request
import re
import urllib.error
def check(url):
    try:
        f= urllib.request.urlopen(url)
    except urllib.error.HTTPError :
            return False
    return True
def trouveurdurls(url):
    f= urllib.request.urlopen(url)
    b=(f.read().decode('utf-8'))
    d = re.findall('<a href=".*?"', b)
    liste=[]
    f.close()
    for el in d:
        g=re.findall('"https?://.*\.*"',el)
        liste.append(g)
    a=[]
    for el in liste:
        chaine= ''.join(map(str,el))
        url=chaine.replace('\'','')
        print(url)
        #check(url)
b=trouveurdurls("http://127.0.0.1/")

【问题讨论】:

    标签: python unit-testing http testing


    【解决方案1】:

    我的回答是基于我所熟悉的 pytest 和 VScode。使用 linter 也很好。我用 flake8。

    我假设您与其他原始文件没有任何关系。在实践中应该有更多很多。但是要从零开始创建一些测试...

    • 创建一个文件夹,把你要测试的代码放在里面
    • 在 VSCode 中打开文件夹(这对 VSCode 很重要)
    • 创建一个测试目录,test
    • Ctrl+Shift+P 然后 Python: Configure Tests,选择 pytest,选择 test 作为您的测试所在
    • 如果安装了所有需要的模块,VSCode 会注意到没有安装测试。您可能需要安装一些模块,但有时 VScode 会提供帮助。

    .vscode\settings.json 有望出现。我的看起来像:

    {
        "python.linting.pylintEnabled": true,
        "python.linting.flake8Enabled": true,
        "python.linting.enabled": true,
        "python.testing.pytestArgs": [
            "test"
        ],
        "python.testing.unittestEnabled": false,
        "python.testing.nosetestsEnabled": false,
        "python.testing.pytestEnabled": true
    }
    

    现在创建test\__init__.py(空)和test\test_url.py

    # I called your file trou.py
    from trou import check  # __init__.py needed for the import to work
    
    def test_check():  # pytest finds functions starting with test_
        """A very simple test."""
        assert check("http://stackoverflow.com/") is True
    

    扩展名Python Test Explorer for Visual Studio Code 非常有用。开始测试发现将失败,因为您正在测试的文件有错误。为了让它看到测试,我需要做的最起码是:

    # b=trouveurdurls("http://127.0.0.1/")
    

    pytest 的输出应该是这样的。虽然 VSCode 测试资源管理器提供了一个漂亮的绿色勾号。

    ============================= test session starts =============================
    platform win32 -- Python 3.8.5, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
    rootdir: c:\xxx\temp
    plugins: anyio-2.2.0, asyncio-0.14.0
    collected 1 item
    
    test\test_url.py .                                                       [100%]
    
    - generated xml file: C:\xxx\AppData\Local\Temp\tmp-24832WX0Q0P6CNZbs.xml -
    ============================== 1 passed in 1.23s ==============================
    

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2023-02-01
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多