Improving tests with any()

There are many gems inside the standard library of Python and I think the slogan batteries included is a great choice. But not many are that known and sometimes features get re-implemented because the function from the stdlib is not known.

While refactoring some tests I found code like the following:

found = False
for line in result:
    if line.strip():
        if 'admin users' in line:
            found = True
            break

self.assertTrue(found, 'Missing Admin Users in Share opsi_depot')

That is a lot of code to check if a line with some required text is inside the iterable result.

This brings us to todays gem any()! If any item of the iterable passed to any is truth-y then the function returns True. If the iterable is empty or no truthy value is found we get a False.

With this knowledge we can shorten the test code to the following:

self.assertTrue(any('admin users' in line for line in result if line.strip()), 'Missing Admin Users in Share opsi_depot')

I have been even going so far as to throw out the self.assertTrue coming from unittest.TestCase as this makes a conversion to a different test framework easier and the test is still nice to read.

We can also remove the check if the line is filled (line.split()) because there is no chance of a false positive introduced by this.

Now we end up with this:

assert any('admin users' in line for line in result), 'Missing Admin Users in Share opsi_depot'

And if you ever want to check if all values in an iterable are truth-y you should check out the function all!