Correct structure for many test cases in Python with unittest

I am considering a package unittest, and I am not sure of the correct way to structure my test cases when writing many of them for the same method. Say I have a function factthat calculates the factorial of a number; will this test file be okay?

import unittest

class functions_tester(unittest.TestCase):
    def test_fact_1(self):
        self.assertEqual(1, fact(1))
    def test_fact_2(self):
        self.assertEqual(2, fact(2))
    def test_fact_3(self):
        self.assertEqual(6, fact(3))
    def test_fact_4(self):
        self.assertEqual(24, fact(4))
    def test_fact_5(self):
        self.assertFalse(1==fact(5))
    def test_fact_6(self):
        self.assertRaises(RuntimeError, fact, -1)
        #fact(-1)

if __name__ == "__main__":
    unittest.main()

It seems sloppy to have so many testing methods for one method. I would like to have only one testing method and put a ton of the main test cases (for example, 4! == 24, 3! == 6, 5! == 120, etc.), but unittest does not allow you to do this.

What is the best way to structure a test file in this scenario?

Thanks in advance for your help.

+3
3

:

def test_fact(self):
    tests = [(1,1), (2,2), (3,6), (4,24), (5,120)]
    for n,f in tests:
        self.assertEqual(fact(n), f)
+6

, , , ( ).

, interjay, (, , , unittest , ). , . , , , , .

, (, 1 5), , , . , 10, 100, 1000 (.. ), , ..

, . . (5) ( , ). , .

def test_fact_5(self):
    self.assertFalse(1==fact(5))

: "test_fact_6" , (6). - "test_fact_minus_one" , , "test_fact_negative_number".

def test_fact_6(self):
    self.assertRaises(RuntimeError, fact, -1)

, , .

+5

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


All Articles