[Answer]-Django tests: Test that a certain number of elements appear in page?

1👍

assertContains() has a count option built in:

assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)

If count is provided, text must occur exactly count times in the response.

Therefore, you can use:

self.assertContains(response, '</li>', 4)

0👍

I’d use BeautifulSoup to achieve this. Something along the lines of:

def test_call_view_bnf_all(self):
    response = self.client.get('/bnf/')
    response_soup = BeautifulSoup(response.content)

    li_elements = response_soup.find_all('li')
    self.assertEqual(len(li_elements), 4)

0👍

I’ve been using PyQuery to do this kind of stuff. Basically, you’d end up writing a jquery selector and then testing the result. The nice thing, being jquery-compatible is that you can test your selector in your browser first.

Pretty happy with PyQuery so far, except that it has an lxml dependency which I have found is challenging to install with Chef.

data = PyQuery(response.content)
result = data("li")

#haven't used PyQuery to check the length of a result yet
#might be
self.assertEqual(4,len(result))

Leave a comment