An Introduction to Unit Testing in Python

An Introduction to Unit Testing in Python

Unit tests can pass or fail, and that makes them a great technique to check your code. In this tutorial Goran Aviani will demonstrate how to write unit tests in python

Originally published by Goran Aviani at freecodecamp.org

You just finished writing a piece of code and you are wondering what to do. Will you submit a pull request and have your teammates review the code? Or will you manually test the code?

You should do both of these things, but with an additional step: you need to unit test your code to make sure that the code works as intended.

Getting started

The best way you can understand testing is if you do it hands-on. For that purpose, in a file named name_function.py, I will write a simple function that takes a first and last name, and returns a full name:

#Generate a formatted full name
def formatted_name(first_name, last_name):
   full_name = first_name + ' ' + last_name
   return full_name.title()

The function formatted_name() takes the first and the last name and combines them with a space between to form a full name. It then capitalizes the first letter of every word. To check that this code works, you need to write some code that uses this function. In names.py I will write some simple code that lets users enter their first and last names:

from name_function import formatted_name

print("Please enter the first and last names or enter x to E[x]it.")

while True:
first_name = input("Please enter the first name: ")
if first_name == "x":
print("Good bye.")
break

last_name = input("Please enter the last name: ")
if last_name == "x":
print("Good bye.")
break

result = formatted_name(first_name, last_name)
print("Formatted name is: " + result + ".")

This code imports formatted_name() from name_function.py and on running, allows the user to enter a series of first and last names and shows the formatted full names.

Unit test and Test cases

There is a module in Python’s standard library called unittest which contains tools for testing your code. Unit testing checks if all specific parts of your function’s behavior are correct, which will make integrating them together with other parts much easier.

Test case is a collection of unit tests which together proves that a function works as intended, inside a full range of situations in which that function may find itself and that it’s expected to handle. Test case should consider all possible kinds of input a function could receive from users, and therefore should include tests to represent each of these situations.

Passing a test

Here’s a typical scenario for writing tests:

First you need to create a test file. Then import the unittest module, define the testing class that inherits from unittest.TestCase, and lastly, write a series of methods to test all the cases of your function’s behavior.

There’s a line by line explanation below the following code:

import unittest
from name_function import formatted_name

class NamesTestCase(unittest.TestCase):

def test_first_last_name(self):
result = formatted_name("pete", "seeger")
self.assertEqual(result, "Pete Seeger")

First, you need to import a unittest and the function you want to test, formatted_name() . Then you create a class, for example NamesTestCase, that will contain tests for your formatted_name() function. This class inherits from the class unittest.TestCase.

NamesTestCase contains a single method that tests one part of formatted_name() . You can call this method test_first_last_name().

Remember that every method that starts with “test_” will be run automatically when you run test_name_function.py.

Within test_first_last_name() test method, you call the function you want to test and store a return value. In this example we are going to call formatted_name() with the arguments “pete” and “seeger” , and store the result in the resulting variable.

In the last line we will use the assert method. The assert method verifies that a result you received matches the result you expected to receive. And in this case we know that formatted_name() function will return full name with capitalized first letters, so we expect the result “Pete Seeger”. To check this, the unittest’s assertEqual() method is being used.

self.assertEqual(result, “Pete Seeger”)

This line basically means: Compare the value in the resulting variable with “Pete Seeger” and if they are equal it’s OK, but if they are not let me know.

On running test_name_function.py you are expected to get a OK meaning that the test has passed.

Ran 1 test in 0.001s OK
Failing a test

To show you what a failing test looks like I’m going to modify a formatted_name() function by including a new middle name argument.

So I’m going to rewrite the function to look like this:

#Generate a formatted full name including a middle name
def formatted_name(first_name, last_name, middle_name):
full_name = first_name + ' ' + middle_name + ' ' + last_name
return full_name.title()

This version of formatted_name() will work for people with middle names, but when you test it you will see that the function is broken for people who don’t have a middle name.

So when you run the test_name_function.py you will get the output that looks something like this:

Error
Traceback (most recent call last):
 
File “test_name_function.py”, line 7, in test_first_last_name
    result = formatted_name(“pete”, “seeger”)
 
TypeError: formatted_name() missing 1 required positional argument: ‘middle_name’
 
Ran 1 test in 0.002s
 
FAILED (errors=1)

In the output you will see information that will tell you all you need to know where the test fails:

  • First item in the output is the Error telling you that at least one test in test case resulted in an error.
  • Next you’ll see the file and method in which the error occurred.
  • After that you will see the line in which the error occurred.
  • And what kind of error it is, in this case we are missing 1 argument “middle_name”.
  • You will also see the number of run tests, the time needed for the tests to complete, and a textual message that represents the status of the tests with number of errors that occurred.
What to do when the test has failed
A passing test means the function is behaving according to what’s expected from it. However, a failing test means there’s more fun ahead of you.

I’ve seen couple of programmers that prefer to change the test instead of improving the code — but don’t to that. Spend a little more time to fix the issue, as it will help you to better understand the code and save time in the long run.

In this example, our function formatted_name() first required two parameters, and now as it is rewritten it requires one extra: a middle name. Adding a middle name to our function broke the desired behavior of it. Since the idea is not to make changes to the tests, the best solution is to make middle name optional.

After we do this the idea is to make the tests pass when the first and last name are used, for example “Pete Seeger”, as well as when first, last and middle names are used, for example “Raymond Red Reddington”. So let’s modify the code of formatted_name() once again:

#Generate a formatted full name including a middle name
def formatted_name(first_name, last_name, middle_name=''):
   if len(middle_name) > 0:
       full_name = first_name + ' ' + middle_name + ' ' + last_name
   else:
       full_name = first_name + ' ' + last_name
   return full_name.title()

Now the function should work for names with and without the middle name.

And to make sure it still works with “Pete Seeger” run the test again:

Ran 1 test in 0.001s

OK

And this is what I intended to show you: It’s always better to make changes to your code to fit your tests than other way around. Now the time has come to add a new test for names that do have a middle name.
Adding new tests

Write a new method to the NamesTestCase class that will test for middle names:

import unittest
from name_function import formatted_name
 
class NamesTestCase(unittest.TestCase):
 
    def test_first_last_name(self):
        result = formatted_name("pete", "seeger")
        self.assertEqual(result, "Pete Seeger")
 
    def test_first_last_middle_name(self):
        result = formatted_name("raymond", "reddington", "red")
        self.assertEqual(result, "Raymond Red Reddington")

After you run the test, both tests should pass:

Ran 2 tests in 0.001s

OK

Bra gjort!
Well done!

You have written your tests to check if the function works using names with or without a middle name. 

Originally published by Goran Aviani at freecodecamp.org

 ===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python for Time Series Data Analysis

☞ The complete beginner’s guide to JSON

☞ The Complete Guide to JSON Web Tokens

☞ Python Programming For Beginners From Scratch

☞ Python Network Programming | Network Apps & Hacking Tools

☞ Intro To SQLite Databases for Python Programming

☞ Ethical Hacking With Python, JavaScript and Kali Linux

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming


Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Quizzes
Assignments
Job Interview Preparation Questions
& Much More

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: