unittest

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Aug 15 08:39:47 EDT 2009


On Sat, 15 Aug 2009 07:32:15 -0400, Mag Gam wrote:

> So, in this example:
> 
> "import random"
> 
> In my case I would do "import foo" ? is there anything I need to do for
> that?


Suppose you have a file mymodule.py containing your code, and you want 
some unit tests. 

If you only have a few, you can probably put them inside mymodule.py, but 
let's say you have lots and want to keep them in a separate file. So 
create a new module mymoduletests.py, and start it like this:

# mymoduletests.py

import unittest
import mymodule

class MyTests(unittest.TestCase):  # Inherit from the TestCase class.
    # Put your tests inside this class
    def test_module_has_docstring(self):
        """Fail if the module has no docstring, or if it is empty."""
        docstring = mymodule.__doc__
        self.assert_(docstring is not None)
        self.assert_(docstring.strip() != '')

if __name__ == '__main__':
    # only execute this part when you run the module
    # not when you import it
    unittest.main()




Now to actually run the tests, from command-line, type:

python mymoduletests.py

and hit enter. (You do this from the operating system shell, not the 
Python interactive interpreter.) You should see something like this:

.
----------------------------------------------------------------------
Ran 1 tests in 0.001s

OK




-- 
Steven



More information about the Python-list mailing list