Continuing in Python's unittest when an assertion fails

前端 未结 12 1555
感情败类
感情败类 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:35

    One option is assert on all the values at once as a tuple.

    For example:

    class CarTest(unittest.TestCase):
      def test_init(self):
        make = "Ford"
        model = "Model T"
        car = Car(make=make, model=model)
        self.assertEqual(
                (car.make, car.model, car.has_seats, car.wheel_count),
                (make, model, True, 4))
    

    The output from this tests would be:

    ======================================================================
    FAIL: test_init (test.CarTest)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "C:\temp\py_mult_assert\test.py", line 17, in test_init
        (make, model, True, 4))
    AssertionError: Tuples differ: ('Ford', 'Ford', True, 3) != ('Ford', 'Model T', True, 4)
    
    First differing element 1:
    Ford
    Model T
    
    - ('Ford', 'Ford', True, 3)
    ?           ^ -          ^
    
    + ('Ford', 'Model T', True, 4)
    ?           ^  ++++         ^
    

    This shows that both the model and the wheel count are incorrect.

提交回复
热议问题