Good test practice in python

1

I'm working on a python test for a week, I started with unittest and some doubts came up ... Should I use a test class for each method of a class, or use a test class for each class ... and still, how to proceed with functions that do not belong to a class?

    
asked by anonymous 09.07.2018 / 00:27

1 answer

4

unittest requires tests to be in classes more because of the way it is implemented - it is practical to search for UnitTests subclasses, and have the setup and teardown methods for a set of tests - rather than matching any class division of your program.

So - if you have functions that are not in classes, you have to test them 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 default library, most of the Python community nowadays uses pytest for testing. Among the various reasons for its use is a lesser bureaucracy to write its tests - if it makes sense to group them into classes, do so, but most of the projects group tests in .py files that have to do with same subject.

Among other advantages of pytest are: it's easier for any user of your project to run the tests - Python developers are accustomed 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.

Why, then, is it not in the default library? In recent years the Python community chooses not to place some libraries that are used almost universally within the language just so as not to stall its development. Placing the pytest or the requests in Python's stdlib would limit that versions with new features of those libraries would only be released with each new version of Python. What's more, versions to fix small bugs would also have to follow Python's micro-version cycle - which can last for several months (and sometimes fixes are urgent). In addition, the contributors of these projects, besides 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 unittest: it has been built into Python for over 10 years, and has practically stopped in time with no new functionality.

    
09.07.2018 / 19:36