I have tests like this:
import unittest
class TestBase(unittest.TestCase):
def setUp(self):
self.decorator = None
def testA(self):
data = someGeneratorA().generate()
self.assertTrue(self.decorator.someAction(data))
def testB(self):
data = someGeneratorB().generate()
self.assertTrue(self.decorator.someAction(data))
def testC(self):
data = someGeneratorC().generate()
self.assertTrue(self.decorator.someAction(data))
class TestCaseA(TestBase):
def setUp(self):
self.decorator = SomeDecoratorA
class TestCaseB(TestBase):
def setUp(self):
self.decorator = SomeDecoratorB
As you see, TestCaseA and TestCaseB is very similar, so I made TestBase class which implement body of testA, testB and testC method.
TestCaseA different from TestCaseB only decorator parameter.
So, I would like to ask, is any better way to organize my tests? And I have problem beacuse TestBase class - it's test's - shouldn't be runned ever (self.decorator is None so it will rase an exception)
Anything that inherits from unittest.TestCase is seen as a set of tests.
You could instead have your base class not inherit from TestCase, moving that base class to your concrete test classes instead:
class TestBase(object):
# base tests to be reused
class TestCaseA(TestBase, unittest.TestCase):
# Concrete tests, reusing tests defined on TestBase
class TestCaseB(TestBase, unittest.TestCase):
# Concrete tests, reusing tests defined on TestBase
Related
I would like to mock my class attribute under test.
The class is as follows:
import path.to.some.other.class.OtherClass
class ClassToTest:
def __init__(self, some_path):
self._attribute_to_test = OtherClass(some_other_path)
#rest of the class details
..
Unit Test that I tried to write is as follows (but does not work as expected):
with patch("path.to.some.other.class.OtherClass") as _mock:
instance = _mock.return_value
ClassToTest._attribute_to_test = instance
Now when I try to instantiate the ClassToTest the attribute attribute_to_test does not mock.
As can be seen in the following example, I've defined a BaseClass for all tests, each test case class inherits the base class.
Both classes needs to perform a one time initialization, when test_vehicles.py is executed, I need to make sure that setUpClass of the base class is invoked as well, not sure how to achieve that where #classmethod is in play.
# base.py
import unittest
class BaseClass(unittest.TestCase):
#classmethod
def setUpClass(cls):
# initialize stuff
cls.app = app
# test_vehicles.py
class VehiclesTestCase(BaseClass):
#classmethod
def setUpClass(cls):
# initialize stuff
cls.vehicle_id = '123'
def test_get_vehicle(self):
resp = self.app.get(self.vehicle_id)
self.assertEqual(resp, True)
if __name__ == '__main__':
unittest.main()
Similar question Using super with a class method. More information yoou can get also from https://docs.python.org/3/library/functions.html#super.
Solution: use super function and bound to the class
# test_vehicles.py
class VehiclesTestCase(BaseClass):
#classmethod
def setUpClass(cls):
super(VehiclesTestCase, cls).setUpClass()
cls.vehicle_id = '123'
if __name__ == '__main__':
unittest.main()
You can use the super method in the inherited classes' setUpClass to access the setUpClass of BaseClass:
super().setUpClass()
If you don't want to call super in each child class, just create an abstract method in BaseClass and call it in setUpClass of BaseClass. VehiclesTestCase now has to implement this abstract method:
class BaseClass(unittest.TestCase):
#classmethod
def setUpClass(cls):
# initialize stuff
cls.app = app
#classmethod
def _setUpChild(cls):
raise NotImplementedError
class VehiclesTestCase(BaseClass):
#classmethod
def _setUpChild(cls):
# initialize stuff
cls.vehicle_id = '123'
def test_get_vehicle(self):
resp = self.app.get(self.vehicle_id)
self.assertEqual(resp, True)
I would also recommend that BaseClass is not a TestCase if it cannot run by itself. It would always show up in your test report although it has no tests. You can instead use multi-inheritance:
class BaseClass:
# Stuff
class VehiclesTestCase(BaseClass, unittest.TestCase):
# Stuff
The order of inheritance is important. Method lookup is done from left to right. This means that BaseClass.setUpClass overrides the setUpClass of TestCase.
I have a Test class with as many as 50 different method. I want to patch every method with a mock function.
prod = {"foo": "bar"}
def TestClass:
#patch(db.get_product, return_value=prod)
def test_1:
pass
#patch(db.get_product, return_value=prod)
def test_2:
pass
.
.
.
#patch(db.get_product, return_value=prod)
def test_50:
pass
Is there any easy way to do this instead of repeating #patch(db.get_product, return=prod) 50 times?
You can use patch as a class decorator instead:
#patch(db.get_product, return_value=prod)
class TestClass:
def test_1:
pass
def test_2:
pass
.
.
.
def test_50:
pass
Excerpt from the documentation:
Patch can be used as a TestCase class decorator. It works by
decorating each test method in the class. This reduces the boilerplate
code when your test methods share a common patchings set.
I have a test class with few test methods and I want to patch some app classes and methods from the test methods.
In pytest docs I found an example of how to use monkeypatch module for tests. It that example all tests are just functions, not testclass methods.
But I have a class with test methods:
class MyTest(TestCase):
def setUp():
pass
def test_classmethod(self, monkeypatch):
# here I want to use monkeypatch.setattr()
pass
And just passing monkeypatch as method param is obviously doesn't work. So looks like py.test magic doesn't work this way.
So the question is simple and maybe stupid: how can I use monkeypatch.setattr() for pytest inside from the test class method?
It can't work in this form
While pytest supports receiving fixtures via test function arguments
for non-unittest test methods, unittest.TestCase methods cannot
directly receive fixture function arguments as implementing that is
likely to inflict on the ability to run general unittest.TestCase test
suites.
You might create monkeypatch directly
from _pytest.monkeypatch import MonkeyPatch
class MyTest(TestCase):
def setUp():
self.monkeypatch = MonkeyPatch()
def test_classmethod(self):
self.monkeypatch.setattr ...
...
or create own fixture, which will add monkeypatch to your class, and use #pytest.mark.usefixtures
#pytest.fixture(scope="class")
def monkeypatch_for_class(request):
request.cls.monkeypatch = MonkeyPatch()
#pytest.mark.usefixtures("monkeypatch_for_class")
class MyTest(TestCase):
def setUp():
pass
def test_classmethod(self):
self.monkeypatch.setattr ...
...
I had exactly the same problem.
This works perfectly
import unittest
import pandas as pd
from _pytest.monkeypatch import MonkeyPatch
from src.geipan_data import loadLongitudeLatitudeDateTestimony
class TestGeipanData(unittest.TestCase):
def setUp(self):
self.monkeypatch = MonkeyPatch()
def test_loadLongitudeLatitudeDateTestimony(self):
def read_csv(*args, **kwargs):
return pd.DataFrame({
'obs_date_heure': ['2010-05-21', '1926-05-21'],
'obs_1_lon': [45.123, 78.4564],
'obs_1_lat': [32.123, 98.4564],
})
self.monkeypatch.setattr(pd, 'read_csv', read_csv)
df = loadLongitudeLatitudeDateTestimony()
self.assertListEqual(
df.columns.values.tolist(),
['obs_date_heure', 'obs_1_lon', 'obs_1_lat']
)
In this example I do mock the pd.read_csv method with monkey patch and I uses asserListEqual that extends from unittest.TestCase
I am trying to patch a class that is instantiated by the class I am trying to test, but it doesn't work. I have read the various docs but still haven't found what I am doing wrong. Here is the code snippet:
In tests/Test.py:
from module.ClassToTest import ClassToTest
class Test(object):
#mock.patch('module.ClassToPatch.ClassToPatch', autospec = False)
def setUp(self, my_class_mock):
self.instance = my_class_mock.return_value
self.instance.my_method.return_value = "def"
self.class_to_test = ClassToTest()
def test(self):
val = self.class_to_test.instance.my_method() #Returns 'abc' instead of 'def'
self.assertEqual(val, 'def')
In module/ClassToPatch.py:
class ClassToPatch(object):
def __init__(self):
pass
def my_method(self):
return "abc"
In module/ClassToTest.py:
from module.ClassToPatch import ClassToPatch
class ClassToTest(object):
def __init__:
# Still instantiates the concrete class instead of the mock
self.instance = ClassToPatch()
I know in this case I could easily inject the dependency, but this is just an example. Also, we use a single class per file policy, with the file named like the class, hence the weird import naming.
As norbert mentions, the fix is to change the mock line from
#mock.patch('module.ClassToPatch.ClassToPatch', autospec = False)
to
#mock.patch('module.ClassToTest.ClassToPatch', autospec = False)
According to the docs:
The patch() decorator / context manager makes it easy to mock classes or objects in a module under test. The object you specify will be replaced with a mock (or other object) during the test and restored when the test ends.
You are testing the ClassToTest module, not the ClassToPatch module.