开发者社区> 问答> 正文

pytest:将测试标记为“必须通过”,如果测试失败就停止测试

我正在尝试实现一个新的pytest标记,名为@pytest.mark。must_pass,以指示如果标记的测试失败,pytest应该跳过所有后续测试并终止。 我已经能够使用pytest_runtest_call钩子来让pytest在标记的测试失败时终止,但是我使用的是pytest。退出,它不打印回溯,也不显示有关测试的失败指示。 我需要将此故障显示为任何其他测试故障,除了pytest在打印出它需要打印的任何内容以详细说明故障之后停止测试之外。 我的代码到目前为止:

# Copied this implementation from _pytest.runner
def pytest_runtest_call(item):
    _update_current_test_var(item, "call")
    try:
        del sys.last_type
        del sys.last_value
        del sys.last_traceback
    except AttributeError:
        pass
    try:
        item.runtest()
    except Exception:
        # Store trace info to allow postmortem debugging
        type, value, tb = sys.exc_info()
        assert tb is not None
        tb = tb.tb_next  # Skip *this* frame
        sys.last_type = type
        sys.last_value = value
        sys.last_traceback = tb
        del type, value, tb  # Get rid of these in this frame

        # If test is marked as must pass, stop testing here
        if item.iter_markers(name = "must_pass"):
            pytest.exit('Test marked as "must_pass" failed, terminating.')

        raise

pytest中已经有这样的机制了吗? 任何帮助都将非常感谢。 谢谢。 问题来源StackOverflow 地址:/questions/59379412/pytest-mark-a-test-as-a-must-pass-and-stop-testing-if-it-fails

==A:== 所以这可以通过使用pytest_runtest_makereport和pytest_runtest_setup来实现 在您的conftest.py中,您将放置以下内容:

import pytest


def pytest_runtest_makereport(item, call):
    if item.iter_markers(name='must_pass'):
        if call.excinfo is not None:
            parent = item.parent
            parent._mpfailed = item


def pytest_runtest_setup(item):
    must_pass_failed = getattr(item.parent, '_mpfailed', None)
    if must_pass_failed is not None:
        pytest.skip('must pass test failed (%s)' % must_pass_failed.name)

现在我们用下面的方法来测试它:

import pytest


def foo(a, b):
    return a + b


def test_foo_1():
    assert foo(1, 1) == 2


@pytest.mark.must_pass
def test_foo_2():
    assert foo(2, 2) == 6


def test_foo_3():
    assert foo(3, 3) == 6


def test_foo_4():
    assert foo(4, 4) == 8

我们看到期望的输出:

     ▲ = pytest test.py 
=============================================================== test session starts ================================================================
platform darwin -- Python 3.6.5, pytest-4.6.2, py-1.8.0, pluggy-0.12.0
rootdir: /Users/foo/Desktop/testing, inifile: pytest.ini
plugins: cov-2.7.1
collected 4 items                                                                                                                                  

test.py .Fss                                                                                                                                 [100%]

===================================================================== FAILURES =====================================================================
____________________________________________________________________ test_foo_2 ____________________________________________________________________

    @pytest.mark.must_pass
    def test_foo_2():
>       assert foo(2, 2) == 6
E       assert 4 == 6
E        +  where 4 = foo(2, 2)

test.py:14: AssertionError
================================================== 1 failed, 1 passed, 2 skipped in 0.08 seconds ===================================================

=============================== title : [ 在python中不能使用请求模块代理请求 ] 我试图在python中构建一个基本的代理检查器实用程序。这是我现在拥有的:

import requests 
from bs4 import BeautifulSoup
currentip=""
originalip=""
isProxied=False

proxies=["104.236.54.196:8080", "187.62.191.3:61456", "138.204.179.162:44088", "91.216.66.70:32306"]
proxy_count = len(proxies)

url = "https://www.ipchicken.com/"
r = requests.get(url)

def statement():
    global currentip
    global originalip
    print("Current ip is: "+currentip)
    print("Your true ip is: "+originalip)



def main(req):
    global currentip
    soup = BeautifulSoup(req.content, "html.parser")
    html = soup.html
    body = html.body
    font = body.find_all('font')
    ip_container = font[0].b
    ip = ip_container.contents[0]
    currentip=ip

main(r)

originalip=currentip

statement()

print("\n\n")

print("testing proxies...")

print("\n\n")

for x in range(proxy_count):
    proxyContainer={"http":"http://"+proxies[x]}
    r2 = requests.get(url, proxies=proxyContainer, timeout=20)
    print("proxy: " + proxies[x])
    main(r2)
    statement()
    print("\n\n")
    if (currentip==originalip): 
        print("Proxy failed.")
    else:
        print("This proxy works")
    print("\n")

代码运行良好,发出了请求,但它们似乎没有被代理。这是我的输出:

Current ip is: 
199.229.249.163
Your true ip is: 
199.229.249.163



testing proxies...



proxy: 104.236.54.196:8080
Current ip is: 
199.229.249.163
Your true ip is: 
199.229.249.163



Proxy failed.


proxy: 187.62.191.3:61456
Current ip is: 
199.229.249.163
Your true ip is: 
199.229.249.163



Proxy failed.


proxy: 138.204.179.162:44088
Current ip is: 
199.229.249.163
Your true ip is: 
199.229.249.163



Proxy failed.


proxy: 91.216.66.70:32306
Current ip is: 
199.229.249.163
Your true ip is: 
199.229.249.163



Proxy failed.

我已经在一个单独的程序中测试了这些代理,它们似乎工作得很好,我不认为代理是问题。 问题来源StackOverflow 地址:/questions/59379384/cannot-proxy-requests-in-python-using-requests-module

展开
收起
kun坤 2019-12-30 09:32:04 2064 0
2 条回答
写回答
取消 提交回答
  • 机翻 云里雾里的

    2020-01-03 14:24:31
    赞同 展开评论 打赏
  • 如果你连接到加密的url https,那么你必须为https连接设置代理,但你只为http设置代理,所以它不使用代理。 问题是找到工作代理。 我从https://hidemy.name/en/proxy-list/?但我不知道它将工作多久。 为了测试IP,我使用了httpbin.org,它返回JSON格式的数据,因此很容易显示或转换成Python的字典。

    import requests 
    
    url = "https://httpbin.org/ip"
    
    proxies = {
       #"http": '141.125.82.106:80',
       "https": '141.125.82.106:80',
    }
    
    r = requests.get(url, proxies=proxies)
    
    print(r.text)
    
    ip = r.json()["origin"]
    print('IP:', ip)
    

    顺便说一句:其他问题可能是一些代理在额外的报头发送你的IP和服务器可能得到它-所以不是所有的代理都是anonymouse。 编辑:版本与https://www.ipchicken.com/

    import requests 
    from bs4 import BeautifulSoup
    
    def get_ip(request):
        soup = BeautifulSoup(request.content, "html.parser")
        return soup.find('font').b.contents[0]
    
    url = "https://www.ipchicken.com/"
    
    proxies = {
       #"http": '141.125.82.106:80',
       "https": '141.125.82.106:80',
    }
    
    r = requests.get(url, proxies=proxies)
    ip = get_ip(r)
    print(ip)
    
    2019-12-30 09:32:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
移动互联网测试到质量的转变 立即下载
给ITer的技术实战进阶课-阿里CIO学院独家教材(四) 立即下载
F2etest — 多浏览器兼容性测试整体解决方案 立即下载