Good practice of python tests

Asked

Viewed 213 times

1

I am a week studying tests in python, I started with unittest and some doubts arose... I must use a test class for each method of a class, or use a test class for each class...and yet, how to proceed with functions that do not belong to a class?

  • Unit tests should have a test for each unit of code - very suggestive, right? So, you should define this. Does your method have a test case? Then a test method is enough. Does your method have several test cases? Then only one is not enough.

1 answer

5


The unittest requires testing to be in classes more because of how it is implemented - it is practical to find subclasses of Unittests, and have setup and teardown methods for a set of tests - than to match any class division of your program.

So - if you have functions that are not in classes, you have to put the tests in a class in the same way. Keep in mind that tests in the same class can share setup and teardown methods.

In fact, although unitest is in the standard library, today most of the Python community uses the library pytest for testing. Among the various reasons for its use is precisely a smaller bureaucracy to write its tests - if it makes sense to group them into classes, do it, but most projects group the tests into archives. py that has to do with the same subject.

Among the other advantages of pytest are: it’s easier for any user of your project to run the tests - Python developers are used to calling py.test. It is extremely versatile to produce data that will be used as "fixtures". It has plug-ins for Coverage and statistics and Profiling, among other things.

But why isn’t it in the standard library? In recent years the Python community chooses not to put some libraries that are used almost universally within the language precisely in order not to halt its development. Placing pytest or requests in Python stdlib would limit the release of new versions of these libraries to each new version of Python. Even more - versions to fix small bugs would also have to follow the Python micro-version cycle - which can last several months (and sometimes the fixes are urgent). In addition, the contributors of these projects, in addition to following the sieve and processes of each project would also be restricted by the processes for inclusion in the language itself. A good way to understand this is precisely the unittest: it was incorporated into Python more than 10 years ago, and practically stopped in time, with no new functionality.

  • Thanks Bueno...which answer...I will do a search on pytest.. I was very excited.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.