Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing class methods with pytest

Tags:

python

pytest

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()?

like image 306
laserbrain Avatar asked Sep 08 '16 16:09

laserbrain


People also ask

How do you write a pytest class in Python?

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.

How do I run a pytest test 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 .

How do you test a class in Python?

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() .


2 Answers

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 
like image 132
elethan Avatar answered Oct 02 '22 15:10

elethan


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 
like image 35
Tyler Sebastian Avatar answered Oct 02 '22 16:10

Tyler Sebastian