views:

246

answers:

5

Hey - I'm new to python , and I'm having a hard time grasping the concept of Unit testing in python.

I'm coming from Java - so unit testing makes sense because - well , there you actually have a unit - A Class. But a Python class is not necessarily the same as a Java class , and the way I use Python - as a scripting language - is more functional then OOP - So what do you "unit test" in Python ? A flow?

Thanks!

A: 

Try using this site to get a handle on unit-testing in python

As for how you are testing, if you are using it as a primarily scripting language there is am much less need, at least in my opinion, of doing unit testing. For the use of python in more critical situations then unit test the functions you are writing.

Mimisbrunnr
+3  A: 

If you make functional programming then the unit is the function and I would recommend to unit test your functions

luc
+2  A: 

I wrote a post about unit testing in IronPython - it works same as in other Python flavors as well.

Have a look at these projects as well:

Dror Helper
+1  A: 

For quick and simple testing, you might like to have a look at doctests.

To write the tests, you place things that look like interactive interpreter sessions in a docstring:

def my_function(n):
    """Return n + 5

    >>> my_function(500)
    505"""
    return n + 5

to run the test, you import doctest and run doctest.testmod() which will run all the doctests in the module. You can also use doctest.testfile("...") to run all the tests in some other file.

If you check the documentation for doctests you will find ways to make a test expect exceptions, lists, etc -- anything the interpreter would output, plus some wildcards for brevity.

This is a quick way to write tests in Python modules, there isn't a lot of boilerplate code, and IMO it's easier to keep them up to date (the test is right there in the function!). But I also find them a little ugly.

Carson Myers
+7  A: 

Python has a unittest module that I like, heres a tutorial for it. Check it out! :)

mizipzor