Twi
Twi

Reputation: 825

Conditional assertion in Python

I have a response from a WS which returns a dictionary of the list. In general, I need to check if none of the lists is empty from the dictionary. However now I need to check some of them, but not all of them, based on the condition.

For example: The result is:

{
    'firstList': [{...}], #some data in the list
    'secondList': [], #empty list
    'thirdList': [{...}], #some data in the list
    ...
}

So for example, if I have a condition, that the secondList shouldn't be checked with

assert len(response['secondList']) > 0

Then it shouldn't raise an exception, but if I don't have it in the condition, then it should raise an assertion exception.

Any idea what is the best solution for this problem? Maybe another assertion library?

The best would've been to collect all of the exceptions in the end then I could validate them if they are ok/nok.

Upvotes: 2

Views: 7296

Answers (2)

asikorski
asikorski

Reputation: 922

There are several ways but one that is quite clean would be:

lists_to_check = ('firstList', 'thirdList')
for list_name in lists_to_check:
    assert len(response[list_name]) > 0

If you want to check them one by one you can also use something like:

assert condition1 or len(response['firstList']) > 0
assert condition3 or len(response['thirdList']) > 0

but I would use the first one anyway. The above snippets only check the length of the 'firstList' and 'thirdList'.

Upvotes: 5

Guy
Guy

Reputation: 50809

You can add the condition to the assert

assert condition or len(response['secondList']) > 0

The assertion will pass if atleast one of the conditions is True.

Upvotes: 2

Related Questions