How to test (using unittest) the HTML output of a Django view? - python

I'm writing unit tests for my Django application. However, I don't know how to test the HTML output of a view.
Sometimes I might want to check if a specific element contains certain value, or how many of those elements are displayed, or things like that. How can I do such tests?
I would like a solution that uses unittest and django's own django.test.
I know I can use Selenium or Pyccuracy (which uses Selenium), but Selenium tests are quite slow because of the huge overhead of launching a browser. Also, unit tests work out-of-the-box with django-coverage package.

I've always found a combination of BeautifulSoup, and assertContains and assertFormError from TestCase's available assertions to do the trick.

These other answers are now out of date regarding assertions. The assertion assertHTMLEqual (since Django 1.4) takes care of things like ignoring whitespace, and ignoring the order of attributes.
For example (from the docs):
from django.test import TestCase
class MyTest(TestCase):
def test_some_html(self):
# A passing test that doesn't raise an AssertionError.
self.assertHTMLEqual(
'<input type="checkbox" checked="checked" id="id_accept_terms" />',
'<input id="id_accept_terms" type="checkbox" checked>'
)
In practice, one of the arguments to assertHTMLEqual would be dynamically generated.

Django's test framework is ideal for this.
Check the status code and content.
http://docs.djangoproject.com/en/1.2/topics/testing/#django.test.TestCase.assertContains
Check the template. http://docs.djangoproject.com/en/1.2/topics/testing/#django.test.TestCase.assertTemplateUsed
Also, it helps to use id="something" tags within your HTML to make it easier to find things when unit testing. We have tests like this.
def should_find_something( self ):
response= self.client.get( "/path/to/resource/pk/" )
self.assertContains( response, '<td id="pk">the pk string</td>', status_code=200 )
self.assertTemplateUsed( response, 'appropriate_page.html' )
Works nicely.

Have a look at Django with asserts - which uses lxml.
https://django-with-asserts.readthedocs.org/en/latest/

Here is the solution with BeautifulSoup:
import bs4 as bs
class HtmlTestMixin:
maxDiff = None
def assertElementContains(self, request_content, html_element="", html_selectors={}, element_text=""):
soup = bs.BeautifulSoup(request_content, "html.parser")
element = soup.find(html_element, **html_selectors)
soup_1 = bs.BeautifulSoup(element_text, "html.parser")
self.assertEqual(str(element.prettify()), soup_1.prettify())
It can be called like:
self.assertElementContains(
response.content,
"select",
{"id": "order-model"},
'''
<select name="order" id="order-model" class="form-select">
<option value="_score" >
Score
</option>
</select>
''',
)

Related

Selenium/Python - Class name with spaces unable to local element

I'm having trouble locating an element. I'm trying to locate it and enter some data into the field. I notice that the class name has spaces and ID is generated automatically (compare these to other forms) so can't use the ID for the automation as I want to automate this to create new forms and will be using the 'Description' field every time.
Below is the html for the Description field, which I'm trying to locate.
<input size="15" maxlength="255" class="acitem description s-description ui-autocomplete-input" spinner="/assets/spinner-48c6e73f2bbe9ea753f7f8e5410541a8138d19d657ddd532b2765335ed3d62bf.gif" auto_complete="true" data-autocomplete-url="/items/auto_complete" data-autocomplete-renderer="item_autocomplete_renderer" data-autocomplete-delay="250" type="text" name="invoice[invoice_lines_attributes][68345][description]" id="invoice_invoice_lines_attributes_68345_description" autocomplete="off">
The codes that I'm using so far has failed.
test_1 = driver.find_element_by_css_selector('.acitem.description.s-description.ui-autocomplete-input')
test_1.send_keys("HELLO WORLD")
test_2 = driver.find_element_by_css_selector("input[class='acitem description s-description ui-autocomplete-input']")
test_2.send_keys("HELLO WORLD")
test_3 = Select(driver.find_element_by_xpath("//*[#class='acitem description s-description ui-autocomplete-input']"))
test_3.send_keys("HELLO WORLD")
Did I got the code wrong or is there some workaround with the class name that has spaces? Thanks.
Thanks for all your help. I solved by using start-with and contains.
Below is my code.
invc_desc =driver.find_element_by_xpath("//input[starts-with(#class,'acitem') and contains(#class,'s-description')]")
invc_desc.clear()
invc_desc.send_keys("HELLO WORLD")
Try with xpath
//input[starts-with(#id,'invoice_invoice_lines_attributes_')]
I almost all the cases, all the elements from the DOM can be accessed via XPATH.
In your case I would go with the following:
element = driver.find_element_by_xpath("//input[#id='acitem description s-description ui-autocomplete-input']")

How to control my webapp with Alexa

I built an alexa skill using Python with Flask_ask, which goes to my DB and retrieves information that I need and spells it out.
I am now trying to create a web UI which would have an option of asking the required question by typing it in or speaking directly to alexa. The web UI works easily as it redirects to the page I want as below :
#app.route('/getdog')
def getdog():
return render_template('mypage.html')
Ideally I would configure an intent which would trigger the change in webpage e.g.
#ask.intent('myintent')
def changepage():
getdog()
Any ideas how to handle this?
You can use use a simple HTML form with a text input box:<form method="POST" action="/changepage/">
Enter Your Query: <input type="text" name="intent_string" />
<input type="submit" value="Ask Alexa"/>
</form>
Your changepage url should call a method which handles calling other intents based on whatever string has been passes in the POST request.
If you not able to exactly match the required intent to call you can add a full text search and match with that

How to display html from the controller in the view using Web2Py?

I'm utilizing web2py and I'd like to display html code that is returned from a python function in the controller.
I have the following controller (default.py):
def index():
return {"html_code":"<img src='https://static1.squarespace.com/static/54e8ba93e4b07c3f655b452e/t/56c2a04520c64707756f4267/1493764650017'>"}
This is my view (index.html):
{{=html_code}}
When I visit the site (http://127.0.0.1:8000/test/default/index), I see the following (instead of the image)
<img src='https://static1.squarespace.com/static/54e8ba93e4b07c3f655b452e/t/56c2a04520c64707756f4267/1493764650017'>
How can I render the variable called html_code as html instead of as plain text?
By default, any content written to the view via {{=...}} is escaped. To suppress the escaping, you can use the XML() helper:
{{=XML(html_code)}}
Alternatively, you can construct the HTML via the server-side HTML helpers rather than generating raw HTML:
def index():
return {"html_code": IMG(_src='https://static1.squarespace.com/static/54e8ba93e4b07c3f655b452e/t/56c2a04520c64707756f4267/1493764650017')}
And then you can leave the view as you have it:
{{=html_code}}
The above assumes that you are generating the HTML via your own code. If the HTML in question comes from an untrusted source (e.g., user input), writing it to the view without escaping presents a security risk. In that case, you can have the XML() helper doing some sanitizing (i.e., it will limit the allowed HTML tags and attributes to a safe whitelist) (see here for more details):
{{=XML(html_code, sanitize=True)}}
try use XML() helper
def index():
return {"html_code":XML("<img src='https://static1.squarespace.com/static/54e8ba93e4b07c3f655b452e/t/56c2a04520c64707756f4267/1493764650017'>")}

Generating HTML documents in python

In python, what is the most elegant way to generate HTML documents. I currently manually append all of the tags to a giant string, and write that to a file. Is there a more elegant way of doing this?
You can use yattag to do this in an elegant way. FYI I'm the author of the library.
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('html'):
with tag('body'):
with tag('p', id = 'main'):
text('some text')
with tag('a', href='/my-url'):
text('some link')
result = doc.getvalue()
It reads like html, with the added benefit that you don't have to close tags.
I would suggest using one of the many template languages available for python, for example the one built into Django (you don't have to use the rest of Django to use its templating engine) - a google query should give you plenty of other alternative template implementations.
I find that learning a template library helps in so many ways - whenever you need to generate an e-mail, HTML page, text file or similar, you just write a template, load it with your template library, then let the template code create the finished product.
Here's some simple code to get you started:
#!/usr/bin/env python
from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django
# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""
t = Template(template)
c = Context({"title": "title from code",
"mystring":"string from code"})
print t.render(c)
It's even simpler if you have templates on disk - check out the render_to_string function for django 1.7 that can load templates from disk from a predefined list of search paths, fill with data from a dictory and render to a string - all in one function call. (removed from django 1.8 on, see Engine.from_string for comparable action)
If you're building HTML documents than I highly suggest using a template system (like jinja2) as others have suggested. If you're in need of some low level generation of html bits (perhaps as an input to one of your templates), then the xml.etree package is a standard python package and might fit the bill nicely.
import sys
from xml.etree import ElementTree as ET
html = ET.Element('html')
body = ET.Element('body')
html.append(body)
div = ET.Element('div', attrib={'class': 'foo'})
body.append(div)
span = ET.Element('span', attrib={'class': 'bar'})
div.append(span)
span.text = "Hello World"
if sys.version_info < (3, 0, 0):
# python 2
ET.ElementTree(html).write(sys.stdout, encoding='utf-8',
method='html')
else:
# python 3
ET.ElementTree(html).write(sys.stdout, encoding='unicode',
method='html')
Prints the following:
<html><body><div class="foo"><span class="bar">Hello World</span></div></body></html>
There is also a nice, modern alternative: airium: https://pypi.org/project/airium/
from airium import Airium
a = Airium()
a('<!DOCTYPE html>')
with a.html(lang="pl"):
with a.head():
a.meta(charset="utf-8")
a.title(_t="Airium example")
with a.body():
with a.h3(id="id23409231", klass='main_header'):
a("Hello World.")
html = str(a) # casting to string extracts the value
print(html)
Prints such a string:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8" />
<title>Airium example</title>
</head>
<body>
<h3 id="id23409231" class="main_header">
Hello World.
</h3>
</body>
</html>
The greatest advantage of airium is - it has also a reverse translator, that builds python code out of html string. If you wonder how to implement a given html snippet - the translator gives you the answer right away.
Its repository contains tests with example pages translated automatically with airium in: tests/documents. A good starting point (any existing tutorial) - is this one: tests/documents/w3_architects_example_original.html.py
I would recommend using xml.dom to do this.
http://docs.python.org/library/xml.dom.html
Read this manual page, it has methods for building up XML (and therefore XHTML). It makes all XML tasks far easier, including adding child nodes, document types, adding attributes, creating texts nodes. This should be able to assist you in the vast majority of things you will do to create HTML.
It is also very useful for analysing and processing existing xml documents.
Here is a tutorial that should help you with applying the syntax:
http://www.postneo.com/projects/pyxml/
I am using the code snippet known as throw_out_your_templates for some of my own projects:
https://github.com/tavisrudd/throw_out_your_templates
https://bitbucket.org/tavisrudd/throw-out-your-templates/src
Unfortunately, there is no pypi package for it and it's not part of any distribution as this is only meant as a proof-of-concept. I was also not able to find somebody who took the code and started maintaining it as an actual project. Nevertheless, I think it is worth a try even if it means that you have to ship your own copy of throw_out_your_templates.py with your code.
Similar to the suggestion to use yattag by John Smith Optional, this module does not require you to learn any templating language and also makes sure that you never forget to close tags or quote special characters. Everything stays written in Python. Here is an example of how to use it:
html(lang='en')[
head[title['An example'], meta(charset='UTF-8')],
body(onload='func_with_esc_args(1, "bar")')[
div['Escaped chars: ', '< ', u'>', '&'],
script(type='text/javascript')[
'var lt_not_escaped = (1 < 2);',
'\nvar escaped_cdata_close = "]]>";',
'\nvar unescaped_ampersand = "&";'
],
Comment('''
not escaped "< & >"
escaped: "-->"
'''),
div['some encoded bytes and the equivalent unicode:',
'你好', unicode('你好', 'utf-8')],
safe_unicode('<b>My surrounding b tags are not escaped</b>'),
]
]
I am attempting to make an easier solution called
PyperText
In Which you can do stuff like this:
from PyperText.html import Script
from PyperText.htmlButton import Button
#from PyperText.html{WIDGET} import WIDGET; ex from PyperText.htmlEntry import Entry; variations shared in file
myScript=Script("myfile.html")
myButton=Button()
myButton.setText("This is a button")
myScript.addWidget(myButton)
myScript.createAndWrite()
I wrote a simple wrapper for the lxml module (should work fine with xml as well) that makes tags for HTML/XML -esq documents.
Really, I liked the format of the answer by John Smith but I didn't want to install yet another module to accomplishing something that seemed so simple.
Example first, then the wrapper.
Example
from Tag import Tag
with Tag('html') as html:
with Tag('body'):
with Tag('div'):
with Tag('span', attrib={'id': 'foo'}) as span:
span.text = 'Hello, world!'
with Tag('span', attrib={'id': 'bar'}) as span:
span.text = 'This was an example!'
html.write('test_html.html')
Output:
<html><body><div><span id="foo">Hello, world!</span><span id="bar">This was an example!</span></div></body></html>
Output after some manual formatting:
<html>
<body>
<div>
<span id="foo">Hello, world!</span>
<span id="bar">This was an example!</span>
</div>
</body>
</html>
Wrapper
from dataclasses import dataclass, field
from lxml import etree
PARENT_TAG = None
#dataclass
class Tag:
tag: str
attrib: dict = field(default_factory=dict)
parent: object = None
_text: str = None
#property
def text(self):
return self._text
#text.setter
def text(self, value):
self._text = value
self.element.text = value
def __post_init__(self):
self._make_element()
self._append_to_parent()
def write(self, filename):
etree.ElementTree(self.element).write(filename)
def _make_element(self):
self.element = etree.Element(self.tag, attrib=self.attrib)
def _append_to_parent(self):
if self.parent is not None:
self.parent.element.append(self.element)
def __enter__(self):
global PARENT_TAG
if PARENT_TAG is not None:
self.parent = PARENT_TAG
self._append_to_parent()
PARENT_TAG = self
return self
def __exit__(self, typ, value, traceback):
global PARENT_TAG
if PARENT_TAG is self:
PARENT_TAG = self.parent

Un/bound methods in Cheetah

Is there a way to declare static methods in cheetah? IE
snippets.tmpl
#def address($address, $title)
<div class="address">
<b>$title</h1></b>
#if $address.title
$address.title <br/>
#end if
$address.line1 <br/>
#if $address.line2
$address.line2 <br/>
#end if
$address.town, $address.state $address.zipcode
</div>
#end def
....
other snippets
other.tmpl
#from snippets import *
$snippets.address($home_address, "home address")
This code reports this error: NotFound: cannot find 'address'. Cheetah is compiling it as a bound method, natch:
snippets.py
class snippets(Template):
...
def address(self, address, title, **KWS):
Is there a way to declare static methods? If not, what are some alternative ways to implement something like this (a snippets library)?
This page seems to have some relevant information, but I'm not in a position to try it out myself right now, sorry.
Specifically, you should just be able to do:
##staticmethod
#def address($address, $title)
...and have it work.
(If you didn't know, staticmethod is a built-in function that creates a... static method :) It's most commonly used as a decorator. So I found that page by Googling "cheetah staticmethod".)

Categories