In the documentation of pytest various examples for test cases are listed. Most of them show the test of functions. But I’m missing an example of how to test classes and class methods. Let’s say we have the following class in the module cool.py
we like to test:
class SuperCool(object): def action(self, x): return x * x
How does the according test class in tests/test_cool.py
have to look?
class TestSuperCool(): def test_action(self, x): pass
How can test_action()
be used to test action()
?
Pytests may be written either as functions or as methods in classes – unlike unittest, which forces tests to be inside classes. Test classes must be named “Test*”, and test functions/methods must be named “test_*”. Test classes also need not inherit from unittest. TestCase or any other base class.
Running pytestWe can run a specific test file by giving its name as an argument. A specific function can be run by providing its name after the :: characters. Markers can be used to group tests. A marked grouped of tests is then run with pytest -m .
First you need to create a test file. Then import the unittest module, define the testing class that inherits from unittest. TestCase, and lastly, write a series of methods to test all the cases of your function's behavior. First, you need to import a unittest and the function you want to test, formatted_name() .
All you need to do to test a class method is instantiate that class, and call the method on that instance:
def test_action(self): sc = SuperCool() assert sc.action(1) == 1
Well, one way is to just create your object within the test method and interact with it from there:
def test_action(self, x): o = SuperCool() assert o.action(2) == 4
You can apparently use something like the classic setup
and teardown
style unittest using the methods here: http://doc.pytest.org/en/latest/xunit_setup.html
I'm not 100% sure on how they are used because the documentation for pytest is terrible.
Edit: yeah so apparently if you do something like
class TestSuperCool(): def setup(self): self.sc = SuperCool() ... # test using self.sc down here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With