Python:使用fixture for unittest.TextTestRunner.run()

时间:2017-08-29 10:18:04

标签: python-3.x pytest

定义了Cases.py文件和定义的套件:

import unittest
import pytest

from adminzone_tests.Clients import TestClients

def collect_suite():
    suite = unittest.TestSuite()
    suite.addTest(TestClients)
    return suite

@pytest.mark.usefixtures('admin_session')
def run():
    unittest.TextTestRunner(verbosity=2).run(collect_suite())

@pytest.mark.usefixtures('client_session')
def run():
    unittest.TextTestRunner(verbosity=2).run(collect_suite())

conftest.py档案:

import pytest

from base.Common import Common
from base.Users import Users


@pytest.fixture(scope='session')
def admin_session(request):
    Users.users('admin')

    def admin_session_teardown():
        Common.logout()
    request.addfinalizer(admin_session_teardown)

@pytest.fixture(scope='session')
def client_session(request):
    Users.users('client')

    def client_session_teardown():
        Common.logout()
    request.addfinalizer(client_session_teardown)

创意:使用不同的用户会话逐个执行相同的套件。 但只有在包含autouse=True

的情况下才执行fixture

如何在没有autouse=True的情况下使夹具可执行并使用不同的设置运行相同的套件?

1 个答案:

答案 0 :(得分:1)

最后我找到了我正在寻找的解决方案,可能对某人有用:
使用命令行参数的钩子

conftest.py档案:

import pytest

def pytest_addoption(parser):
# adding command line arg --user
parser.addoption('--users', action='append', default=['user1'])

def pytest_generate_tests(metafunc):
    if 'users' in metafunc.fixturenames:
        us = set(metafunc.config.option.users)
        if not us:
            us = ['user1']
        elif 'all' in us:
            us = ['user2', 'user1']
        else:
            us = list(us)
        metafunc.parametrize('users', us, scope='session')

@pytest.yield_fixture(scope='session', autouse=True)
def define_users(request, users):
    # Execute login here, as example called function with param of user_type
    login(users)

def teardown():
    # Execute logout here
    logout()
    request.addfinalizer(teardown)

Cases.py档案:

import unittest

suite = unittest.TestSuite()

def collect_suite():
    suite.addTest(TestClass1)
    # adding more test classes here

def run():
    unittest.TextTestRunner(verbosity=2).run(suite)

现在通过命令行执行命令(在项目的根目录中) python -m pytest Cases.py -s -v -n auto --users all

测试套件将以登录user1执行,之后将以user2

登录执行