Python 3 Essential Training
Illustration by John Hersey

Using unit tests


Python 3 Essential Training

with Bill Weinman

Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now

Video: Using unit tests

The Python standard library includes a unit test module that's very powerful and very flexible and is also very easy to use. Unit tests are valuable for a few reasons. Unit tests are automated tests that you can run on your code and you can write these tests once and save them and run them over and over. So if you have a set of code that's got a lifetime to it, that over the course of its lifetime it gets updated, it gets changed, having these unit tests already written and being able to run these unit tests on your code is going to have some real value for you.
Expand all | Collapse all
  1. 5m 14s
    1. Welcome
      1m 32s
    2. Understanding prerequisites for Python
      2m 4s
    3. Using the exercise files
      1m 38s
  2. 33m 29s
    1. Getting started with "Hello World"
      4m 43s
    2. Selecting code with conditionals
      4m 45s
    3. Repeating code with a loop
      4m 13s
    4. Reusing code with a function
      2m 43s
    5. Creating sequences with generator functions
      2m 46s
    6. Reusing code and data with a class
      4m 39s
    7. Greater reusability with inheritance and polymorphism
      7m 17s
    8. Handling errors with exceptions
      2m 23s
  3. 22m 32s
    1. Installing Python 3 and Eclipse for Windows
      11m 24s
    2. Installing Python 3 and Eclipse for Mac
      11m 8s
  4. 28m 0s
    1. Creating a main script
      3m 27s
    2. Understanding whitespace in Python
      4m 8s
    3. Commenting code
      3m 28s
    4. Assigning values
      3m 37s
    5. Selecting code and values with conditionals
      4m 46s
    6. Creating and using functions
      3m 54s
    7. Creating and using objects
      4m 40s
  5. 31m 23s
    1. Understanding variables and objects in Python
      2m 46s
    2. Distinguishing mutable and immutable objects
      2m 41s
    3. Using numbers
      3m 34s
    4. Using strings
      6m 38s
    5. Aggregating values with lists and tuples
      4m 55s
    6. Creating associative lists with dictionaries
      4m 24s
    7. Finding the type and identity of a variable
      4m 45s
    8. Specifying logical values with True and False
      1m 40s
  6. 9m 42s
    1. Selecting code with if and else conditional statements
      2m 22s
    2. Setting multiple choices with elif
      2m 14s
    3. Understanding other strategies for multiple choices
      2m 38s
    4. Using the conditional expression
      2m 28s
  7. 11m 26s
    1. Creating loops with while
      1m 27s
    2. Iterating with for
      3m 54s
    3. Enumerating iterators
      3m 22s
    4. Controlling loop flow with break, continue, and else
      2m 43s
  8. 23m 28s
    1. Performing simple arithmetic
      2m 14s
    2. Operating on bitwise values
      3m 30s
    3. Comparing values
      3m 32s
    4. Operating on Boolean values
      2m 59s
    5. Operating on parts of a container with the slice operator
      6m 52s
    6. Understanding operator precedence
      4m 21s
  9. 11m 34s
    1. Using the re module
      1m 4s
    2. Searching with regular expressions
      3m 12s
    3. Replacing with regular expressions
      3m 29s
    4. Reusing regular expressions with re.compile
      3m 49s
  10. 9m 10s
    1. Learning how exceptions work
      1m 18s
    2. Handling exceptions
      4m 15s
    3. Raising exceptions
      3m 37s
  11. 23m 1s
    1. Defining functions
      6m 23s
    2. Using lists of arguments
      2m 26s
    3. Using named function arguments
      4m 32s
    4. Returning values from functions
      1m 55s
    5. Creating a sequence with a generator function
      7m 45s
  12. 47m 29s
    1. Understanding classes and objects
      5m 12s
    2. Using methods
      6m 12s
    3. Using object data
      10m 4s
    4. Understanding inheritance
      5m 11s
    5. Applying polymorphism to classes
      7m 13s
    6. Using generators
      9m 48s
    7. Using decorators
      3m 49s
  13. 18m 54s
    1. Understanding strings as objects
      3m 25s
    2. Working with common string methods
      5m 24s
    3. Formatting strings with str.format
      5m 31s
    4. Splitting and joining strings
      2m 49s
    5. Finding and using standard string methods
      1m 45s
  14. 25m 27s
    1. Creating sequences with tuples and lists
      4m 6s
    2. Operating on sequences with built-in methods
      5m 50s
    3. Organizing data with dictionaries
      4m 56s
    4. Operating on character data with bytes and byte arrays
      10m 35s
  15. 11m 46s
    1. Opening files
      2m 4s
    2. Reading and writing text files
      4m 33s
    3. Reading and writing binary files
      5m 9s
  16. 21m 27s
    1. Creating a database with SQLite 3
      6m 56s
    2. Creating, retrieving, updating, and deleting records
      7m 31s
    3. Creating a database object
      7m 0s
  17. 18m 27s
    1. Using standard library modules
      8m 0s
    2. Finding third-party modules
      5m 47s
    3. Creating a module
      4m 40s
  18. 23m 11s
    1. Dealing with syntax errors
      8m 19s
    2. Dealing with runtime errors
      4m 0s
    3. Dealing with logical errors
      4m 22s
    4. Using unit tests
      6m 30s
  19. 19m 56s
    1. Normalizing a database interface
      6m 39s
    2. Deconstructing a database application
      8m 9s
    3. Displaying random entries from a database
      5m 8s
  20. 29s
    1. Goodbye

please wait ...
Watch the Online Video Course Python 3 Essential Training
6h 36m Beginner Jul 29, 2010

Viewers: in countries Watching now:

Due to its power, simplicity, and complete object model, Python has become the scripting language of choice for many large organizations, including Google, Yahoo, and IBM. In Python 3 Essential Training, Bill Weinman demonstrates how to use Python 3 to create well-designed scripts and maintain existing projects. This course covers the basics of the language syntax and usage, as well as advanced features such as objects, generators, and exceptions. Example projects include a normalized database interface and a complete working CRUD application. Exercise files accompany the course.

Topics include:
  • A Python 3 quick start for experienced developers
  • Creating functions and objects
  • Using Python’s built-in objects and classes
  • Repeating code with loops and iterators
  • Understanding and using conditional expressions
  • Creating sequences with generators
  • Reusing code with objects and libraries
  • Handling errors with exceptions
Developer Web
Bill Weinman

Using unit tests

The Python standard library includes a unit test module that's very powerful and very flexible and is also very easy to use. Unit tests are valuable for a few reasons. Unit tests are automated tests that you can run on your code and you can write these tests once and save them and run them over and over. So if you have a set of code that's got a lifetime to it, that over the course of its lifetime it gets updated, it gets changed, having these unit tests already written and being able to run these unit tests on your code is going to have some real value for you.

So let's look at how this is done in Python. I've got the saytime module here, which has been used for a number of different purposes in this course. And you'll notice at the end of it it's got a little test function. And when I wrote this, this just seemed like the easiest way to do it. And it's also, I like to be able to look at the results and say yeah, that looks right. That looks right. That looks right. If this were anymore complicated or if it was going to have much of a development lifecycle to it, I would use unit tests instead.

And so we're going to go ahead and do that. This is a unittest script that I wrote for saytime. And I basically took those textual tests and I made them into unit tests. And this is very, very easy to do. All I do is I import saytime and I import the unittest. So this is the module that I'm working on and this is the unittest framework from the Python standard library. And then I create this class.

And then at the end of the module here, if __name == "__main__", instead of just calling my own main, I call a special main that's in the unittest package. And in the unittest package, the special main will actually open up this file and parse it and find the classes that import unittest, and it will go ahead and run the test in that class. And so here is the class. So I can name it whatever I want. And it has a special method called setUp. In this special method setUp, I can do any initializations that I want to.

And so here I've created this list of numbers. I could have just as easily put that in the test for the numbers, but I wanted to demonstrate the setUp here. And so I take a range of 11 numbers, from 0-10, and I make a list out of them, and I assign them to this variable here. And so that gets used in test_numbers. So here is the first method. These methods will get run as the tests. So the first method here is test_numbers. And I've got some words that I'm going to compare those numbers again. And these are the words that will be the results of my saywords numwords.

So 'oh', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', those are the results that I'm expecting. And so I enumerate through the self.nums. I get both an index and the number itself. And then I run this assertEqual method, which is from the unittest package, and it's going to compare two values. And if these two values are equal, then fine. It will leave it alone. And if they're not, then it will throw an AssertionError. And so here the two values are the result from my saytime.numwords and the word from this tuple here.

If they equal, then fine. And if they're not equal, then it'll throw an AssertionError. And so the same thing here, test_time. I have time_tuples. And so this is a tuple with a bunch of tuples in it. And these are the times that I'm testing against. And these are hours and minutes. And then here's the list of the results that I want, "midnight", "one past midnight", "eleven o'clock", etcetera. And if they compare equal, it's the same thing. I enumerate through the time_tuples. I run them through the module that I'm testing and I compare them to this tuple up here of these words.

If they're equal, fine. If they're not equal, it throws an AssertionError. So this is how this works. And obviously you can write your own tests. There are a number of different assertion tests. You can find those in the documentation for the unittest module. I strongly recommend that you read the documentation for the unittest package. It's got a lot of options. It has a lot of methods that you can use for your testing. There are a lot of different assertions that you can test for. And it even has some ways to do some more complicated tests.

This kind of test that I've written here is the simplest case. And for most purposes, this is actually just fine, and it does the job and it does the job well. So let's go ahead and run it. When we run this, you'll notice that we get our little test. And we've been just selecting Python Run for all of these. There's a special one here in the PyDev module for Eclipse. It's called Python unit-test. And we're going to run that one. Say OK. And here it ran our unittest. We'll maximize this so we can see what it does.

First of all, it finds files. And it finds the test-saytime. And that's our unittest module that we just wrote. And it imports the test module. So it's importing the saywords. And here it runs the two tests, test_numbers and test_time. It ran the two tests. It didn't throw any assertion errors. And there's the result that we're expecting. If it had not gotten the result that it wanted, let's just go ahead and misspell one of these words here. I'll just throw an extra o in there. We'll save that and we'll run it.

And now we got one failure. You see it got an AssertionError that oh did not equal to ooh. So it gives us enough information here that we can actually go through the code and we can say, oh, well, I've got a typo in my assertion test or there's an actual problem in my module that I need to go and fix. So the beauty of this is, is that as your code goes through its development lifecycle, you make one release. You make another release. You make another release. You add features. You take features away. You change features.

Your unit-tests are already written. And so you can accumulate more. You can change them. And this is going to help you to keep the quality of your code high throughout its development lifecycle. So unit-tests are very useful. The unit-test package that comes in the standard Python library is very complete and very well written and very reliable. If you're going to be releasing your code using Python, you must submit unit-tests with it. And of course the unit-tests are going to be of value to you in any code that has a lengthy product lifecycle.

Find answers to the most frequently asked questions about Python 3 Essential Training .

Expand all | Collapse all
please wait ...
Q: The installation process for the PyDev Eclipse plug-in doesn’t work as described in the videos. What should I do?
A: The version of Eclipse used in the recording of Python 3 Essential Training was Eclipse 3.5.2 (Galileo SR2) and the version of PyDev was 1.5.7. Soon after recording, the Eclipse project was updated to version 3.6, called Helios. As of this writing, the current version of Eclipse is 3.6.1 (Helios SR1).
Around the same time as these updates were being released, the PyDev project was updated as well. As of this writing, the current version of PyDev is 1.6.2. If you are using these most recent versions, the procedure for installing Eclipse itself has not changed, but the process documented in the videos for installing PyDev may not work.

We will be releasing new versions of the videos soon, but the author has posted a document describing the new installation procedure at:
Q: How do you install the pydev-interpreter in Eclipse Indigo on Mac OS X Lion? It's significantly different than what's shown in the video "Installing Python 3 and Eclipse for Mac."
A: Since this course was publishing, there have been upgrades to Mac OS X and Eclipse. In this scenario, after installing Python and Eclipse and the Pydev interpreter, there is a different directory to go to when modifying the preferences. As instructed in the movie (at around 6:40) restart Eclipse and then go to Eclipse > Preferences and drill down to Pydev > Interpreter - Python in the sidebar. Click New and in the Select interpreter dialog that opens, click Browse.

The Open dialog box will open, but does not appear to display your hard drive. You must press and hold the Command+Shift+Period keys. This will display all hidden files on your system. Navigate to the new path ~/Library/Frameworks/Python.framework/versions/3.2/bin/python 3.2 and click Open.

You should be able to proceed normally from there.
Q: When I try to install PyDev, it's not showing up in the Available Software window.
A:  This can happen if the site is down.
    You can manually download PyDev from the web site, or from my site here:

    Installation is simple. I've included instructions on my web site above.
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.

Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.

Mark all as unwatched Cancel


You have completed Python 3 Essential Training.

Return to your organization's learning portal to continue training, or close this page.

Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.