How to check a member variable with py.test skipif?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles
--
Chapters
00:00 Question
01:05 Accepted answer (Score 8)
02:42 Answer 2 (Score 3)
03:05 Thank you
--
Full question
https://stackoverflow.com/questions/2260...
Accepted answer links:
[documentation]: https://pytest.org/latest/skipping.html#...
[the documentation]: https://pytest.org/latest/builtin.html#r...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pytest
#avk47
ACCEPTED ANSWER
Score 10
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 ===================================
ANSWER 2
Score 3
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):
...