Testing in Python - Unit Test & Script
Testing in Python - Unit Test & Script
Version 1.0
This is a supplementary material of the Course “Software Quality Assurance – Testing”, FPT University
delivered by Tran Dinh Que, [email protected] . This file will be updated regularly and display in class.
The simplest tool for editing code is notepad. Since we only need to write functions for unit testing,
notepad is enough .
The purpose of this tutorial is to assist students to be familiar with Python:
Writing functions in Python (if…elif…else, for)
Call functions from some file
Writing script for testing (unit and integration) in Python
There are two simple ways of unit testing SCRIPT with test cases in Python
Using simple assertion
Using library unittest
If not being familiar with Python yet, you can download and implement
https://www.python.org/downloads/.
1. Delicious smell of Python
Easy to access, easy to learn coding
https://www.tutorialspoint.com/python/python_lists.htm
1.1.Definition of functions in python
#Define sum of sequence of numbers
def sum(arg):
total = 0
for val in arg:
total += val
return total
addNumbers(25, 6)
subtractNumbers(25, 6)
multiplyNumbers(25, 6)
divideNumbers(25, 6)
modulusNumbers(25, 6)
displayText()
2. Testing – Test cases – Assertion
Example 1
def functCond1(x,y):
if (1 > x > 0) and y > 0:
return x+y
elif (x > 1) and y < 0:
return x*y
else:
return x-y
def test_functCond1():
assert functCond1(1,-5) == 6, "Should be 6"
if __name__ == "__main__":
test_functCond1()
print("Everything passed")
Example 2
a. Edit file maxSeq.py containing the following function
======
#Define max of a sequence of numbers
def maxSequence(u):
max = u[0]
for elem in u:
if elem > max:
max = elem
return max
b. Edit file for testing maxSeqTesting.py containing the following function
======
#syntax for testing testcases
#without library unittest
def test_maxSequence():
assert maxSequence([1, 2, 3]) == 3, "Should be 3"
#you replace 3 by 2 to see what occurs!
if __name__ == "__main__":
3
test_maxSequence()
print("Everything passed")
c. Write test cases and Testing. Happy with this
if __name__ == "__main__":
test_maxDayso()
print("Everything passed")
import unittest
from maxD import *
4
class TestmaxDay(unittest.TestCase):
#inherit from unittest
def test_list_int(self):
data = [1, 2, 3]
result = maxDayso(data)
self.assertEqual(result, 4)
if __name__ == '__main__':
unittest.main()
https://pythonhosted.org/gchecky/unittest-pysrc.html
https://docs.python.org/3.0/library/unittest.html