Continuing in Python's unittest when an assertion fails

前端 未结 12 1553
感情败类
感情败类 2020-11-27 14:03

EDIT: switched to a better example, and clarified why this is a real problem.

I\'d like to write unit tests in Python that continue executing when an assertion fails

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 14:52

    Since Python 3.4 you can also use subtests:

    def test_init(self):
        make = "Ford"
        model = "Model T"
        car = Car(make=make, model=model)
        with self.subTest(msg='Car.make check'):
            self.assertEqual(car.make, make)
        with self.subTest(msg='Car.model check'):
            self.assertEqual(car.model, model)
        with self.subTest(msg='Car.has_seats check'):
            self.assertTrue(car.has_seats)
        with self.subTest(msg='Car.wheel_count check'):
            self.assertEqual(car.wheel_count, 4)
    

    (msg parameter is used to more easily determine which test failed.)

    Output:

    ======================================================================
    FAIL: test_init (__main__.CarTest) [Car.model check]
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "test.py", line 23, in test_init
        self.assertEqual(car.model, model)
    AssertionError: 'Ford' != 'Model T'
    - Ford
    + Model T
    
    
    ======================================================================
    FAIL: test_init (__main__.CarTest) [Car.wheel_count check]
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "test.py", line 27, in test_init
        self.assertEqual(car.wheel_count, 4)
    AssertionError: 3 != 4
    
    ----------------------------------------------------------------------
    Ran 1 test in 0.001s
    
    FAILED (failures=2)
    

提交回复
热议问题