[Django]-Django assert that response contains one of a list of possible strings

3👍

Try this:

if not any([x in response.content for x in NO_FOLLOWERS_MESSAGES]):
        raise AssertionError("Did not match any of the messages in the request")

About any(): https://docs.python.org/2/library/functions.html#any

2👍

Would something like this work?

found_quip = [quip in response.content for quip in NO_FOLLOWERS_MESSAGES]
self.assertTrue(any(found_quip))

2👍

Internally assertContains(), uses the count from _assert_contains()

So if you want to preserve exactly the same behavior as assertContains(), and given that the implementation of _assert_contains() isn’t a trivial one, you can get inspiration from the source code above and adapt one for your needs

Our assertContainsAny() inspired by assertContains()

def assertContainsAny(self, response, texts, status_code=200,
                      msg_prefix='', html=False):

    total_count = 0
    for text in texts:
        text_repr, real_count, msg_prefix = self._assert_contains(response, text, status_code, msg_prefix, html)
        total_count += real_count

    self.assertTrue(total_count != 0, "None of the text options were found in the response")

Use by passing the argument texts as a list, e.g.

self.assertContainsAny(response, NO_FOLLOWERS_MESSAGES)
👤bakkal

Leave a comment