Join Club ShowMeDo to Learn Python!

This series is a part of Club ShowMeDo. Click to learn why you should join our club with a simple monthly subscription.

  • We teach Python and all the cool modules
  • Topics include beginner Python, GUIs, Web and Desktop Apps
  • Long, specially crafted video tutorials just for you
  • Club video tutorials extend our normal Free content
  • Save your time - we've done the research for you
  • Keep your skills up-to-date
  • Learn at your own pace, everything you need is shown to you
  • Over 12 hours of archived material are waiting for you in the club

Name: [002] Ian Ozsvald
Member: 108 months
Authored: 181 videos
Description: I am the co-founder of ShowMeDo (see http://showmedo.com/about), author of `The Screencasting Handbook <http://thescreencastinghandbook.com>`_ and the founder of the professional screencast production company `ProCasts <http://procasts.co.uk>`_: .. image:: http://procasts.co.uk/media/procasts_sma ...

Unit Tests for Dependable Code [ID:143] (9/10)

in series: Python Development on XP

(Showmedo is undergoing major changes. To report any problems viewing the videos please email us and include browser and OS specifics. Cheers - Kyran.)

Testing lets us trust our code - and unit-tests (via 'nosetests') make the task of writing tests super-easy. We should all be writing unit-tests with our code.

Here we use the excellent 'nosetests' to adopt a test-driven approach to coding, allowing us to build our confidence that our code is working exactly as we want it to. If you don't have nosetests yet, see the Installing Nosetests screencast.

We build 'checkNumbers.py' and a corresponding unit-test module 'testCheckNumbers.py' (source code in the wiki) that confirms that our program - written to parse a file of numbers and check that the numbers match our specified criteria - passes all the tests and only accepts the kind of numbers that we are after.

We use boolean conditions and exception handling to robustly parse the file of numbers, along with commenting our code and using sensible variable names.

Additionally you should watch Jeff Winkler's ShowMeDo on the nosey.

At the end of this set you will have the necessary knowledge to write your own unit-tests, allowing you to be confident that your code runs (and fails) in the right way.

If you want more details see this worked-example at DiveIntoPython and this nose write-up. For some more background, see wikipedia for entries on Unit Testing and Test Driven Development (TDD).

To talk to your fellow Pythonistas you should join the ShowMeDo Learners Group.

Got any questions?

Get answers in the ShowMeDo Learners Google Group.

Video statistics:

  • Video's rank shown in the most popular listing
  • Video plays: 366 (since July 30th)
  • Plays in last week: 0
  • Published: Sometime before 1st March 2007 (in other words - we don't remember!)

Thank-yous, questions and comments

If this video tutorial was helpful please take some time to say thank-you to the authors for their hard work. Feel free to ask questions. Let the author know why their video tutorial was useful - what are you learning about? Did the video tutorial save you time? Would you like to see more?

You may also want to see our ShowMeDo Google Group to speak to our active users and authors.

Your email address will not be published.

Show some quick comments >>








All comments excluding tick-boxed quick-comments

Very informative, this will save me hours of time just getting started on unit testing.

Thank you,

Steve


Excellent series. Havn't looked yet but do you have a series on designing software using UML or what ever is used with the python mind set and what graphical tool to use to plan for software with?


Thank you very much Ian, it's been a great series so far. I would only point out something, I would like to see more code examples, some useful pieces of code that show us the power of python.

Other than that it's a very interesting series of tutorials.


I find it easier to learn by following an example, so your tutorials are immensely useful to me. Thank you.


Thank you very much for the unit test demonstration. I had long wondered what it was about.

I had trouble running the nose tool. It appeared to have installed fine, but the nosestest command would not run on the command line.


hi -

i just subscribed, and a comment i have is that it would be nice if i could speed up the video playback - i can hear faster than you can talk. this might be a feature of the player.

anyway, this stuff is great- i'm looking forward to learning python quickly.

thanks,

jeff


This is an excellent series. Within a few minutes I was up and running on EasyEclipse for Python. The longest wait was for the download. In one evening I went through the series and was using PyDev in Eclipse. Thanks!


Hi Gasto, yes, I see what you mean. By saying that 'pass' shows that the test has 'passed' I'm introducing some possible confusion.

'pass' is a Python statement which means 'do nothing', we use it when we haven't written more useful code yet. Since 'pass' is a no-op, it doesn't Fail or Error, so when nosetests is running is sees a perfectly good bit of code and chalks it up as a success.

Thanks for pointing out that possible confusion!

Ian.


I am a little worried about what was said that the pass statement in the function is for Nose U.T. to recognize it as a passed/correct function. It is rather a python syntax for creating a dummy function.


Hi Ian,

Great job!

The visual instructions of the screen cast is an efficient learning method.

Its a time saver, looking forward to more python series!

Cheers,

Kupper


Hi Eldaria, thanks for the wiki update and the comment. Yes, the wiki update is great. I'm glad you're enjoying testing :-)

Ian.


Very useful, I have been doing a lot of minor coding, but never really done testing.

I usually always used debugging to find errors, basically stepping through the entire code untill it breaks. :-)

Anyway, I updated the Wiki to inlude how to install nosetests on Ubuntu, that was actually my first Wiki entry ever anywhere, hope I did it right. :-)


Hi leeard. I have updated the wiki page for installing nosetests:

http://wiki.showmedo.com/index.php/PythonOzsvaldPyNewbieSeries#Installing_nosetests

which now links to the 'adding Python to DOS path' video:

http://showmedo.com/videos/video?name=960000&fromSeriesID=96

which you need so that DOS can see nosetests.

Cheers

Ian.


very nice, and easy to understand. My only problem is installing nose. I followed the steps exactly (a few times) on the wiki and I don't have the easy_install command after running the ez_setup script. I'm XP Pro, any suggestions?


Thanks Ian for taking the time to make this episode it’s been a great spring board to re-approach python programming which I fully agree with. Thanks for making it simple to kick off with.


From memory - the behaviour of nosetests and directories is a bit odd. You can specify a directory as a nosetest argument and it runs the tests there, but the 'current' directory for the scripts is (I think) the directory you run nosetests from (and not the directory you specified).

This caused me some headaches as I have two sets of test directories which both refer to configuration files elsewhere on the path, so I had to use relative file names (various '../') to access the files.

It *does* work, you just have to figure out where you are in the path.

To test - get your test code to do something like:

def test1():

import os

print "Current dir: ", os.getcwd(), os.path.dirname(__file__) # show loc of the file and working dir, as nosetests sees it

1/0 # force a ZeroDivisionError in the nosetest

You use the 1/0 to force nosetest to print error messages - which includes the getcwd/dirname result, and from that you can see where you are in the path.

Ian.


Maybe the discussion about what directories nosetests will search is moot? If you don't start nosetests from the directory where the script to be tested resides, and if the script to be tested contains a reference to the current directory (like fileObject = open("../data/anyfile.txt", "r"), it appears that nosetests won't find it the file and returns an error.


Hi Vincent. I have done some more digging and I get different behaviour on my laptop with Python 2.5 than I do with my Python 2.4 at WebFaction (which runs ShowMeDo), I'll explain this at the end.

Directories - I can have an arbitrary number of directories which nosetests will look through, as long as they have names like 'testXYZ'. E.g. I can have:

mySource\test1.py

mySource\testDir1\testDir2\test2.py

and both the test files are found if I run nosetests within 'mySource'. If I have:

mySource\aDir\testDir3\test3.py

then 'test3.py' isn't found.

I can also name any of the directories to be 'src' as you have mentioned, but this isn't mentioned in the official nosetests documentation:

http://somethingaboutorange.com/mrl/projects/nose/

If you look at 'Writing tests' on that webpage you'll see a paragraph describing the regular expression that is used to match Python test modules and directory names:

(?:^|[b_.-])[Tt]est)

but I can't understand this Regular Expression (I *think* it is in error - see below). Can anyone expand upon this? My RegExp knowledge is pretty light.

Under 'Finding and running tests' on the same webpage we have:

'If it looks like a test, it's a test. Names of directories, modules, classes and functions are compared against the testMatch regular expression, and those that match are considered tests. Any class that is a unittest.TestCase subclass is also collected, so long as it is inside of a module that looks like a test.'

However, if we run "nosetests --help" then we get:

---

...

Any python source file,

directory or package that matches the testMatch regular expression

(by default: (?:^|[\b_\.-])[Tt]est) will be collected as a test (or

source for collection of tests).

(my break)

In addition, all other packages

found in the working directory are examined for python source files

or directories that match testMatch. Package discovery descends all

the way down the tree, so package.tests and package.sub.tests and

package.sub.sub2.tests will all be collected.

...

---

which explains things differently from the main help-page as the Regular Expression is now escaped (with \b and \. which makes a touch more sense). However I still don't see how this applies to the problems that we see...

Re. WebFaction - there I have a set of directories like:

\myFiles\testRunningSite

\myFiles\someSource\tests

and the tests in each are found when we run 'nosetests' from 'myFiles' - this appears to be different behaviour from what I get here on Windows on my laptop.

So - I have two questions - perhaps someone else can help?

1) How come if we have a subdirectory like 'mySource\aDir\testDir3\test3.py' then the test isn't found if we run 'nosetests' from 'mySource'?

2) How come 'src' is accepted as a directory for running tests even though it isn't discussed in the nosetests help (webpage or via --help)?

The solutions are out there...

Ian.


More Nosetest Quirks: The video says that nosetests will search subdirectories, but here's the behavior I get. Nosetest will search the directory where it is started, plus a subdirectory, if any, immediately below that one, but apparently only if it is called "src".


Note: I just discovered that nosetests not only looks for "test" at the beginning of a filename, but also for "Test" (but not "TesT" or _test), and that it also looks in the middle or end of a filename for "_test" (therefore it will test a file called something like number_test_file or number_test).


Great, glad the whole set was so useful :-)

I'm working on the new Introductory Python series today, now I must brew some coffee and get on with recording the first episodes...

Ian.


Now up and running with the formidable Eclipse, Pydev, Nose, and Nosy combination on both Suse Linux and Windows. I hate to imagine how horrible it would have been without your help.

Now I can start working on my project....er...uh......I mean on reviewing some actual Python commands and structures. Is that new Python course ready yet? I'm so hooked on these showmedos that I hate to try to learn something without one.


If you like nosetests, make sure you check out Jeff Winkler's video about nosy. Doing unit testing with nosy is almost fun. I can't wait to try this out on my next project. Now, if only I can figure out how to get nosetests working right on my Suse Linux box....


Unit tests and Test Driven Development (TDD) are crucial to writing dependable code.

I ignored them in Python for years because it was always a pain with C++ (I was a C++ coder for years)...then it turns out that after 10 minutes of playing with nosetests in Python it all 'just works' and is really easy. Woot!

Best to get into TDD sooner rather than later, it'll save you a lot of heartache on tricky problems and most importantly it keeps your momentum up (rather than leaving you feeling annoyed and frustrated!).

Cheers,

Ian.


You have convinced me to try your unit testing method. The lesson is clear about how it works.

My main difficulty had to do with getting nosetests installed under Windows XP, which in turn required an installation of easy_install. I got it with a little effort, and the wiki and links you kindly provided, but I think a total newbie might need a little more screencast style hand-holding.

I'm still fooling around with the Linux installation, but that is probably outside the scope of the course.


Hi miracle. I wanted to make an episode on unit-testing as I avoided trying it for so long because it sounded complicated. When I tried it...of course...it was super-easy and so I wanted to show others how to get going.

Unit-testing is a great way to solidly test your code (or website - we use it with Titus' Twill to test ShowMeDo).

I *really* recommend that new users learn about nosetests, it will surely help them write better code and, especially, it will help them avoid frustrating errors and hours of debugging from silly mistakes (mistakes which your unit-tests will already catch and stop you repeating).

Ian.


This is another great session. Lots of information (including links) to get started with unittest. The focus to teach TDD method is very important and beyond python.

Great work, Ian. Hope more is coming...

I will surely recommend this series/site to my friends...


Hi Chris. Great, I'm glad it was helpful :-) I worked hard to give a nice, easy introduction to unit-testing. Here I hope I've given enough to let a new user start unit-testing their own code nice and quickly.

The discussion at the end on how much (or little) unit-testing should be done ought to be useful to those new to the technique too.

Cheers!

Ian.


This was a great video that shows how to create tests for your code so that you can verify it does what you want it to! I found this to be very helpful.


Showmedo is a peer-produced video-tutorials and screencasts site for free and open-source software (FOSS)- with the exception of some club videos, the large majority are free to watch and download.

how to help » about » faq »

Educating the Open-source Community With Showmedo

Although as important as the software it supports, education and documentation are relatively neglected in the Open-source world. Coders love to code, and explaining how best to use or improve the software tends to be deferred or even sidelined.

At Showmedo we believe the community can play a vital role here and also say thanks for the tools and software that make our lives easier. If you have a piece of software you love or a programming langugage you are enthusiastic about, why not make a screencast showing others how to use it? All the stuff you wish you'd been told, the tips, tricks, insights that would have saved you time and frustration.

Screencasting is easier than you think, and we're happy to help you. You can emailus for advice or just use some of the how-to screencasts on the site. This screencasting learning-pathis a good place to start.

Kudos and Thanks for Ian

Content

Feedback

Showmedo's development is fairly rapid and bugs will inevitably creep in. If you have any problems please drop us a line using the contact address below. Likewise, any suggestions for improvements to the site are gratefully received.

feedback@showmedo.com