Python 3 How to: Write Unit tests (PyUnit, pytest, nose)

In the following blog post I’ll cover the following frameworks for unit testing.

1) PyUnit, also known as unittest in the Python modules.
2) Pytest – a mature full-featured Python testing tool that helps you write better programs.
3) Nose – a nicer testing for Python? It’s more like a unit test loader since it supports all the above for loading.

How to get them?

1) PyUnit – already installed for you. Just import unittest in your unit tests file

2) Pytest – devs guide -> here

3) Nose – devs guide -> here

 

Get to know TDD:

TDD – Test-Driven Development or also known as Red, Green and Refactor. Can be explained simple in a image.

TDD

 

How to start writing tests with PyUnit:

1) Import unittest

2) Import the code you want to test

3) Create a class that inherits  from unittest.TestCase

4) Create methods for the class you created that MUST start with test

5) Run the tests with the python3 interpreter in the console or your IDE

 

Useful methods to know (framework’s API)

Unit test source code

And when run in the terminal

Terminal PyUnit

 

 

How to start writing tests with Pytest:

1) Install pytest

2) Import the  code you want to test

3) Write test functions, it’s optional to create a class with methods.

4) Run the tests with py.test in the console

 

For Pytest all you need to know is how Python 3’s assert works.  Read a little more about Pytest and assert

Unit test source code (framework’s API)

And when run in the terminal

Terminal pytest

 

How to start writing tests with Nose:

1) Install nose

2) Import the  code you want to test

3) Import nose.tools

4) Create a class that starts wtih Test

5) Create tests (methods) that start with test

6) Run the test with nosetests in the console

 

Useful methods  to know . (framework’s API)

Most of the time you’ll use:

*  ok_ which is a short-hand for assert

*  eq_ which is (a, b) and tests if a == b

Unit test source code

And when run in the terminal

Terminal Nose

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s