Chapter 1. Using Unittest To Develop Basic Tests

In this chapter, we will cover:

  • Asserting the basics
  • Setting up and tearing down a test harness
  • Running test cases from the command line
  • Running a subset of test case methods
  • Chaining together a suite of tests
  • Defining test suites inside the test case
  • Retooling old test code to run inside unittest
  • Breaking down obscure tests into simple ones
  • Testing the edges
  • Testing corner cases by iteration

Introduction

Testing has always been a part of software development. However, the world was introduced to a new concept called automated testing when Kent Beck and Erich Gamma introduced JUnit for Java development (http://junit.org). It was based on Kent's earlier work with Smalltalk and automated testing (http://www.xprogramming.com/testfram.htm). In this day and age, automated testing has become a well-accepted concept in the software industry.

A Python version, originally dubbed PyUnit, was created in 1999 and added to Python's standard set of libraries later in 2001 in Python 2.1 (http://docs.python.org/library/unittest.html). Since then, the Python community referred to it as unittest, the name of the library imported into the test code.

Unittest is the foundation of automated testing in the Python world. In this chapter, we will explore the basics of testing and asserting code functionality, building suites of tests, test situations to avoid, and finally testing edges, and corner cases.

For all the recipes in this chapter, we will use virtualenv (http://pypi.python.org/pypi/virtualenv) to create a controlled Python runtime environment. Unittest is part of the standard library, which requires no extra installation steps. But, in later chapters, using virtualenv will allow us to conveniently install other test tools without cluttering up our default Python installation.

  1. To install virtualenv, either download it from the site mentioned previously, or if you have easy_install, just type: easy_install virtualenv.

    Note

    For some systems, you may need to install it either as root or by using sudo

  2. After installing virtualenv, use it to create a clean environment named ptc (an abbreviation used for Python Testing Cookbook) by using --no-site-packages.
  3. Activate the virtual Python environment. This can vary, depending on which shell you are using.
    Introduction
  4. Finally, verify that the environment is active by checking the path of pip.

    Tip

    For more information on the usage and benefits of virtualenv, please read http://iamzed.com/2009/05/07/a-primer-on-virtualenv.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.254.90