0% found this document useful (0 votes)
251 views7 pages

Python Mobile Inventory Testing

1) The document defines a MobileInventory class to manage inventory of mobile models and quantities. It allows initializing inventory, adding new stock, and selling stock while validating data types and values. 2) Test classes are defined to test the initialization, stock addition, and stock selling methods. They include tests that validate exception raising for invalid data types or values. 3) The tests utilize the Pytest framework and assertions to validate the MobileInventory class functions as expected under different conditions.

Uploaded by

TECHer YT
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
251 views7 pages

Python Mobile Inventory Testing

1) The document defines a MobileInventory class to manage inventory of mobile models and quantities. It allows initializing inventory, adding new stock, and selling stock while validating data types and values. 2) Test classes are defined to test the initialization, stock addition, and stock selling methods. They include tests that validate exception raising for invalid data types or values. 3) The tests utilize the Pytest framework and assertions to validate the MobileInventory class functions as expected under different conditions.

Uploaded by

TECHer YT
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Part 1: Mobile Inventory Classes
  • Part 2: Inventory Import and Test Creation
  • Part 3: Inventory Testing Classes

------------------------------------------------ HANDS ON PYTEST

class InsufficientException(Exception):

pass

class MobileInventory:

def __init__(self, inventory={}):

if type(inventory) != dict:

raise TypeError("Input inventory must be a dictionary")

elif inventory == {}:

self.balanced_inventory = inventory

elif inventory != {}:

for i in [Link]():

if type(i) != str:

raise ValueError("Mobile model name must be a string")

for i in [Link]():

if type(i) != int or i < 0:

raise ValueError("No. of mobiles must be a positive integer")

self.balanced_inventory = inventory

def add_stock(self, new_stock):

if type(new_stock) != dict:

raise TypeError("Input stock must be a dictionary")

elif new_stock != {}:

for i in new_stock.keys():

if type(i) != str:

raise ValueError("Mobile model name must be a string")

for i in new_stock.values():

if type(i) != int or i < 0:

This study source was downloaded by 100000832806195 from [Link] on 01-10-2022 00:37:01 GMT -06:00

[Link]
raise ValueError("No. of mobiles must be a positive integer")

self.balanced_inventory.update(new_stock)

def sell_stock(self, requested_stock):

if type(requested_stock) != dict:

raise TypeError("Input stock must be a dictionary")

elif requested_stock != {}:

mobileName = []

mobileQuantity = []

for i in requested_stock.keys():

if type(i) != str:

raise ValueError("Mobile model name must be a string")

for i in requested_stock.values():

if type(i) != int or i < 0:

raise ValueError("No. of mobiles must be a positive integer")

for i in requested_stock.keys():

if i not in self.balanced_inventory.keys():

raise InsufficientException("No Stock. New Model Request")

if self.balanced_inventory[i] < requested_stock[i]:

raise InsufficientException("Insufficient Stock")

else:

self.balanced_inventory[i] = (

self.balanced_inventory[i] - requested_stock[i]

PART 2

from [Link] import MobileInventory, InsufficientException

import pytest

This study source was downloaded by 100000832806195 from [Link] on 01-10-2022 00:37:01 GMT -06:00

[Link]
class TestingInventoryCreation:

def test_creating_empty_inventory(self):

c1 = MobileInventory({})

assert c1.balanced_inventory == {}

def test_creating_specified_inventory(self):

c2 = MobileInventory(

{"iPhone Model X": 100, "Xiaomi Model Y": 1000, "Nokia Model Z": 25}

assert c2.balanced_inventory == {

"iPhone Model X": 100,

"Xiaomi Model Y": 1000,

"Nokia Model Z": 25,

def test_creating_inventory_with_list(self):

with [Link](TypeError) as excinfo:

c3 = MobileInventory(["iPhone Model X", "Xiaomi Model Y", "Nokia Model Z"])

assert "Input inventory must be a dictionary" in str([Link])

def test_creating_inventory_with_numeric_keys(self):

with [Link](ValueError) as excinfo:

c4 = MobileInventory(

{1: "iPhone Model X", 2: "Xiaomi Model Y", 3: "Nokia Model Z"}

assert "Mobile model name must be a string" in str([Link])

def test_creating_inventory_with_nonnumeric_values(self):

with [Link](ValueError) as excinfo:

c5 = MobileInventory(

This study source was downloaded by 100000832806195 from [Link] on 01-10-2022 00:37:01 GMT -06:00

[Link]
{

"iPhone Model X": "100",

"Xiaomi Model Y": "1000",

"Nokia Model Z": "25",

assert "No. of mobiles must be a positive integer" in str([Link])

def test_creating_inventory_with_negative_value(self):

with [Link](ValueError) as excinfo:

c6 = MobileInventory(

{"iPhone Model X": -45, "Xiaomi Model Y": 200, "Nokia Model Z": 25}

assert "No. of mobiles must be a positive integer" in str([Link])

PART 3

class TestInventoryAddStock():

def setup_class(cls):

[Link] = MobileInventory({'iPhone Model X': 100, 'Xiaomi Model Y': 1000, 'Nokia Model
Z':25})

def test_add_new_stock_as_dict(self):

with [Link](TypeError) :

MobileInventory.add_stock(['iPhone Model X', 'Xiaomi Model Y', 'Nokia Model Z'])

def test_add_new_stock_as_list(self):

with [Link](TypeError) as excinfo:

MobileInventory(['iPhone Model X', 'Xiaomi Model Y', 'Nokia Model Z'])

assert "Input inventory must be a dictionary" in str([Link])

This study source was downloaded by 100000832806195 from [Link] on 01-10-2022 00:37:01 GMT -06:00

[Link]
def test_add_new_stock_with_numeric_keys(self):

with [Link](ValueError) as excinfo:

MobileInventory({1:'iPhone Model A', 2:'Xiaomi Model B', 3:'Nokia Model C'})

assert "Mobile model name must be a string" in str([Link])

def test_add_new_stock_with_nonnumeric_values(self):

with [Link](ValueError) as excinfo:

MobileInventory({'iPhone Model A':'50', 'Xiaomi Model B': '2000', 'Nokia ModelC':'25'})

assert "No. of mobiles must be a positive integer" in str([Link])

def test_add_new_stock_with_float_values(self):

with [Link](ValueError) as excinfo:

MobileInventory({'iPhone Model A':50.5, 'Xiaomi Model B':2000.3, 'Nokia Model C':25})

assert "No. of mobiles must be a positive integer" in str([Link])

class TestInventorySellStock:

inventory = None

@classmethod

def setup_class(cls):

[Link] = MobileInventory(

"iPhone Model A": 50,

"Xiaomi Model B": 2000,

"Nokia Model C": 10,

"Sony Model D": 1,

This study source was downloaded by 100000832806195 from [Link] on 01-10-2022 00:37:01 GMT -06:00

[Link]
def test_sell_stock_as_dict(self):

[Link].sell_stock(

{"iPhone Model A": 2, "Xiaomi Model B": 20, "Sony Model D": 1}

def test_sell_stock_as_list(self):

with [Link](TypeError):

MobileInventory.sell_stock(

self, ["iPhone Model A", "Xiaomi Model B", "Nokia Model C"]

def test_sell_stock_with_numeric_keys(self):
with [Link](ValueError):

MobileInventory.sell_stock(

self, {1: "iPhone Model A", 2: "Xiaomi Model B", 3: "Nokia Model C"}

def test_sell_stock_with_nonnumeric_values(self):

with [Link](ValueError):

MobileInventory.sell_stock(

self,

{"iPhone Model A": "5", "Xiaomi Model B": "3", "Nokia Model C": "4"},

def test_sell_stock_of_nonexisting_model(self):

with [Link](InsufficientException, match="No Stock. New Model Request"):

[Link].sell_stock({"iPhone Model B": 2, "Xiaomi Model B": 5})

def test_sell_stock_of_insufficient_stock(self):

This study source was downloaded by 100000832806195 from [Link] on 01-10-2022 00:37:01 GMT -06:00

[Link]
with [Link](InsufficientException, match="Insufficient Stock"):

[Link].sell_stock(

{"iPhone Model A": 2, "Xiaomi Model B": 5, "Nokia Model C": 15}

This study source was downloaded by 100000832806195 from [Link] on 01-10-2022 00:37:01 GMT -06:00

[Link]
Powered by TCPDF ([Link])

Common questions

Powered by AI

The error handling in MobileInventory employs both TypeErrors and ValueErrors, along with custom exceptions like InsufficientException, which effectively captures and controls erroneous input conditions. This systematic approach prevents data corruption and ensures that the inventory state remains accurate, contributing significantly to the reliability and stability of the software .

Testing with Pytest enables thorough validation of the MobileInventory class by organizing test scenarios that simulate various inventory operations followed by assertion checks for expected exceptions. It enhances software development by catching errors early, validating function behavior, and ensuring adherence to specified requirements .

The functionality of the MobileInventory class is validated through unit tests that cover various scenarios, including creation of inventories with valid and invalid data types, addition of stocks with incorrect formats, and selling operations that attempt to exceed inventory limits or involve non-existent models. These tests raise expected exceptions to ensure the class's robustness to invalid data .

When attempting to sell a non-existent model or an insufficient number of a model, the MobileInventory class raises an InsufficientException with messages 'No Stock. New Model Request' for non-existing models and 'Insufficient Stock' for insufficient quantities .

The MobileInventory class is effective in handling invalid input through rigorous type and value checks in its methods. It raises appropriate exceptions such as TypeError for non-dictionary input and ValueError for malformed data, such as non-string keys or non-positive integer values, ensuring robustness in its operations .

Without checks preventing inventory levels from going below zero, the MobileInventory class might facilitate unauthorized stock deductions, culminating in inaccurate inventory records and potential business losses. Such deficits could degrade system reliability, lead to unfulfilled orders, financial discrepancies, and could ultimately undermine trust in the system's integrity .

The MobileInventory class requires the new stock to be in dictionary format, with strings for mobile model names and positive integers for quantities. Deviating from this requirement raises a TypeError if the stock is not a dictionary and raises a ValueError if the model names aren't strings or if the quantities aren't positive integers .

The MobileInventory class encapsulates functionality by implementing methods that manage inventory operations within the class, ensuring that only valid transactions alter its state. Type and value validation encapsulated within each method exemplifies encapsulation and reinforces the object-oriented design by safeguarding data integrity through controlled access .

The MobileInventory class maintains immutability by performing checks before operations and updating the inventory only if the new stock data passes strict validation. During sales, it checks inventory levels to ensure quantities are within the available range, preventing unauthorized modifications by raising exceptions when discrepancies are detected .

The inventory dictionary must only use strings as keys for mobile model names and positive integers as values for the quantity of mobiles. The type of the inventory must be a dictionary, otherwise, a TypeError is raised. Any deviation, such as using lists or numeric keys, results in ValueError or TypeError exceptions .

------------------------------------------------ HANDS ON PYTEST
class InsufficientException(Exception):
    pass
 
 
class
raise ValueError("No. of mobiles must be a positive integer")
            self.balanced_inventory.update(
class TestingInventoryCreation:
    def test_creating_empty_inventory(self):
        c1 = MobileInventory({})
        assert
{
                    "iPhone Model X": "100",
                    "Xiaomi Model Y": "1000",
def test_add_new_stock_with_numeric_keys(self):
       with pytest.raises(ValueError) as excinfo:
              MobileInven
def test_sell_stock_as_dict(self):
        self.inventory.sell_stock(
            {"iPhone Model A": 2, "Xiaomi Model B":
with pytest.raises(InsufficientException, match="Insufficient Stock"):
            self.inventory.sell_stock(

You might also like