Michio JP

Michio JP

1565248290

An Introduction to Unit Testing 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

What is GEEK

Buddha Community

An Introduction to Unit Testing in Python
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Gage  Monahan

Gage Monahan

1616417160

Python Unit Testing: One Time Initialization

Introduction
Recently, after writing a microservice to manage Create-Read-Update-Delete (CRUD) operations for a MongoDB database, it logically was time to write unit test cases. As I had developed the microservice using Python and Flask, the unit test also had to be in Python. For unit testing, I used the unittest package.

Writing Unit Tests
By writing unit tests, not only was I ensuring that I could run the same tests over and over again but, assuming that the underlying functionality of the micro-service had not broken, I could expect the same results for each execution. Moreover, as the number of REST functions increased, the unit tests would help me ensure that none of the existing functionality was broken. Additionally, the unit tests would help me reduce the total amount of time I needed to spend on testing the same functionality over and over again.

#python #python development #python unit test #python unit testing

Software Testing 101: Regression Tests, Unit Tests, Integration Tests

Automation and segregation can help you build better software
If you write automated tests and deliver them to the customer, he can make sure the software is working properly. And, at the end of the day, he paid for it.

Ok. We can segregate or separate the tests according to some criteria. For example, “white box” tests are used to measure the internal quality of the software, in addition to the expected results. They are very useful to know the percentage of lines of code executed, the cyclomatic complexity and several other software metrics. Unit tests are white box tests.

#testing #software testing #regression tests #unit tests #integration tests

Tamia  Walter

Tamia Walter

1596754901

Testing Microservices Applications

The shift towards microservices and modular applications makes testing more important and more challenging at the same time. You have to make sure that the microservices running in containers perform well and as intended, but you can no longer rely on conventional testing strategies to get the job done.

This is where new testing approaches are needed. Testing your microservices applications require the right approach, a suitable set of tools, and immense attention to details. This article will guide you through the process of testing your microservices and talk about the challenges you will have to overcome along the way. Let’s get started, shall we?

A Brave New World

Traditionally, testing a monolith application meant configuring a test environment and setting up all of the application components in a way that matched the production environment. It took time to set up the testing environment, and there were a lot of complexities around the process.

Testing also requires the application to run in full. It is not possible to test monolith apps on a per-component basis, mainly because there is usually a base code that ties everything together, and the app is designed to run as a complete app to work properly.

Microservices running in containers offer one particular advantage: universal compatibility. You don’t have to match the testing environment with the deployment architecture exactly, and you can get away with testing individual components rather than the full app in some situations.

Of course, you will have to embrace the new cloud-native approach across the pipeline. Rather than creating critical dependencies between microservices, you need to treat each one as a semi-independent module.

The only monolith or centralized portion of the application is the database, but this too is an easy challenge to overcome. As long as you have a persistent database running on your test environment, you can perform tests at any time.

Keep in mind that there are additional things to focus on when testing microservices.

  • Microservices rely on network communications to talk to each other, so network reliability and requirements must be part of the testing.
  • Automation and infrastructure elements are now added as codes, and you have to make sure that they also run properly when microservices are pushed through the pipeline
  • While containerization is universal, you still have to pay attention to specific dependencies and create a testing strategy that allows for those dependencies to be included

Test containers are the method of choice for many developers. Unlike monolith apps, which lets you use stubs and mocks for testing, microservices need to be tested in test containers. Many CI/CD pipelines actually integrate production microservices as part of the testing process.

Contract Testing as an Approach

As mentioned before, there are many ways to test microservices effectively, but the one approach that developers now use reliably is contract testing. Loosely coupled microservices can be tested in an effective and efficient way using contract testing, mainly because this testing approach focuses on contracts; in other words, it focuses on how components or microservices communicate with each other.

Syntax and semantics construct how components communicate with each other. By defining syntax and semantics in a standardized way and testing microservices based on their ability to generate the right message formats and meet behavioral expectations, you can rest assured knowing that the microservices will behave as intended when deployed.

Ways to Test Microservices

It is easy to fall into the trap of making testing microservices complicated, but there are ways to avoid this problem. Testing microservices doesn’t have to be complicated at all when you have the right strategy in place.

There are several ways to test microservices too, including:

  • Unit testing: Which allows developers to test microservices in a granular way. It doesn’t limit testing to individual microservices, but rather allows developers to take a more granular approach such as testing individual features or runtimes.
  • Integration testing: Which handles the testing of microservices in an interactive way. Microservices still need to work with each other when they are deployed, and integration testing is a key process in making sure that they do.
  • End-to-end testing: Which⁠—as the name suggests⁠—tests microservices as a complete app. This type of testing enables the testing of features, UI, communications, and other components that construct the app.

What’s important to note is the fact that these testing approaches allow for asynchronous testing. After all, asynchronous development is what makes developing microservices very appealing in the first place. By allowing for asynchronous testing, you can also make sure that components or microservices can be updated independently to one another.

#blog #microservices #testing #caylent #contract testing #end-to-end testing #hoverfly #integration testing #microservices #microservices architecture #pact #testing #unit testing #vagrant #vcr