Search code examples
pythonunit-testing

Is there a convention for throwing many similar error messages when unit tests fail?


I am writing unit tests, and am raising many similar error messsages to the point where the code looks very messy.

Something like this:

# Test that compare_pass1 is downstream to secondary_pass1
self.assertTrue(
    all(
        task in all_downstream_task_for_secondary_pass1_task
        for task in {compare_pass1}
    ),
    f'One of {compare_pass1} not found in downstream to {secondary_pass1_task task}',
)

# Check that primary_pass1 is upstream to secondary_pass1
self.assertTrue(
    all(
        task in all_upstream_task_for_secondary_pass1_task
        for task in {primary_pass1_task}
    ),
    f'One of {primary_pass1_task} not found in upstream to {secondary_pass1_task} task',
)
    
# Check that secondary_pass1 is upstream to compare_pass1
self.assertTrue(
    all(
        task in all_upstream_task_for_compare_pass1_task
        for task in {secondary_pass1_task}
    ),
    f'one of {secondary_pass1_task} not found in upstream to {compare_pass1_task} task',
)

What I am refering to is the error message that is thrown when a unit test fails, although they are not exactly the same, the message is similar.

Is there a convention of creating a function and calling the function when throwing the error messages?


Solution

  • You can use non-f-string formatting to define a string template that is then filled with variables:

    compare_pass1 = "foo"
    secondary_pass1_task = "bar"
    
    s = 'One of {} not found in downstream to {}'
    
    print(s.format(compare_pass1, secondary_pass1_task))
    
    compare_pass2 = "fee"
    secondary_pass2_task = "bas"
    
    print(s.format(compare_pass2, secondary_pass2_task))