Rodrigo A
Rodrigo A

Reputation: 767

Pytest how to specify python version per test function

I'm running some tests and one of them compares an exception with it's message, it looks like this, BaseCallback is just a class with abstract methods from abc, I'm testing that there is an error if the methods are not defined using inheritance, intentionally I miss the method __call__ that is mandatory by the base class

from base import BaseCallback

import pytest


def test_base_callback_call():
    class MyDummyCallback(BaseCallback):
        def __init__(self, metric):
            self.metric = metric

        def on_step(self, record=None, logbook=None, estimator=None):
            print(record)

    with pytest.raises(Exception) as excinfo:
        callback = MyDummyCallback(metric="fitness")

    assert (
        str(excinfo.value) == "Can't instantiate abstract class MyDummyCallback with abstract methods __call__ "
    )

The problem is that I'm testing several python versions at the same time, it works on python 3.6, 3.7 and 3.8 but in python 3.9 the assertion message changes from "Can't instantiate abstract class MyDummyCallback with abstract methods call " to "Can't instantiate abstract class MyDummyCallback with abstract method call "

So it makes my test fail due that missing S

Is there a way that I set the valid python versions in this function (say from 3.6 to 3.8) and create another test for python 3.9? Or what would be the suggested way to handle this kind of changes?

I made a turnaround by checking by 1 of the 2 messages, if at least 1 is present the test pass, but it feels kinda odd

Upvotes: 2

Views: 1871

Answers (1)

Micky Loo
Micky Loo

Reputation: 1493

pytest allows you to conditionally skip tests by using the skipif decorator.

@pytest.mark.skipif(sys.version_info >= (3, 9))
def test_base_callback_call():
   ...

https://docs.pytest.org/en/6.2.x/skipping.html#id1

Upvotes: 10

Related Questions