Frappe Framework: Unittest

Leonardo Augusto
2 min readSep 23, 2019

--

Tests passing reaction

As developers, we need to sharpen our skills to ensure product quality. For this, automated testing is one of the key features we have to use.

This time, let’s see how to test DocType form fields.

Your app folder tree must be something like that:

├── nota_fiscal
│ ├── config
│ │ ├── desktop.py
│ │ ├── docs.py
│ │ ├── __init__.py
│ ├── hooks.py
│ ├── __init__.py
│ ├── modules.txt
│ ├── nota_fiscal
│ │ ├── doctype
│ │ │ ├── __init__.py
│ │ │ ├── nfe
│ │ │ │ ├── __init__.py
│ │ │ │ ├── nfe.js
│ │ │ │ ├── nfe.json
│ │ │ │ ├── nfe.py
│ │ │ │ ├── test_nfe.js
│ │ │ │ └── test_nfe.py
│ ├── patches.txt
│ ├── public
│ │ ├── css
│ │ └── js
│ ├── templates
│ │ ├── includes
│ │ ├── __init__.py
│ │ ├── pages
│ │ │ ├── __init__.py
│ └── www
├── README.md
├── requirements.txt
└── setup.py

The important thing here is the test_doctypename.py file. This file comes pre-configured with basics resources: frappe and unittest modules.

The test code:

def required_fields():
return ['natureza_operacao','data_emissao','data_entrada_saida',
'tipo_documento', 'finalidade_emissao', 'cnpj_emitente']
class TestNFe(unittest.TestCase):
def setUp(self):
self.doc = frappe.new_doc('NFe')
def test_form_fields(self):
"""Validate expected form fields"""
fields = required_fields()
for field in fields:
with self.subTest():
self.assert_(field in str(self.doc.as_dict()),
msg='Field "{}" does not exist on NFe DocType'.format(field))

What does this code do?

First, we’ve created a method that returns a list of field names(our required fields).

Then, inside test class, we’ve defined a setup method that set self.doc equals to a new document.

To validate form fields, the test_form_fields method will do the job. The method iterate our required fields and then fall to self.subTest(). This method stores all of assertionErrors until for loop ends, and then, all assertionErrors are showed up in the terminal.

self.assert_() is a little more complicated, that compares if field(for loop value) is in str(self.doc.as_dict()), if not, this will return our custom message inside the msg parameter.

--

--