15.12.2022 Views

Python Eficaz

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

A maneira mais simples de escrever testes é usar o módulo nativo unittest. Por

exemplo, digamos que exista uma função utilitária definida no arquivo utils.py:

# utils.py

def to_str(data):

if isinstance(data, str):

return data

elif isinstance(data, bytes):

return data.decode('utf-8')

else:

raise TypeError('Must supply str or bytes, '

'found: %r' % data)

Para definir os testes, crio um segundo arquivo chamado test_utils.py ou

utils_test.py, que contém testes para cada comportamento esperado.

# utils_test.py

from unittest import TestCase, main

from utils import to_str

class UtilsTestCase(TestCase):

def test_to_str_bytes(self):

self.assertEqual('hello', to_str(b'hello'))

def test_to_str_str(self):

self.assertEqual('hello', to_str('hello'))

def test_to_str_bad(self):

self.assertRaises(TypeError, to_str, object())

if __name__ == '__main__':

main()

Os testes são organizados em classes TestCase. Cada teste é um método

começando com a palavra test. Se um método de teste roda sem levantar nenhum

tipo de exceção (incluindo o AssertionError dos comandos assert), considera-se

que o teste teve sucesso, ou seja, passou sem encontrar erros.

www.full-ebook.com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!