How to use item_db method in pytest-django

Best Python code snippet using pytest-django_python

190507x_mini_project.py

Source:190507x_mini_project.py Github

copy

Full Screen

1import shelve2import csv3"Class StockInformation"4class StockInfromation:5 def __init__(self, item_name, item_description, item_selling_price, item_stock_level, item_mac):6 self.item_name = item_name7 self.item_description = item_description8 self.item_selling_price = item_selling_price9 self.item_stock_level = item_stock_level10 self.item_mac = item_mac11#ADD ITEM12def additem():13 print("##############ADD###############")14 item_db = shelve.open("item_db")15 item_name = input("Enter the product name ")16 if item_name in item_db or item_name =="": #Check for duplicate names/ blank17 print('Duplicated Items/Invalid input') #print and go back to the options18 else:19 item_description = input("Enter the product description ")20 while True:21 item_selling_price = input("Enter product's selling price: ") #Check if the product is an integer or string22 try:23 #Try if it's integer convert to float for item_selling_price and break the loop24 item_selling_price = float(item_selling_price)25 break26 except ValueError: # print and loop back27 print(item_selling_price, " is not a integer \nPlease enter again ")28 while True:29 item_stock_level = input("Enter Product's stock level: ")#Check if the product is an integer or string30 try:31 # Try if it's integer convert to float for item_stock_level and break the loop32 item_stock_level = int(item_stock_level)33 break34 # Exception if stock was not an integer35 except ValueError:# print and loop back36 print(item_stock_level, " is not a integer\nPlease enter again \n")37 item_mac = input("Enter the product manufacturer ")38 item = StockInfromation(item_name,item_description,item_selling_price,item_stock_level,item_mac) #Place all the input into a class39 item_db = shelve.open("item_db") #open shelve40 item_db[item_name] = item41 item_db.close()42 print("Item is recorded in the Database ")43#REMOVE ITEM44def removeitem():45 print("###############REMOVE###############")46 item_db = shelve.open("item_db")47 print("""1. Delete all of Inventory\n2. Delete individual Inventory """)48 option = input("Options: ")49 if option == "1":50 for name in item_db: #loop name in item_db to check for item_name51 del item_db[name] # delete all of the products52 print("All Inventories have been deleted ")53 elif option =="2" :54 for name in item_db: #loop name in item_db to check for item_name55 exist = item_db[name] #exist set as a variable key for the data56 print("List of products : {}".format(exist.item_name))57 item_name = input("Enter the item Name {Caps Sensitive} : ")58 if item_name in item_db:59 del item_db[item_name] #Delete inventory base on item_name {user_input}60 print("Item has been deleted")61 else:62 print("Invalid item name")63 item_db.close()64#DISPLAY ITEM65def display_item():66 print("##############Binary###########")67 item_db = shelve.open("item_db")68 list = []69 l = 0 # index70 for name in item_db: # meat and fish71 exist = item_db[name]72 list.append(exist.item_name)73 l +=174 print("{}. List of products : {}".format(l,exist.item_name))75#Binary Sort76 def binary_sort(list, target):77 start = 078 end = len(list) - 179 while start <= end:80 middle = (start + end) // 281 midpoint = list[middle]82 if midpoint > target:83 end = middle - 184 elif midpoint < target:85 start = middle + 186 else:87 return midpoint88#Quicksort89 def quicksort(list):90 if not list:91 return []92 return (quicksort([x for x in list[1:] if x < list[0]])93 + [list[0]] +94 quicksort([x for x in list[1:] if x >= list[0]]))95 user = input("Enter to search product {Caps Sensitive} : ") # User input the product name96 if user in item_db:97 list = quicksort(list) #to sort the list for binary98 bin = binary_sort(list, user)99 if bin in item_db:100 item = item_db[bin]101 print(""" 102 [Item Name] : {}103 [Item Description] : {}104 [Item Selling Price] : ${:.2f}105 [Item Stock Level] : {} Stocks106 [Item Manufacture] : {}""".format(item.item_name, item.item_description, float(item.item_selling_price),107 item.item_stock_level, item.item_mac))108 else:109 print("invalid data")110 else:111 print('Invalid data')112 item_db.close()113#SORTING114#Sort base on the stock and selling price by ascensding order115#Note: Average/Sum features {under progress/later do }116def sort():117 print("##############SORTING###########")118 stock_list = []119 selling_list = []120 item_db = shelve.open("item_db")121 for name in item_db: # meat and fish122 exist = item_db[name]123 stock_list.append(int(exist.item_stock_level))124 selling_list.append(float(exist.item_selling_price))125#Insertion Sort126 def insertionSort(selling_list):127 n = len(selling_list)128 #print("len of n " ,n) #2129 # Starts with the first item as the only sorted entry.130 for i in range(1, n):131 #print("loop",i)132 # Save the value to be positioned133 value = selling_list[i]134 #print("value in the list " ,value)135 # Find the position where value fits in the136 # ordered part of the list.137 pos = i138 while pos > 0 and value < selling_list[pos - 1]: # To compare the first number139 # Shift the items to the right during the search140 selling_list[pos] = selling_list[pos - 1]141 pos -= 1142 # Put the saved value into the open slot.143 selling_list[pos] = value144#Bubble Sort145 def bubbleSort_optimized(stock_list):146 n = len(stock_list)147 # Perform n-1 bubble operations on the sequence148 for i in range(n - 1, 0, -1):149 # Set boolean variable to check occurrence of swapping150 # in inner loop151 # Bubble the largest item to the end152 noSwap = True153 for j in range(i):154 if stock_list[int(j)] > stock_list[int(j) + 1]:155 # swap the j and j + 1 items156 tmp = stock_list[j]157 stock_list[j] = stock_list[j + 1]158 stock_list[j + 1] = tmp159 # Set boolean variable value if swapping occured160 noSwap = False161 # Exit the loop if no swapping occured162 # in the previous pass163 if noSwap:164 break165 sort = input("1. Display by Item selling price\n2. Display the Stock level\nUser input: ")166 #Sort base on the selling price / stock level167 if sort == '1':168 print("##########Displaying Selling price from accending ###########")169 print('Input List:', selling_list)170 print('total list: ',len(selling_list)) #len of the list171 insertionSort(selling_list)172 print('Ascending order')173 print('Sorted List:', selling_list)174 elif sort == '2':175 print("##########Displaying Stock level from accending ###########")176 print('Input List:', stock_list)177 print('total list: ',len(stock_list)) # len of the list178 bubbleSort_optimized(stock_list)179 print('Ascending order')180 print('Sorted List:', stock_list)181 else:182 print('Wrong input')183 pass184#Update Product185#Additonal features ??186#Decide to update selling price / stock level instead187def update_product():188 print("################Update##################")189 item_db = shelve.open("item_db")190 #Show the list of stock191 def list_stock():192 l = 0193 for product_name in item_db: # List all of the products194 l +=1195 print(l,"List of products : {}".format(product_name))196 while True:197 user = input("Enter the product name to make a change {Caps Sensitive} : ")198 #Loop to check user in item_db199 if user in item_db:200 return user201 else:202 print('ERROR : Invalid data')203 #Update selling price204 def update_selling_price(user):205 exist = item_db[user]206 user_value = float(input("Please enter a value for new selling price value {Caps Sensitive} "))207 item = StockInfromation(exist.item_name, exist.item_description, user_value, exist.item_stock_level,208 exist.item_mac)209 item_db[exist.item_name] = item210 print("Product Selling price have been updated in the database")211 #Update stock level212 def update_stock_level(user):213 exist = item_db[user]214 user_value = int(input("Please enter a value for new stock level"))215 item = StockInfromation(exist.item_name, exist.item_description, exist.item_selling_price, user_value,216 exist.item_mac)217 item_db[exist.item_name] = item218 print("Product Stock level have been updated in the database")219 #Options for selling price / stock level220 print("""1) Update Selling Price \n2) Update Stock Level """)221 user_option = input("Please enter an options: ")222 if user_option == "1":223 user = list_stock() #return user224 update_selling_price(user)225 elif user_option == "2":226 user = list_stock() #return user227 update_stock_level(user)228 else:229 print('Invalid Data')230 item_db.sync()231 item_db.close()232#Exporting csv file from shelve233#Additional features (1)234#import csv235def exporting_csv():236 print("#################Exporting == CSV#################")237 item_db = shelve.open('item_db')238 data_dict = [] #dict in list239 #list = []240 header = ["Item Name","Item Description","Item Selling Price","Item Stock level","Item manufacturer"] # header for csv241 for item in item_db:242 exist = item_db[item]243 #list.append(244 #[exist.item_name, exist.item_description, exist.item_selling_price, exist.item_stock_level, exist.item_mac])245 data_dict.append(246 {"Item Name":exist.item_name, "Item Description":exist.item_description, "Item Selling Price":exist.item_selling_price, "Item Stock level":exist.item_stock_level, "Item manufacturer":exist.item_mac})247 def write_csv_from_dicts(data, header): # Write the data from the shelve to the csv file row by row248 with open("Inventory_data_backup.csv", "w") as csv_file: #write the file as csv_file249 dict_writer = csv.DictWriter(csv_file, fieldnames=header)250 dict_writer.writeheader() # write header251 for row in data: #data == data_dict252 dict_writer.writerow(row) # write each row253 write_csv_from_dicts(data_dict, header)254 print("Data has been export to Inventory_data_backup.csv")255 #csv_writer = csv.writer(inventory, delimiter='\t')256 # csv_writer.writerow([exist.item_name, exist.item_description, exist.item_selling_price, exist.item_stock_level,exist.item_mac])257#Importing csv258#read csv file to shelve259#Overwriting common existing data_attributes in the shelve with the csv file data260def importing_csv():261 item_db = shelve.open('item_db')262 list_dict = []263 print("WARNING This will overwrite the existing data you have in shelve \nif you like to leave type Q else Proceed type K")264 option = input("Option : Leave(Q) , Proceed(K) ")265 if option =="k":266 def read_csv(): # read the data from csv file to python and store it into the shelve database267 print("Overwriting with Inventory_data_backup.csv")268 with open("Inventory_data_backup.csv", 'r') as csv_file:269 dict_read = csv.DictReader(csv_file)270 len = 1271 for row in dict_read :272 list_dict.append(row)273 print(len,row['Item Name'])274 len = len + 1275 item = StockInfromation(row['Item Name'], row['Item Description'], row['Item Selling Price'],276 row['Item Stock level'], row['Item manufacturer'])277 item_db[row['Item Name']] = item278 read_csv()279 elif option == "q":280 pass281# Stock Inventory Summary282#View sum/average of the inventory283def stock_summary():284 print("###########################Stock Summary#############################")285 stock_list = []286 item_db = shelve.open("item_db")287 for name in item_db:288 exist = item_db[name]289 stock_list.append(exist.item_stock_level)290 print("""1) Sum of the stock inventory \n2) Average of the stock inventory""")291 option = input("Enter the options : ")292 def sum_stock(): #Sum of the inventory293 sum = 0294 for num in stock_list:295 sum+= int(num)296 return sum297 def average_stock(): #Average of the inventory298 avglen = len(stock_list)299 sum = sum_stock()300 avg = sum /avglen301 return avg302 if option == '1':303 sum = sum_stock()304 print("\nThe total sum of inventory stock is:", sum,"products")305 elif option == "2":306 avg = average_stock()307 print("\nThe average of the total inventory stock is:", avg)308###############################################################################309while True:310 print(" ")311 print('''####################################################################################312Welcome to The EZy Shop Management Panel, select the following option to continue:313-----------------------------------------------------------------3141. Add a new procuct3152. Delete the product3163. View the product3174. Update ~stock value/selling price value3185. Sorting ~ Stock/ selling price ascending order3196. Export to CSV file3207. Import from CSV file3218. Inventory Summary ~ Sum/average of inventory size 3220. Close 323##################################################################''')324 option = input("Please enter your options ")325 print(" ")326 if option == '':327 continue328 if option == '1':329 additem()330 if option == '2':331 removeitem()332 if option == '3':333 display_item()334 if option == '4' :335 update_product()336 if option == "5":337 sort()338 if option == "6":339 exporting_csv()340 if option == "7":341 importing_csv()342 if option == "8":343 stock_summary()344 if option == "0":345 break346 else:...

Full Screen

Full Screen

crud.py

Source:crud.py Github

copy

Full Screen

1from sqlalchemy.orm import Session2import models, schemas3def get_user(db: Session, user_id: int):4 return db.query(models.User).filter(models.User.id == user_id).first()5def login_user(db: Session, email: str, password: str):6 return db.query(models.User).filter(models.User.email == email, models.User.hashed_password == password ).first()7def get_user_by_email(db: Session, email: str):8 return db.query(models.User).filter(models.User.email == email).first()9def get_users(db: Session, skip: int = 0, limit: int = 100):10 return db.query(models.User).offset(skip).limit(limit).all()11def create_user(db: Session, user: schemas.UserCreate):12 db_user = models.User(email=user.email, username=user.username, hashed_password=user.password)13 db.add(db_user)14 db.commit()15 db.refresh(db_user)16 return db_user17def update_user_admin_status(db: Session, user: str):18 user_db = db.query(models.User).filter(models.User.email == user).first()19 user_db.is_admin = True20 db.commit()21 db.refresh(user_db)22 return user_db23def update_answer_correct_status(db: Session, item_id: int, status: bool):24 answer_db = db.query(models.Answer).filter(models.Answer.id == item_id).first()25 answer_db.correct = status26 db.commit()27 db.refresh(answer_db)28 return answer_db29def update_user_data(db: Session, user:schemas.User):30 user_db = db.query(models.User).filter(models.User.email == user.email).first()31 user_db.username = user.username32 if not user.password :33 user_db.hashed_password = user.password34 db.commit()35 db.refresh(user_db)36 return user_db37def update_user_item(db: Session, item_id: int, item:schemas.Item):38 item_db = db.query(models.Item).filter(models.Item.id == item_id).first()39 item_db.title = item.title40 item_db.description = item.description41 db.commit()42 db.refresh(item_db)43 return item_db44def update_item_question(db: Session, item_id: int, item:schemas.Question):45 item_db = db.query(models.Question).filter(models.Question.id == item_id).first()46 item_db.title = item.title47 db.commit()48 db.refresh(item_db)49 return item_db50def update_question_answer(db: Session, item_id: int, item:schemas.Answer):51 item_db = db.query(models.Answer).filter(models.Answer.id == item_id).first()52 item_db.title = item.title53 db.commit()54 db.refresh(item_db)55 return item_db56def delete_user(db: Session, user:schemas.User):57 user_db = db.query(models.User).filter(models.User.email == user.email).first()58 db.delete(user_db)59 db.commit()60def delete_user_game_by_id(db: Session, games_id: int):61 item_db = db.query(models.Item).filter(models.Item.id == games_id).first()62 db.delete(item_db)63 db.commit()64def get_items(db: Session, skip: int = 0, limit: int = 100):65 return db.query(models.Item).offset(skip).limit(limit).all()66def get_item_by_id(db: Session, item_id: int):67 return db.query(models.Item).filter(models.Item.id == item_id).first()68def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):69 db_item = models.Item(**item.dict(), user_id=user_id)70 db.add(db_item)71 db.commit()72 db.refresh(db_item)73 return db_item74def create_game_question(db: Session, question: schemas.QuestionCreate, item_id: int):75 db_question = models.Question(**question.dict(), item_id=item_id)76 db.add(db_question)77 db.commit()78 db.refresh(db_question)79 return db_question80def create_questions_answer(db: Session, answer: schemas.AnswerCreate, question_id: int):81 db_answer = models.Answer(**answer.dict(), question_id=question_id)82 db.add(db_answer)83 db.commit()84 db.refresh(db_answer)...

Full Screen

Full Screen

test_cart_all_in_one_refactor_mock.py

Source:test_cart_all_in_one_refactor_mock.py Github

copy

Full Screen

1'''Shopping Cart Test2 - Purpose: Test Requirements 1 ('add' functionality)3 - Description: Test whether when one item is added into shopping cart,4 the number of item in cart is increased by 1.5 - Requirements:6 1. One can add an item(s) into the cart.7 2. One can check the total number of items from the cart.8 3. There exists the maximum limit of items to the cart.9 4. One can verify the total cost of items in the cart.10'''11import random12from unittest.mock import Mock13import pytest14from cart import Cart15from database import ItemDatabase16# Price table for available item in the cart.17p_table = {18 'apple': 300,19 'orange': 200,20 'strawberry': 500,21}22@pytest.fixture23def cart():24 '''pytest fixture function'''25 return Cart(max_number=5)26def test_add_function(cart):27 '''Test: Requirement I ('add' functionality)28 Test whether when one item is added into shopping cart,29 the number of item in cart is increased by 1.30 '''31 cart.add('apple')32 assert cart.get_number_of_items() == 133def test_get_number_of_items_from_cart(cart):34 '''Test adding one item into empty shopping cart'''35 test_number = 336 for _ in range(test_number):37 item_choice = random.choice(list(p_table.keys()))38 cart.add(item_choice)39 print(f'\nTest>>> Added item: {cart.items}')40 print(f'Test>>> The Number of added items: {len(cart.items)}')41 assert cart.get_number_of_items() == test_number42def test_max_number_limit(cart):43 '''Test the max number of allowed items into shopping cart'''44 for _ in range(cart.max_number):45 item_choice = random.choice(list(p_table.keys()))46 cart.add(item_choice)47 # cart.add('apple')48def test_get_total_price(cart):49 '''Test total cost returned'''50 cart.add('apple')51 cart.add('orange')52 assert cart.get_total_price(p_table) == 50053def test_get_total_price_return_value(cart):54 '''Test total cost returned55 Little modification for mocking using 'return_value' option56 '''57 # Create Mocking nature58 item_db = ItemDatabase()59 item_db.get = Mock(return_value=100)60 cart.add('apple')61 cart.add('orange')62 assert cart.get_total_price(item_db) == 20063def test_get_total_price_side_effect(cart):64 '''Test total cost returned65 Little modification for mocking using 'side_effect' option66 '''67 # Create Mocking nature68 item_db = ItemDatabase()69 # Create a simple simulator70 def simulator(item):71 return p_table.get(item)72 73 # simulator = lambda item: p_table.get(item)74 total_price = 075 for _ in range(5):76 item_choice = random.choice(list(p_table.keys()))77 total_price += p_table.get(item_choice)78 item_db.get = Mock(side_effect= simulator)79 cart.add(item_choice)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-django automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful