Kindly Note: If you had any problems, please comment below.
LAB 1: Welcome to Unit Testing using doctest in Python : Hands on doctest
Problem 1: Unit Testing using doctest
Solution 1: Unit Testing using doctest
#!/bin/python3
import os
import sys
import math
import random
import re
import inspect
# Complete the following isPalindrome function:
#
def isPalindrome(x):
# Write the doctests:
"""Checking Palindrome of number
>>>isPalindrome(121)
True
>>>isPalindrome(344)
False
>>>isPalindrome(-121)
Traceback (most recent call last)
ValueError: x must be a positive integer
>>>isPalindrome("hello")
Traceback (most recent call last)
TypeError: x must be an integer
"""
# Write the functionality:
try:
if not isinstance(x,int):
raise TypeError
if x < 0:
raise ValueError
else:
x_string=str(x)
x_reverse=list(reversed(x_string))
flag=True
for i in range(len(x_string)):
if x_string[i] != x_reverse[i]:
flag=False
break
return flag
except ValueError :
raise ValueError("x must be a positive integer")
except TypeError:
raise TypeError("x must be an integer")
# Refer '__main__' method code which is given below if required.
# if __name__ == '__main__':
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
x = input()
if x.isdigit():
x = int(x)
res = isPalindrome(x)
doc = inspect.getdoc(isPalindrome)
func_count = len(re.findall(r'isPalindrome', doc))
true_count = len(re.findall(r'True', doc))
false_count = len(re.findall(r'False', doc))
pp_count = len(re.findall(r'>>>', doc))
trace_count = len(re.findall(r'Traceback', doc))
fptr.write(str(res)+'\n')
fptr.write(str(func_count)+'\n')
fptr.write(str(true_count)+'\n')
fptr.write(str(false_count)+'\n')
fptr.write(str(pp_count) + '\n')
fptr.write(str(trace_count) + '\n')
fptr.close()
Problem 2: Unit Testing using doctest
Solution 2: Unit Testing using doctest
#!/bin/python3
import inspect
import doctest
import math
import re
# Define the class 'Circle' and its methods with proper doctests:
#
class Circle:
def __init__(self, radius):
# Define doctests for __init__ method:
"""
>>> c1 = Circle(2.5)
>>> c1.radius
2.5
"""
self.radius = radius
def area(self):
# Define doctests for area method:
"""
>>> c1 = Circle(2.5)
>>> c1.area()
19.63
"""
# Define area functionality:
pi=math.pi
area=pi* self.radius**2
return round(area,2)
def circumference(self):
# Define doctests for circumference method:
"""
>>> c1=Circle(2.5)
>>> c1.circumference()
15.71
"""
area=math.pi*(self.radius*2)
return round(area,2)
# Define circumference functionality:
# Refer '__main__' method code which is given below if required.
# if __name__ == '__main__':
if __name__ == '__main__':
doctest.testmod()
c2 = Circle(2.5)
doc1 = inspect.getdoc(c2.__init__)
doc2 = inspect.getdoc(c2.area)
doc3 = inspect.getdoc(c2.circumference)
class_count = len(re.findall(r'Circle', doc1))
func1_count = len(re.findall(r'c1.radius', doc1))
func1_val = len(re.findall(r'2.5', doc1))
print(str(class_count), str(func1_count), str(func1_val))
class_count = len(re.findall(r'Circle', doc2))
func1_count = len(re.findall(r'c1.area', doc2))
func1_val = len(re.findall(r'19.63', doc2))
print(str(class_count), str(func1_count), str(func1_val))
class_count = len(re.findall(r'Circle', doc3))
func1_count = len(re.findall(r'c1.circumference', doc3))
func1_val = len(re.findall(r'15.71', doc3))
print(str(class_count), str(func1_count), str(func1_val))
LAB 2 Welcome to Unit Testing using unittest in Python.
Problem 1 : Unit Testing using unittest in Python.
Solution 1: Unit Testing using unittest in Python.
#!/bin/python3
import inspect
import re
import unittest
import math
# Define class 'Circle' and its methods with proper doctests:
class Circle:
def __init__(self, radius):
# Define initialization method:
self.radius=radius
if (type(radius) != type(int())) and (type(radius) != type(float())):
raise TypeError("radius must be a number")
if self.radius<0 or self.radius>1000:
raise ValueError("radius must be between 0 and 1000 inclusive")
def area(self):
# Define area functionality:
pi=math.pi
area=pi* self.radius**2
return round(area,2)
def circumference(self):
# Define circumference functionality:
area=math.pi*(self.radius*2)
return round(area,2)
class TestCircleCreation(unittest.TestCase):
def test_creating_circle_with_numeric_radius(self):
# Define a circle 'c1' with radius 2.5, and check if
# the value of c1.radius is equal to 2.5 or not.
c1= Circle(2.5)
self.assertEqual(c1.radius, 2.5)
def test_creating_circle_with_negative_radius(self):
# Define a circle 'c' with radius -2.5, and check
# if it raises a ValueError with the message
# "radius must be between 0 and 1000 inclusive".
with self.assertRaises(ValueError) as e:
c= Circle(-2.5)
message="radius must be between 0 and 1000 inclusive"
self.assertEqual( str(e.exception) , message)
def test_creating_circle_with_greaterthan_radius(self):
# Define a circle 'c' with radius 1000.1, and check
# if it raises a ValueError with the message
# "radius must be between 0 and 1000 inclusive".
with self.assertRaises(ValueError) as e:
c=Circle(1000.1)
message="radius must be between 0 and 1000 inclusive"
self.assertEqual(str(e.exception) , message)
def test_creating_circle_with_nonnumeric_radius(self):
# Define a circle 'c' with radius 'hello' and check
# if it raises a TypeError with the message
# "radius must be a number".
with self.assertRaises(TypeError) as e:
c=Circle("hello")
message= "radius must be a number"
self.assertEqual(str(e.exception) , message)
# Refer '__main__' method code which is given below if required.
# if __name__ == '__main__':
if __name__ == '__main__':
fptr = open('output.txt', 'w')
runner = unittest.TextTestRunner(fptr)
unittest.main(testRunner=runner, exit=False)
fptr.close()
with open('output.txt') as fp:
output_lines = fp.readlines()
pass_count = len(re.findall(r'\.', output_lines[0]))
print(str(pass_count))
doc1 = inspect.getsource(TestCircleCreation.test_creating_circle_with_numeric_radius)
doc2 = inspect.getsource(TestCircleCreation.test_creating_circle_with_negative_radius)
doc3 = inspect.getsource(TestCircleCreation.test_creating_circle_with_greaterthan_radius)
doc4 = inspect.getsource(TestCircleCreation.test_creating_circle_with_nonnumeric_radius)
assert1_count = len(re.findall(r'assertEqual', doc1))
print(str(assert1_count))
assert1_count = len(re.findall(r'assertEqual', doc2))
assert2_count = len(re.findall(r'assertRaises', doc2))
print(str(assert1_count), str(assert2_count))
assert1_count = len(re.findall(r'assertEqual', doc3))
assert2_count = len(re.findall(r'assertRaises', doc3))
print(str(assert1_count), str(assert2_count))
assert1_count = len(re.findall(r'assertEqual', doc4))
assert2_count = len(re.findall(r'assertRaises', doc4))
print(str(assert1_count), str(assert2_count))
Problem 2 : Unit Testing using unittest in Python
Solution 2: Unit Testing using unittest in Python
import inspect
import re
import unittest
import math
class Circle:
def __init__(self, radius):
# Define initialization method:
self.radius=radius
if (type(radius) != type(int())) and (type(radius) != type(float())):
raise TypeError("radius must be a number")
if self.radius<0 or self.radius>1000:
raise ValueError("radius must be between 0 and 1000 inclusive")
def area(self):
# Define area functionality:
pi=math.pi
area=pi* self.radius**2
return round(area,2)
def circumference(self):
# Define circumference functionality:
area=math.pi*(self.radius*2)
return round(area,2)
class TestCircleArea(unittest.TestCase):
def test_circlearea_with_random_numeric_radius(self):
# Define a circle 'c1' with radius 2.5, and check if
# its area is 19.63.
self.assertEqual(Circle(2.5).area(),19.63)
def test_circlearea_with_min_radius(self):
# Define a circle 'c2' with radius 0, and check if
# its area is 0.
self.assertEqual(Circle(0).area(),0)
def test_circlearea_with_max_radius(self):
# Define a circle 'c3' with radius 1000, and check if
# its area is 3141592.65.
self.assertEqual(Circle(1000).area(),3141592.65)
# Refer '__main__' method code which is given below if required.
# if __name__ == '__main__':
if __name__ == '__main__':
fptr = open('output.txt', 'w')
runner = unittest.TextTestRunner(fptr)
unittest.main(testRunner=runner, exit=False)
fptr.close()
with open('output.txt') as fp:
output_lines = fp.readlines()
pass_count = [ len(re.findall(r'\.', line)) for line in output_lines if (line.startswith('.') or line.startswith('E')) and line.endswith('.\n')]
pass_count = pass_count[0]
print(str(pass_count))
doc1 = inspect.getsource(TestCircleArea.test_circlearea_with_random_numeric_radius)
doc2 = inspect.getsource(TestCircleArea.test_circlearea_with_min_radius)
doc3 = inspect.getsource(TestCircleArea.test_circlearea_with_max_radius)
assert1_count = len(re.findall(r'assertEqual', doc1))
print(str(assert1_count))
assert1_count = len(re.findall(r'assertEqual', doc2))
print(str(assert1_count))
assert1_count = len(re.findall(r'assertEqual', doc3))
print(str(assert1_count))
Problem 3: Unit Testing using unittest in Python
Solution 3: Unit Testing using unittest in Python
import inspect
import re
import unittest
import math
# Define class 'Circle' and its methods:
class Circle:
def __init__(self, radius):
# Define initialization method:
self.radius=radius
if (type(radius) != type(int())) and (type(radius) != type(float())):
raise TypeError("radius must be a number")
if self.radius<0 or self.radius>1000:
raise ValueError("radius must be between 0 and 1000 inclusive")
def area(self):
# Define area functionality:
pi=math.pi
area=pi* self.radius**2
return round(area,2)
def circumference(self):
# Define circumference functionality:
area=math.pi*(self.radius*2)
return round(area,2)
class TestCircleCircumference(unittest.TestCase):
def test_circlecircum_with_random_numeric_radius(self):
# Define a circle 'c1' with radius 2.5, and check if
# its circumference is 15.71.
self.assertEqual(Circle(2.5).circumference(),15.71)
def test_circlecircum_with_min_radius(self):
# Define a circle 'c2' with radius 0, and check if
# its circumference is 0.
self.assertEqual(Circle(0).circumference(),0)
def test_circlecircum_with_max_radius(self):
# Define a circle 'c3' with radius 1000, and check if
# its circumference is 6283.19.
self.assertEqual(Circle(1000).circumference(),6283.19)
# Refer '__main__' method code which is given below if required.
# if __name__ == '__main__':
if __name__ == '__main__':
fptr = open('output.txt', 'w')
runner = unittest.TextTestRunner(fptr)
unittest.main(testRunner=runner, exit=False)
fptr.close()
with open('output.txt') as fp:
output_lines = fp.readlines()
pass_count = [ len(re.findall(r'\.', line)) for line in output_lines if (line.startswith('.') or line.startswith('E')) and line.endswith('.\n')]
pass_count = pass_count[0]
print(str(pass_count))
doc1 = inspect.getsource(TestCircleCircumference.test_circlecircum_with_random_numeric_radius)
doc2 = inspect.getsource(TestCircleCircumference.test_circlecircum_with_min_radius)
doc3 = inspect.getsource(TestCircleCircumference.test_circlecircum_with_max_radius)
assert1_count = len(re.findall(r'assertEqual', doc1))
print(str(assert1_count))
assert1_count = len(re.findall(r'assertEqual', doc2))
print(str(assert1_count))
assert1_count = len(re.findall(r'assertEqual', doc3))
print(str(assert1_count))
LAB 3: Welcome to Python Qualis - Nose Testing Framework
LAB 3: Welcome to Python Qualis - Nose Testing Framework
from proj.circle import Circle
from nose.tools import assert_raises, eq_, eq_
# Define a nose test class 'TestingCircleCreation'
class TestingCircleCreation:
# Define a nose test method 'test_creating_circle_with_numeric_radius', which creates a circle with radius 2.5, and check if its radius value is 2.5 using eq_ method.
def test_creating_circle_with_numeric_radius(self):
eq_(Circle(2.5).radius,2.5)
# Define a nose test method 'test_creating_circle_with_negative_radius', which checks if the ValueError exception is raised with the error message "radius must be between 0 and 1000 inclusive" using eq_ method, while creating a circle of radius -2.5.
# Hint: Use assert_raises and with.
def test_creating_circle_with_negative_radius(self):
with assert_raises(ValueError) as e:
Circle(-2.5)
message="radius must be between 0 and 1000 inclusive"
eq_( str(e.exception),message)
# Define a nose test method 'test_creating_circle_with_greaterthan_radius', which checks if the ValueError exception is raised with the error message "radius must be between 0 and 1000 inclusive" using eq_ method, while creating circle of radius 1000.1 .
# Hint: Use assert_raises and with
def test_creating_circle_with_greaterthan_radius(self):
with assert_raises(ValueError) as e:
Circle(1000.1)
message="radius must be between 0 and 1000 inclusive"
eq_(str(e.exception) , message)
# Define a nose test method 'test_creating_circle_with_nonnumeric_radius', which checks if the TypeError exception is raised with the error message "radius must be a number" using eq_ method, while creating circle of radius 'hello' .
# Hint: Use assert_raises and with.
def test_creating_circle_with_nonnumeric_radius(self):
with assert_raises(TypeError) as e:
c=Circle("hello")
message= "radius must be a number"
eq_(str(e.exception) , message)
#Define a nose test class 'TestCircleArea'
class TestCircleArea:
# Define a nose test method 'test_circlearea_with_random_numeric_radius', which creates a circle 'c1' with radius 2.5, and check if its computed area is 19.63 using eq_ method.
def test_circlearea_with_random_numeric_radius(self):
eq_(Circle(2.5).area(),19.63)
# Define a nose test method 'test_circlearea_with_min_radius', which creates a circle 'c2' with radius 0, and check if its computed area is 0 using eq_ method.
def test_circlearea_with_min_radius(self):
eq_(Circle(0).area(),0)
# Define a nose test method 'test_circlearea_with_max_radius', which creates a circle 'c3' with radius 1000, and check if its computed area is 3141592.65 using eq_ method.
def test_circlearea_with_max_radius(self):
eq_(Circle(1000).area(),3141592.65)
# Define a nose test class 'TestCircleCircumference'
class TestCircleCircumference:
# Define a nose test method 'test_circlecircum_with_random_numeric_radius', which creates a circle 'c1' with radius 2.5, and check if its computed circumference is 15.71 using eq_ method.
def test_circlecircum_with_random_numeric_radius(self):
eq_(Circle(2.5).circumference(),15.71)
# Define a nose test method 'test_circlecircum_with_min_radius', which creates a circle 'c2' with radius 0, and check if its computed circumference is 0 using eq_ method.
def test_circlecircum_with_min_radius(self):
eq_(Circle(0).circumference(),0)
# Define a nose test method 'test_circlecircum_with_max_radius', which creates a circle 'c3' with radius 1000, and check if its computed circumference is 6283.19 using eq_ method.
def test_circlecircum_with_max_radius(self):
eq_(Circle(1000).circumference(),6283.19)
LAB 4: Welcome to Python Qualis Pytest Testing - Pytest Testing Framework
LAB 4: Welcome to Python Qualis Pytest Testing - Pytest Testing Framework
# Kindly Note:
# If you are getting error like this :
#__________ TestInventoryAddStock.test_add_new_stock_with_float_values failed__________
#========================= 1 failed, 1 passed in 0.06s ==========================
# Then you just need to run this code 2 or 3 time, you may faced this error because of compiler issue.
import sys
import os
sys.path.append(os.getcwd())
from proj.inventory import MobileInventory, InsufficientException
import pytest
# Use assert statement for assert, and to check. Ex: assert 1 == 1
# Define a pytest test class **'TestingInventoryCreation'**
# Define a pytest test class **'TestingInventoryCreation'**
class TestingInventoryCreation:
# Define a pytest test method **'test_creating_empty_inventory'**, which creates an empty inventory and checks if its 'balance_inventory' is an empty dict using assert.
def test_creating_empty_inventory(self):
assert MobileInventory().balance_inventory=={}
# Define a pytest test method **'test_creating_specified_inventory'**, which checks if inventory instance with input {'iPhone Model X':100, 'Xiaomi Model Y': 1000, 'Nokia Model Z':25}.
def test_creating_specified_inventory(self):
my_dict={"iPhone Model X":100,'Xiaomi Model Y':1000,'Nokia Model Z':25}
assert MobileInventory({"iPhone Model X":100,'Xiaomi Model Y':1000,'Nokia Model Z':25}).balance_inventory== my_dict
def test_creating_inventory_with_list(self):
with pytest.raises(TypeError) :
assert "Input inventory must be a dictionary" == MobileInventory(['iPhone Model X', 'Xiaomi Model Y', 'Nokia Model Z'])
# Define a pytest test method **'test_creating_inventory_with_numeric_keys'**, which checks if the method raises a ValueError with the message "Mobile model name must be a string" using assert, when the dict {1:'iPhone Model X', 2:'Xiaomi Model Y', 3:'Nokia Model Z'} is passed as input.
def test_creating_inventory_with_numeric_keys(self):
message="Mobile model name must be a string"
with pytest.raises(ValueError):
assert MobileInventory( {1:'iPhone Model X', 2:'Xiaomi Model Y', 3:'Nokia Model Z'})==message
# Define a pytest test method **'test_creating_inventory_with_nonnumeric_values'**, which checks if the method raises a ValueError with the message "No. of mobiles must be a positive integer" using assert, when the dict {'iPhone Model X':'100', 'Xiaomi Model Y': '1000', 'Nokia Model Z':'25'} is passed as input.
def test_creating_inventory_with_nonnumeric_values(self):
with pytest.raises(ValueError):
message="No. of mobiles must be a positive integer"
assert message == MobileInventory({ 'iPhone Model X':'100', 'Xiaomi Model Y': '1000','Nokia Model Z':'25'})
# Define a pytest test method **'test_creating_inventory_with_negative_value'**, which checks if the method raises a ValueError with the message "No. of mobiles must be a positive integer" using assert, when the dict {'iPhone Model X':-45, 'Xiaomi Model Y': 200, 'Nokia Model Z':25} is passed as input.
def test_creating_inventory_with_negative_value(self):
with pytest.raises(ValueError):
message="No. of mobiles must be a positive integer"
assert message==MobileInventory({'iPhone Model X':-45, 'Xiaomi Model Y': 200, 'Nokia Model Z':25})
# Define another pytest test class **'TestInventoryAddStock'**, which tests the behavior of the **'add_stock'** method, with the following tests.
class TestInventoryAddStock:
# Define a pytest class fixture 'setup_class', which creates an **'MobileInventory'** instance with input {'iPhone Model X':100, 'Xiaomi Model Y': 1000, 'Nokia Model Z':25} and assign it to class attribute **'inventory'**.
@classmethod
def setup_class(cls):
cls.inventory=MobileInventory({'iPhone Model X':100, 'Xiaomi Model Y': 1000, 'Nokia Model Z':25} )
# Define a pytest test method **'test_add_new_stock_as_dict'**, which adds the new stock {'iPhone Model X':50, 'Xiaomi Model Y': 2000, 'Nokia Model A':10} to the existing inventory, and update the **balance_inventory** attribute. Also, check if the updated **balance_inventory** equals {'iPhone Model X':150, 'Xiaomi Model Y': 3000, 'Nokia Model Z':25, 'Nokia Model A':10} using assert.
def test_add_new_stock_as_dict(self):
self.inventory.add_stock({'iPhone Model X':50, 'Xiaomi Model Y': 2000, 'Nokia Model A':10})
assert self.inventory.balance_inventory=={'iPhone Model X':150, 'Xiaomi Model Y': 3000, 'Nokia Model Z':25, 'Nokia Model A':10}
# Define a pytest test method **'test_add_new_stock_as_list'**, which adds the new stock ['iPhone Model X', 'Xiaomi Model Y', 'Nokia Model Z'] to the existing inventory, and which checks if the method raises a TypeError with the message "Input stock must be a dictionary" using assert.
def test_add_new_stock_as_list(self):
my_dict_as_list = ['iPhone Model X', 'Xiaomi Model Y', 'Nokia Model Z']
message="Input stock must be a dictionary"
with pytest.raises(TypeError):
assert message ==self.inventory.add_stock(my_dict_as_list)
# MobileInventory.add_stock(self,my_dict_as_list)
# Define a pytest test method **'test_add_new_stock_with_numeric_keys'**, which adds the new stock {1:'iPhone Model A', 2:'Xiaomi Model B', 3:'Nokia Model C'} to the existing inventory, and which checks if the method raises a ValueError with the message "Mobile model name must be a string" using assert.
def test_add_new_stock_with_numeric_keys(self):
my_dict_as_list = {1:'iPhone Model A', 2:'Xiaomi Model B', 3:'Nokia Model C'}
message= "Mobile model name must be a string"
with pytest.raises(ValueError):
assert message ==self.inventory.add_stock(my_dict_as_list)
# Define a pytest test method **'test_add_new_stock_with_nonnumeric_values'**, which adds the new stock {'iPhone Model A':'50', 'Xiaomi Model B':'2000', 'Nokia Model C':'25'} to the existing inventory, and which checks if the method raises a ValueError with the message "No. of mobiles must be a positive integer" using assert.
def test_add_new_stock_with_nonnumeric_values(self):
message= "No. of mobiles must be a positive integer"
my_dict_as_string= {'iPhone Model A':'50', 'Xiaomi Model B':'2000', 'Nokia Model C':'25'}
with pytest.raises(ValueError):
assert message==MobileInventory.add_stock(self,my_dict_as_string)
# Define a pytest test method **'test_add_new_stock_with_float_values'**, which adds the new stock {'iPhone Model A':50.5, 'Xiaomi Model B':2000.3, 'Nokia Model C':25} to the existing inventory, and which checks if the method raises a ValueError with the message "No. of mobiles must be a positive integer" using assert.
def test_add_new_stock_with_float_values(self):
message= "No. of mobiles must be a positive integer"
my_dict_as_float = {'iPhone Model A':50.5, 'Xiaomi Model B':2000.3, 'Nokia Model C':25}
with pytest.raises(ValueError):
assert message==MobileInventory.add_stock(self,my_dict_as_float)
# Define another pytest test class **'TestInventorySellStock'**, which tests the behavior of the **'sell_stock'** method, with the following tests.
class TestInventorySellStock:
stock_as_list_message="Requested stock must be a dictionary"
stock_as_numeric_key_message="Mobile model name must be a string"
stock_as_float_values_message= "No. of mobiles must be a positive integer"
stock_as_non_numeric_message= "No. of mobiles must be a positive integer"
# Define a pytest class fixture 'setup_class', which creates an **'MobileInventory'** instance with the input {'iPhone Model A':50, 'Xiaomi Model B': 2000, 'Nokia Model C':10, 'Sony Model D':1}, and assign it to the class attribute **'inventory'**.
@classmethod
def setup_class(cls):
my_dict= {'iPhone Model A':50, 'Xiaomi Model B': 2000, 'Nokia Model C':10, 'Sony Model D':1}
cls.inventory=MobileInventory(my_dict)
# Define a pytest test method **'test_sell_stock_as_dict'**, which sells the requested stock {'iPhone Model A':2, 'Xiaomi Model B':20, 'Sony Model D':1} from the existing inventory, and update the **balance_inventory** attribute. Also check if the updated **balance_inventory** equals {'iPhone Model A':48, 'Xiaomi Model B': 1980, 'Nokia Model C':10, 'Sony Model D':0} using assert.
def test_sell_stock_as_dict(self):
my_dict_as_sell_stock= {'iPhone Model A':2, 'Xiaomi Model B':20, 'Sony Model D':1}
my_dict_balance= {'iPhone Model A':48, 'Xiaomi Model B': 1980, 'Nokia Model C':10, 'Sony Model D':0}
self.inventory.sell_stock(my_dict_as_sell_stock)
assert my_dict_balance == self.inventory.balance_inventory
# Define a pytest test method **'test_sell_stock_as_list'**, which tries selling the requested stock ['iPhone Model A', 'Xiaomi Model B', 'Nokia Model C'] from the existing inventory, and which checks if the method raises a TypeError with the message "Requested stock must be a dictionary" using assert.
def test_sell_stock_as_list(self):
my_dict_as_list= ['iPhone Model A', 'Xiaomi Model B', 'Nokia Model C']
with pytest.raises(TypeError):
assert TestInventorySellStock.stock_as_list_message== MobileInventory.sell_stock(self,my_dict_as_list)
# Define a pytest test method **'test_sell_stock_with_numeric_keys'**, which tries selling the requested stock {1:'iPhone Model A', 2:'Xiaomi Model B', 3:'Nokia Model C'} from the existing inventory, and which checks if the method raises ValueError with the message "Mobile model name must be a string" using assert.
def test_sell_stock_with_numeric_keys(self):
my_dict_as_int = {1:'iPhone Model A', 2:'Xiaomi Model B', 3:'Nokia Model C'}
with pytest.raises(ValueError):
assert TestInventorySellStock.stock_as_numeric_key_message == self.inventory.sell_stock(my_dict_as_int)
# Define a pytest test method **'test_sell_stock_with_nonnumeric_values'**, which tries selling the requested stock {'iPhone Model A':'2', 'Xiaomi Model B':'3', 'Nokia Model C':'4'} from the existing inventory, and which checks if the method raises a ValueError with the message "No. of mobiles must be a positive integer" using assert.
def test_sell_stock_with_nonnumeric_values(self):
my_dict_as_str = {'iPhone Model A':'2', 'Xiaomi Model B':'3', 'Nokia Model C':'4'}
with pytest.raises(ValueError):
assert TestInventorySellStock.stock_as_non_numeric_message == self.inventory.sell_stock(my_dict_as_str)
# Define a pytest test method **'test_sell_stock_with_float_values'**, which tries selling the requested stock {'iPhone Model A':2.5, 'Xiaomi Model B':3.1, 'Nokia Model C':4} from the existing inventory, and which checks if the method raises a ValueError with the message "No. of mobiles must be a positive integer" using assert.
def test_sell_stock_with_float_values(self):
my_dict_as_float={'iPhone Model A':2.5, 'Xiaomi Model B':3.1, 'Nokia Model C':4}
with pytest.raises(ValueError):
assert TestInventorySellStock.stock_as_float_values_message == self.inventory.sell_stock(my_dict_as_float)
# Define a pytest test method **'test_sell_stock_of_Nonexisting_model'**, which tries selling the requested stock {'iPhone Model B':2, 'Xiaomi Model B':5} from the existing inventory, and which checks if the method raises an InsufficientException with the message "No Stock. New Model Request" using assert.
def test_sell_stock_of_Nonexisting_model(self):
my_dict_Nonexisting = {'iPhone Model B':2, 'Xiaomi Model B':5}
message= "No Stock. New Model Request"
with pytest.raises(InsufficientException):
assert message == self.inventory.sell_stock(my_dict_Nonexisting)
# Define a pytest test method **'test_sell_stock_of_insufficient_stock'**, which tries selling the requested stock {'iPhone Model A':2, 'Xiaomi Model B':5, 'Nokia Model C': 15} from the existing inventory, and which checks if the method raises an InsufficientException with the message "Insufficient Stock" using assert.
def test_sell_stock_of_insufficient_stock(self):
my_dict_insufficient={'iPhone Model A':2, 'Xiaomi Model B':5, 'Nokia Model C': 15}
message= "Insufficient Stock"
with pytest.raises(InsufficientException):
assert message == MobileInventory.sell_stock(self.inventory, my_dict_insufficient)