jinja add tag
I have a script that will generate html using Jinja.

<!-- more html here -->
<ul id="someList">
  <li>Item 1</li>
  <li>Item 2</li>
<!-- more html here, too -->

I would like to make assertions like "assert that the html string has #someList and has 2 items: Item 1 and Item 2." without resorting to substring checking. e.g. 

assert 'ul id="someList"' in renderedHtml
assert 'Item 1' in renderedHtml
assert 'Item 2' in renderedHtml


I imagine something like,

parsedHtml = parse(renderedHtml)
assert someList := parsedHtml.findBySelector("ul#someList")
assert someList.contains("Item 1")
assert someList.contains("Item 2")

Is installing an additional dependency (e.g. BeautifulSoup) an  appropriate way to go about this?

Or does Jinja have a built-in functionality to help with these kinds of tests? I also use `pytest` if that matters.
Top Answer
There is nothing in Jinja. Although it is used for HTML in most cases, it can be used for any text based target, so having something for unit testing specifically would be a bit opinionated anyway IMHO.

So you could use any HTML parser to make sense of the rendered template within unit tests.

    soup = bs4.BeautifulSoup(rendered_html, "html.parser")
    list_node = soup.select_one("ul#someList")
    assert list_node is not None

    item_texts = list(list_node.stripped_strings)
    assert "Item 1" in item_texts
    assert "Item 2" in item_texts
    # or
    assert list(list_node.stripped_strings) == ["Item 1", "Item 2"]

This room is for discussion about this question.

Once logged in you can direct comments to any contributor here.

Enter question or answer id or url (and optionally further answer ids/urls from the same question) from

Separate each id/url with a space. No need to list your own answers; they will be imported automatically.