Testing modules in python?

Hey. I'm new to python, and it's hard for me to grasp the concept of unit testing in python.

I come from Java, so unit testing makes sense because - well, you actually have a unit - a class. But the Python class does not necessarily coincide with the Java class, and the way to use Python as a scripting language is more functional than OOP. So what are you "unit test" in Python? Flow?

Thanks!

+4
source share
4 answers

Python has a unit test module that I like. You can also read the unit test section of the Dive Into Python.

Here is a basic example from the (related) documentation:

import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def test_shuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) # should raise an exception for an immutable sequence self.assertRaises(TypeError, random.shuffle, (1,2,3)) def test_choice(self): element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ == '__main__': unittest.main() 
+9
source

If you are doing functional programming, then this is a function, and I would recommend unit test your functions

+5
source

For quick and easy testing, you may need to doctests .

To write tests, you put things that look like interactive interpreter sessions in a docstring:

 def my_function(n): """Return n + 5 >>> my_function(500) 505""" return n + 5 

to run the test, you import doctest and run doctest.testmod() , which will run all the subsidies in the module. You can also use doctest.testfile("...") to run all the tests in some other file.

If you check the documentation for doctrines , you will find ways to make tests the expected exceptions, lists, etc. - all that the interpreter displays, plus a few wildcards for brevity.

This is a quick way to write tests in Python modules, there is not much template code, and IMO is easier to keep them up to date (the test is right there in the function!). But I also find them a little ugly.

+5
source

I wrote a post about unit testing in IronPython - it works the same as in other Python flavors.

See also these projects:

+3
source

Source: https://habr.com/ru/post/1304743/


All Articles