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:
Project
├── test
│ ├── __init__.py
│ ├── sentence.txt # add test file
│ ├── test_setup_teardown.py # copy of unittest test_vowels
│ ├── test_vowels_nose.py
│ └── test_vowels.py
└── vowels
├── __init__.py
├── vowelsclass.py
└── vowels.py
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 test_setup_teardown.py
#!bin/python2.7
# teset_setup_teardown.py
"""
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 --->"
self.file.close()
# 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__':
unittest.main()
Run with any test module:
# Run from Project folder
cd Project
# unittest
python -m unittest test.test_setup_teardown
# nose
nosetests -vv test/test_setup_teardown.py
# pytest
py.test -vv -s test/test_setup_teardown.py
Output from pytest: