質問

In my setUp function in a TestCase I set a member variable is_type to True or False. I have a few tests in the class which shouldn't be run if the value is false. I don't know how to do this with the skipif functionality.

@py.test.mark.skipif( not ???.is_type )
def test_method(self):
   ...

self doesn't work for ??? since it's not in the object yet. How can I refer to the is_type variable?


More complete example:

class DBTest(unittest.TestCase):
    def setUp(self):
        self.is_dynamo = os.environ.get( 'TEST_DB', '' ) == 'Dynamo'

    def test_account_ts(self):
        if not self.is_dynamo:
            return

        ...

How can I transform that if not self.is_dynamo into a py.test skipif condition instead?

役に立ちましたか?

解決

As you mention, you can't refer to an instance in your skipif marker, since the instance doesn't exist yet.

I would keep it simple and do something like:

@pytest.mark.skipif(os.environ.get('TEST_DB') != 'Dynamo')
def test_dynamo():
    db = MyDatabaseWithDynamo(is_dynamo=True)
    # Some assertion or other.

You can use @pytest.mark.skipif on classes too.

The documentation on this feature has some good examples. Many of them relate to checking parts of the environment to decide what tests should get skipped. This sounds very similar to your use case, so I would say you are in good company.

But if, as you say in your comment below, you want to avoid global variables, you can raise a pytest.skip exception from wherever you want. Below I'm doing it in a fixture, which I think keeps test setup well-separated from test cases. See the documentation for more possibilities.

Here is my test file:

import os
import pytest

class MyDatabaseWithDynamo(object):
    def __init__(self, is_dynamo):
        pass

@pytest.fixture
def database():
    is_dynamo = os.environ.get('TEST_DB') == 'Dynamo'
    if not is_dynamo:
        raise pytest.skip()
    return MyDatabaseWithDynamo(is_dynamo=True)

def test_db(database):
    pass

Here is the test output:

$ py.test test_foo.py
======================================= test session starts =======================================
platform darwin -- Python 2.7.5 -- py-1.4.20 -- pytest-2.5.2
collected 1 items

test_foo.py s

==================================== 1 skipped in 0.01 seconds ===================================

他のヒント

import unittest
import functools


def skipIfNotDynamo(test_method):
    @functools.wraps(test_method)
    def wrapper(self):
        if not self.is_dynamo:
            raise unittest.SkipTest("Skip because it is not dynamo")

        return test_method(self)

    return wrapper


class DBTest(unittest.TestCase):
    def setUp(self):
        self.is_dynamo = ...

    @skipIfNotDynamo        
    def test_account_ts(self):
        ...
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top