How to check the order of appearance on django test

40 Views Asked by At

I use this sentences to check the letters line1 and line2 appears.

self.assertContains(response,"line1"); self.assertContains(response,"line2");

However I want to check the order of appearance.

I checked in this page, but can't figure out which I should use.

https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.SimpleTestCase.assertContains

2

There are 2 best solutions below

1
cadolphs On

Are you saying you want to assert that line 1 appears in the response before line2?

There isn't (probably; I haven't checked but would be quite surprised) a specific command that would assert that.

Instead, use find() to get the indices of where in the response line1 and line2 are found, then compare them.

EDIT: But be aware that if the content isn't found, find will return -1. A solution could be to first just use your assertContains to check that line1 and line2 are present, and after that use find() to verify that one comes before the other.

0
Bartosz Stasiak On

You can also try doing that with regex.

# This will match the line where "line1" appears first, then anything in between and then "line2".
regex_expression = r"line1.*line2"

self.assertRegex(response, regex)

If you don't like it then use .index() method.

self.assertContains(response,"line1")
self.assertContains(response,"line2")

line1_index = response.index("line1")
line2_index = response.index("line2")

self.assertTrue(line1_index < line2_index)