Sunday, October 28, 2012

doctest for python class

You can class test with doctest. One issue to consider is to create object to test the method. This is an example.
"""
This is the "iniFileGenerator" module.

>>> f = iniFileGenerator()
>>> f.get()
hello
"""
class iniFileGenerator:
    def __ini__(self, hintFilePath):
        self.hintFilePath = hintFilePath
    def get(self):
        """
        >>> iniFileGenerator().get()
        hello
        """
        print "hello"
        
if __name__ == "__main__":
    import doctest
    doctest.testmod()
No news is good news, if you want to get the test result you need to use command line.
refactoringChecker> python iniFileGenerator.py -v
Trying:
    f = iniFileGenerator()
Expecting nothing
ok
Trying:
    f.get()
Expecting:
    hello
ok
Trying:
    iniFileGenerator().get()
Expecting:
    hello
ok
2 items had no tests:
    __main__.iniFileGenerator
    __main__.iniFileGenerator.__ini__
2 items passed all tests:
   2 tests in __main__
   1 tests in __main__.iniFileGenerator.get
3 tests in 4 items.
3 passed and 0 failed.
Test passed.

Reuse testing class objects

When testing class, you want to use the same object multiple times throughout the method testing. In this case, you can use extra globs dictionary.
"""
This is the "iniFileGenerator" module.
>>> print f.hintFilePath
./tests/unit_test_files/hint.txt
"""
class iniFileGenerator:
    def __init__(self, hintFilePath):
        self.hintFilePath = hintFilePath
    def hello(self):
        """
        >>> f.hello()
        hello
        """
        print "hello"
if __name__ == "__main__":
    import doctest
    hintFile = "./tests/unit_test_files/hint.txt"
    doctest.testmod(extraglobs={'f': iniFileGenerator(hintFile)})

Reference

1 comment:

  1. The knowledge of python is very essential for the software developers. Python is a high level, general purpose, dynamic programming language that is of code readability and its synatx allows programmers to express the concept in fewer lines of code.
    python training in chennai | python training institutes in chennai

    ReplyDelete