Fallenreaper
Fallenreaper

Reputation: 10704

Testing Flask methods which return a render_template

I have looked into a bunch of different options, but since Python is really as dynamic as we want it to be, I wanted to ask here.

When doing unit tests, it allows me to mock data and test functionality for expected and unexpected results. I noticed that there are a large number of functions in the app i am working on which are Flask Routes, which return render_templated data. Not bad, I am used to that. The issue here is that I wanted to mock data and test those endpoints. I saw there are some options though. When looking on github, i noticed a no-longer-maintained tool flask-testing is no longer maintained it seems. Test Flask render_template() context

I was thinking this would be useful to touch the context to see the resulting data, which is more important than the rendered template to me. That way, I could control inputs and test the resulting dataset.

Is there something that is in unittest or other that is up to date? If this doesn't work, I guess I could just parse the HTML if i know where the data is for it, but it seems a bit bulky to me to just ensure the data passed into render_template is right or wrong.

What is the way people do this normally? parse resulting html for the data you need, or is there a way to mock and obtain the context of the result in order to verify. I have been looking through base docs for unittest and have yet to find anything.

Upvotes: 0

Views: 1530

Answers (1)

Jürgen Gmach
Jürgen Gmach

Reputation: 6121

I just parse the HTML. This makes sure both the data is there (and correct) and the page gets rendered correctly.

If you have a complex function, I'd just extract it out of the view function and unit test it directly.

I am not convinced that mocking would be a great idea here, so I do not mention that you could mock "render_template" itself :-)

Upvotes: 2

Related Questions