setUp and tearDown

Date: January 17th 2016
Last updated: January 17th 2016

setUp and tearDown methods are used to isolate processes not being tested. In addition, setUp and tearDown methods allow multiple test functions to be re-factored.

Assuming the previous file structure:

├── test
│   ├──
│   ├── sentence.txt                # add test file 
│   ├──      # copy of unittest test_vowels
│   ├──
│   └──
└── vowels

Add sentence.txt to test directory:

This is a test.
The is the second line of testing.
And the third... etc etc

Copy and modify the unittest function to

This module tests setup and teardown methods. 
Test function writen using unittest module.
import unittest
from vowels import vowels

class VowelsTest(unittest.TestCase):
    # setUp gets processed first
    # open up the required file
    def setUp(self):
        print "<--- opening file --->"
        self.file = open("test/sentence.txt", "r")
        # get the first line
        self.lines = self.file.readline()
        # Returns: 'This is a test.\n'        
        # more processing can happen in here too...
        self.sentence = self.lines.split('\n')[0]
        # Returns: 'This is a test.'

    # tearDown gets processed last
    # close the text file
    def tearDown(self):
        print "<--- closing file --->"

    # functions process in the middle between setUp and tearDown
    # same function as before: slightly modified

    def testNormalCase(self):
        # replace "this is a test" to self.sentence
        self.assertEqual(vowels.count_vowels(self.sentence), 4)
        #self.assertEqual(vowels.count_vowels('this is a test'), 4)

if __name__ == '__main__':

Run with any test module:

# Run from Project folder
cd Project
# unittest
python -m unittest test.test_setup_teardown
# nose
nosetests -vv test/
# pytest
py.test -vv -s test/

Output from pytest:

results matching ""

    No results matching ""