Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing in python? [closed]

Hey - I'm new to python , and I'm having a hard time grasping the concept of Unit testing in python.

I'm coming from Java - so unit testing makes sense because - well , there you actually have a unit - A Class. But a Python class is not necessarily the same as a Java class , and the way I use Python - as a scripting language - is more functional then OOP - So what do you "unit test" in Python ? A flow?

Thanks!

like image 917
Yossale Avatar asked Nov 30 '22 06:11

Yossale


1 Answers

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

Heres a basic example from the (linked) 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()
like image 80
Mizipzor Avatar answered Dec 05 '22 03:12

Mizipzor