Python Testing Code - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Python Testing Code - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Tuesday, December 18, 2018

Python Testing Code

Python Testing Code



Why test your code?

When you write a function or a class, you can also write tests for that code. Testing proves that your code works as it's supposed to in the situations it's designed to handle, and also when people use your programs in unexpected ways. Writing tests gives you confidence that your code will work correctly as more people begin to use your programs. You can also add new features to your programs and know that you haven't broken existing behavior.

A unit tests verifies that one specific aspect of your code works as it's supposed to. A test case is a collection of unit tests which verify your code's behavior in a wide variety of situations.

Testing a function: A passing test

Python's unittest module provides tools for testing your code. To try it out, we'll create a function that returns a full name. we'll use the function in a regular program, and then build a test case for the function.

#A function to test
def get_full_name(first, last):
 """Return a full name."""
 full_name = "{0} {1}".format(first, last)
 return full_name.title()


#===============
#Using the function
from full_name import get_full_name

janis = get_full_name('janis', 'joplin')
print(janis)

bob = get_full_name('bob', 'dylan')
print(bob)

#Testing a function(cont.)
#Building a testcase with one unit test

import unittest
from full_name import get_full_name

class NamesTestCase(unittest.TestCase):
 """Test for names.py."""

 def test_first_last(self):
  """Test names like Janis Joplin."""
  full_name = get_full_name('janis', 'joplin')
  self.assertEqual(full_name, 'Janis Joplin')

unittest.main()

Screenshot 

python testing

 


Testing a function: A failing test

Failing tests are important; they tell you that a change in the code has affected existing behavior. When a test fails, you need to modify the code so the existing behavior still works.

#Modifying the function
def get_full_name(first, middle, last):
 """Return a full name."""
 full_name = "{0} {1} {2}".format(first, middle, last)
 return full_name.title()


#Using the function
from full_name2 import get_full_name

john = get_full_name('john', 'lee', 'hooker')
print(john)

david = get_full_name('david', 'lee', 'roth')
print(david)

Screenshot 

python testing

 

Adding new tests

You can add as many unit tests to a test case as you need. To write a new test, add a new method to your test, add a new method to your test case class.

#Testing middle names

import unittest
from full_names import get_full_name

class NamesTestCase(unittest.TestCase):
"""Tests for names.py"""

def test_first_last(self):
"""Test names like Janis Joplin."""
full_name = get_fullname('janis', 'joplin')
self.assertEqual(full_name, 'Janis Joplin')

def test_middle(self):
"""Test names like David Lee Roth."""
full_name = get_full_name('david', 'roth', 'lee')
self.assertEqual(ful_name, 'David Lee Roth')

unittest.main()

Screenshot 

python testing

 

A variety of assert methods
Python provides a number of assert methods you can use to test your code.
#Verify that a==b, or a!=b
assertEqual(a, b)
assertNotEqual(a, b)
#Verify that x is True, or x is False
assertTrue(x)
assertFalse(x)
#Verify an item is in a list, or not in a list
assertIn(item, list)
assertNotIn(item, list)
Testing a class
Testing a class is similar to testing a function, since you'll mostly be testing your methods.
A class to test

class Accountant():
"""Manage a bank account."""

def__init__(self, balance=0):
self.balance = balance

def deposit(self, amount):
self.balance += amount

def withdraw(self, amount):
self.balance -= amount

Building a testcase
import unittest
from accountant import Accountant

class TestAccountant(unittest.TestCase):
"""Tests for the class Acountant."""

def test_initial_balance(self):
#Default balance should be 0.
acc = Accountant()
self.assertEqual(acc.balance, 0)

# Test non-default balance.
acc = Accountant(100)
self.assertEqual(acc.balance, 100)

unittest.main()
The setUp() method
When testing a class, you usually have to make an instance of the class. The setUp() method is run before every test. Any instances you make in setUp() are available in every test you write.
Using setUp() to support mutiple tests
import unittest
from accountant import Accountant

class TestAccountant(unittest.TestCase):
"""Tests for the class Accountant."""

def setUp(self):
self.acc = Accountant()

def test_initial_balance(self):
# Default balance should be 0.
self.assertEqual(self.acc.balance, 100)

#Test non-default balance.
acc = Accountant(100)
self.assertEqual(acc.balance, 100)

def test_deposit(self):
#Test single deposit.
self.acc.deposit(100)
self.assertEqual(self.acc.balance, 100)

#Test multiple deposits.
self.acc.deposit(100)
self.acc.deposit(100)
self.assertEqual(self.acc.balance, 300)

def test_withdrawal(self):
#Test single withdrawal.
self.acc.deposit(100)
self.acc.withdraw(100)
self.assertEqual(self.acc.balance, 900)

unittest.main()

No comments:

Post a Comment

Post Top Ad