Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest how to specify python version per test function

Tags:

python

pytest

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

like image 217
Rodrigo A Avatar asked Feb 04 '26 11:02

Rodrigo A


1 Answers

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

like image 102
Micky Loo Avatar answered Feb 07 '26 02:02

Micky Loo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!