I am trying to write a program (API testing) to loop through instance methods in a class. One of the methods "get_one_sale_license" has a variable "self.sale_sgid_in_test" I need to assign this variable each element in the list "sale_list_final" .The variable is used in the instance method as well as the main function. I put a for loop outside the class and it works fine with the output( this is modified part of a single file from the application using framework).
However, I want to remove the loop wrapping the class and try in a more pythonic way.
import json
from datetime import *
from N import NSession
from N import NArgParser
from i_data_provider import iDataProvider
sale_list = open("sales.txt").readlines()
sale_list_final = [s.rstrip() for s in sale_list]
tests_list = open("tests.txt").readlines()
tests_list_final = [t.rstrip() for t in tests_list]
cnt=0
cnt2=0
cnt3=0
cnt6=0
cnt11=0
for i in sale_list_final:
class iDeployChecks:
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
# self.sale_sgid_list = []
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
def get_all_saleable_sales(self):
global cnt2
if cnt2 == 0:
self.i_session.get_sale_seller_info()
self.logger.info('SUCCESS..... Get all sales api\n')
cnt2 += 1
def get_all_sale_dashboard(self):
global cnt6
if cnt6 == 0:
self.i_session.get_All_sale()
self.logger.info('SUCCESS..... Get all sales on dashboard api\n')
cnt6 += 1
def get_current_user_sale_dashboard(self):
global cnt11
if cnt11 == 0:
self.i_session.get_current_user_sale()
self.logger.info('SUCCESS..... Get current sales on dashboard api\n')
cnt11 += 1
def get_one_sale_license(self):
self.logger.info('Getting sale details from:')
self.sale_sgid_list1 = [item.get('salesgid') for item in self.i_session.get_sale_seller_info()]
#self.sale_sgid_list =[item.get('salesgid') for item in self.i_session.get_sale_seller_info() if item.get('salesgid') == i]
print " for sale " + str(i)
self.sale_sgid_in_test = ''.join(i)
self.logger.info('\n')
self.logger.info('Get License for sale with sale sgid {}'.format(self.sale_sgid_in_test))
self.i_session.get_sale_license(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... Get license api\n')
def get_weekly_stats_count(self):
global cnt
if cnt == 0:
self.i_session.get_weekly_statistics()
self.logger.info('SUCCESS..... Weekly statistics api\n')
cnt += 1
def get_sconfig_value_count(self):
self.i_session.get_sconfig_value(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... sconfig api\n')
def main(self):
start = datetime.utcnow()
# check if the method in the list is present in the class, if yes run it.
for j in tests_list_final:
k = "self." + j + "()"
l= [x.strip() for x in j.split(',')]
m= "self."+l[0]+"(self,year)"
n= "self."+l[0]+"(self,year,month)"
if k == str("self.get_all_saleable_sales()"):
if cnt2 == 0:
self.logger.info('Get All sales')
self.get_all_saleable_sales()
self.logger.info('checking if sale with GSID ' + i + ' exists')
if i not in str(self.i_session.get_sale_seller_info()):
print "the sale with GSID " + i + " does not exist !!"
end1 = datetime.utcnow()
self.logger.info('i health check completed in {} seconds.'.format((end1 - start).seconds))
return
else:
print "sale exists !!"
continue
elif k == str("self.get_one_sale_license()"):
self.get_one_sale_license()
continue
elif k == str("self.get_sale_node_status_value()"):
try:
self.logger.info('Get sale node status for sale sgid {}'.format(self.sale_sgid_in_test))
self.get_sale_node_status_value()
except Exception as e: print e
else:
global cnt3
if (cnt3==0):
print '\n'
print " The testcase " +k + "test does not exist,please recheck test name !!"
print '\n'
cnt3 +=1
end = datetime.utcnow()
self.logger.info('IBDL health check completed in {} seconds.'.format((end - start).seconds))
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
iDeployChecks(args.badge, args.environment).main()
Remove the loop and include in the init
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
self.sale_sgid_list = [i for i in sale_list_final]
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
Then loop for the same list element while calling the main
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
for i in sale_sgid_list:
iDeployChecks(args.badge, args.environment,i).main()
Related
I am trying to pass this eligable list to my template so that I can display it in my website but when I run the website it says that local variable 'eligable' referenced before assignment. I dont understand because this is the only time I used the word eligable in my code.
code:
def specificDate(response):
empName = employeeName.objects.all
if 'checkEmployee' in response.POST:
n = response.POST.get("nameEmployee")
specDate = response.POST.get("date")
if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists():
emp = employeeName.objects.get(employee=n)
t = Name.objects.get(name=emp, date=specDate)
overT = Name.objects.filter(name=emp, overtime=True)
eligable = []
for item in overT:
eligable.append(item.date)
print('Hello')
checkIn = t.timeIn.strftime("%H:%M:%S")
checkOut = t.timeOut.strftime("%H:%M:%S")
datee = datetime.strptime(specDate,'%Y-%m-%d')
print("Here:: ",t.date)
print("Month:: ",datee.month)
messages.info(response, checkIn + ' - ' + checkOut)
return redirect('/specificDate')
else:
messages.info(response, 'Name does not exist')
else:
pass
return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable})
def specificDate(response):
empName = employeeName.objects.all
eligable = []
if 'checkEmployee' in response.POST:
n = response.POST.get("nameEmployee")
specDate = response.POST.get("date")
if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists():
emp = employeeName.objects.get(employee=n)
t = Name.objects.get(name=emp, date=specDate)
overT = Name.objects.filter(name=emp, overtime=True)
eligable = []
for item in overT:
eligable.append(item.date)
print('Hello')
checkIn = t.timeIn.strftime("%H:%M:%S")
checkOut = t.timeOut.strftime("%H:%M:%S")
datee = datetime.strptime(specDate,'%Y-%m-%d')
print("Here:: ",t.date)
print("Month:: ",datee.month)
messages.info(response, checkIn + ' - ' + checkOut)
return redirect('/specificDate')
else:
messages.info(response, 'Name does not exist')
else:
pass
return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable})
The error was correct to be there, because in cases where your control would not inside the if block, eligable list won't get intialized , so after encountering the last statement, it would raise the error.
The fix was to pre-initialize the list beforehand.
# Let's put it all together. Write code for the function process_madlib, which takes in
# a string "madlib" and returns the string "processed", where each instance of
**# "NOUN" is replaced with a random noun and each instance of "VERB" is
# replaced with a random verb. You're free to change what the random functions
**# return as verbs or nouns for your own fun, but for submissions keep the code the way it is!****
from random import randint
def random_verb():
random_num = randint(0, 1)
if random_num == 0:
return "run"
else:
return "kayak"
def random_noun():
random_num = randint(0,1)
if random_num == 0:
return "sofa"
else:
return "llama"
def word_transformer(word):
if word == "NOUN":
return random_noun()
elif word == "VERB":
return random_verb()
else:
return word[0]
def process_madlib(text):
proc =""
lenght = len("NOUN")
i=0
while text[i:i+lenght] !='':
i +=1
if text[i:1+lenght] == "NOUN":
proc= text[i:-1] + word_transformer("NOUN") + text[i+lenght:]
return proc
**
**# you may find the built-in len function useful for this quiz
# documentation: https://docs.python.org/2/library/functions.html#len**
**
test_string_1 = "ds NOUN ds"
test_string_2 = "I'm going to VERB VERB to the store and pick up a NOUN or two."
print process_madlib(test_string_1)
print process_madlib(test_string_2)
Always Return none , if i tested it manually and change "i" all look good
edit : adding code ......
your can read the instruction in the comments
Your code has a few issues with the variable you're using in the loop, specifically you should be using lenght + i instead of lenght + 1. Also, you're incrementing i in the wrong spot.
Here's a version that works:
def process_madlib(text):
proc = ""
lenght = len("NOUN")
i = 0
while text[i:lenght + i] != '':
if text[i:lenght + i] == "NOUN":
proc = text[i:-1] + word_transformer("NOUN") + text[i + lenght:]
return proc
i += 1
return text
test_string_1 = "NOUN ds"
test_string_2 = "I'm going to VERB to the store and pick up a NOUN or two."
print(process_madlib(test_string_1))
print(process_madlib(test_string_2))
It looks like you misspelled "lenght". It should be "length".
Aside from that, what I think you are trying to use is len(i).
Here is the code in the middle.
while text[i:len(text)+1] !='':
i +=1
if text[i:len(text)+1] == "NOUN":
proc= text[i:-1] + word_transformer("NOUN") + text[i+len(text):]
return proc
edited based on Aran-Fey's comment.
Hi guys i got my code to work by putting everything in one function which is this
spam = ''
def enterList (names):
newList = []
while True:
names = raw_input('list a series of items and press blank when finished: ')
if names == '':
break
newList = newList + [names]
a = ''
finalText = ''
listOfStuff = []
item = 0
for i in newList:
if item < len(newList)-2:
a = (i + ', ')
listOfStuff.append(a)
item +=1
elif item == len(newList)-2:
a = (i + ' and ')
listOfStuff.append(a)
item +=1
else:
a = i
listOfStuff.append(a)
break
finalText = finalText.join(listOfStuff)
return finalText
print enterList(spam)
So the above code works as i want it to. However i was trying to do the same thing by having two separate functions, the issue that i was having was that i couldn't take the return value of one function and use it in the next function.
This is the old code
spam = ''
def enterList (names):
newList = []
while True:
names = raw_input('list a series of items and press blank when finished: ')
if names == '':
break
newList = newList + [names]
return newList
print enterList(spam)
def newFunc(Addand):
a = ''
finalText = ''
listOfStuff = []
item = 0
for i in spam:
if item < len(spam)-2:
a = (i + ', ')
listOfStuff.append(a)
item +=1
elif item == len(spam)-2:
a = (i + ' and ')
listOfStuff.append(a)
item +=1
else:
a = i
listOfStuff.append(a)
break
finalText = finalText.join(listOfStuff)
return finalText
newFunc(spam)
print newFunc (spam)
I'm not sure what I was doing wrong doing it this way.
Thanks for any help to get my head around the error with this approach.
In your first function make the return statement
return newFunc(newlist)
It's not working because the second function is never actually called.
I don't understand. When I run the SaveModule.open function in this code, it's able to save ShoppingCart.items_in_cart in the correct variable correctly, but not users. Did I do something wrong in this code?
(I realize this might not be the most efficient code in the world, it's still a work in progress. Just trying to get everything working first.)
I tested this in the IDLE program, and everything worked the way it was supposed to, I just don't get what I did wrong here.
As for why I'm trying to do this, it's just a challenge I set for myself. Nothing more.
import os
import linecache
import ast
users = {}
logged_in = False
mspw = '00415564'
class ShoppingCart(object):
#Creates shopping cart objects for users of our fine website.
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def __repr__(self):
return(self.customer_name)
def __str__(self):
print('Hello ' + self.customer_name)
print('You have ' + str(len(self.items_in_cart)) + ' items in your cart.')
for item in self.items_in_cart:
print(' ' + item, self.items_in_cart[item])
return('Thank you for shopping at Job Simulator!')
def add_item(self, product, price):
#add a product to the cart
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print(product + ' added.')
else:
print(product + ' is already in the cart.')
def change_price(self, product, price):
if product in self.items_in_cart:
self.items_in_cart[product] = price
print('Price Changed')
else:
print('Impossible!')
def change_item(self, product, newproduct):
if product in self.items_in_cart:
tempstor = self.items_in_cart[product]
del self.items_in_cart[product]
self.items_in_cart[newproduct] = tempstor
print('Item changed')
else:
print('Impossible')
def remove_item(self, product):
#Remove product from the cart.
if product in self.items_in_cart:
del self.items_in_cart[product]
print(product + ' removed.')
else:
print(product + ' is not in the cart.')
class UserModule(object):
def add_user(usnm, pswd):
if logged_in == False:
if not usnm in users:
users[usnm] = pswd
s = True
else:
s = False
else:
s = False
return s
def remove_user(usnm, pswd):
if logged_in == False:
if usnm in users:
if pswd == users[usnm]:
del users[usnm]
s = True
else:
s = False
else:
s = False
else:
s = False
return s
def check_users(mst):
if mst == mspw:
for item in users:
print(' ' + item, users[item])
else:
print('Need master password')
class SaveModule(object):
def save(file):
svflu = open(file + '.sbcu', 'w')
svfli = open(file + '.sbci', 'w')
svflu.truncate()
svfli.truncate()
svflu.write(str(users))
svfli.write(str(ShoppingCart.items_in_cart))
svflu.close()
svfli.close()
def open(file):
if os.path.isfile(file + '.sbcu') and os.path.isfile(file + '.sbci'):
svfl = open(file + '.sbcu', 'r')
users = ast.literal_eval(linecache.getline(file + '.sbcu', 1))
svfl.close()
svfl = open(file + '.sbci', 'r')
ShoppingCart.items_in_cart = ast.literal_eval(linecache.getline(file + '.sbci', 1))
svfl.close()
else:
print('This file doesn\'t exits.')
I fixed the problem; it was solved by nesting the users variable inside the UserModule module. I don't know why that fixed it; if anyone can answer that, then let me know.
Alright so what I am trying to do is to get objects to save in list form when a user creates a NoteSet. It appends the objects to the list db properly when I input NoteSet('ex','example',True). I made a function called makeNewNoteSet() and it seems to be working correctly but it doesnt append to the db list. I can not figure out why.
import sys
import datetime
import pickle
notesets = []
db = []
def save():
global db
filename = "notesets.dat"
file = open(filename, "wb")
if file == None:
print("There was an error creating your file")
return
pickle.dump(db, file)
file.close()
print("Saved words to ",filename)
def load():
global db
filename = "notesets.dat"
file = open(filename, "rb")
db = pickle.load(file)
print("There are ",len(db)," Note Sets")
file.close()
class NoteSet:
nextseqNum = len(db)+2
def __init__(self,name,description,hidden):
global db
self.seqNum = NoteSet.nextseqNum
self.name = name
self.description = description
self.dateCreated = datetime.date.today()
self.hidden = hidden
self.notes = list()
NoteSet.nextseqNum += 1
print(self)
notesets.append(self)
notelist = [self.seqNum,self.name,self.description,self.dateCreated,self.hidden,self.notes]
print(notelist)
db.append(notelist)
NoteSet.nextseqNum += 1
def __str__(self):
printstr = str(self.seqNum),self.name,self.description,str(self.dateCreated)
printstr = str(printstr)
return printstr
class Note:
nextseqNum = 0
def __init__(self,text,dateCreated,description,category,priority,hidden):
self.text = text
self.dateCreated = str
self.dateRead = str
self.description = str
self.category = str
self.priority = int
self.hidden = bool
self.seqNum = Note.nextseqNum
Note.nextseqNum += 1
def main():
while True:
load()
printMainMenu()
selection = int(input("? "))
if selection == 1:
listNoteSets()
elif selection == 2:
listAllNoteSets()
elif selection == 3:
makeNewNoteSet()
elif selection == 4:
selectNoteSet() # this makes the working note set
elif selection == 5:
deleteNoteSet()
elif selection == 6:
sys.exit()
else:
print("Invalid choice")
def printMainMenu():
print("1. List note sets")
print("2. List all note sets (including hidden sets)")
print("3. Make a new note set")
print("4. Select a working note set")
print("5. Delete a note set")
print("6. Quit")
def listNoteSets():
num = 0
for row in db:
if db[num][4] == False:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def listAllNoteSets():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def makeNewNoteSet():
num = 0
name = input("What would you like to name your note set? --- ")
for row in db:
if name == db[num][1]:
print("That note set has already been created")
makeNewNoteSet()
description = input("Describe your note set briefly --- ")
hidden = input("Would you like this note set to be hidden? --- ")
if hidden == 'y' or 'yes':
hidden = True
else:
hidden = False
NoteSet(name, description, hidden)
print("noteset created you can now access it through the menu")
input("[Press enter to return to menu]")
main()
def selectNoteSet():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
response = input("Enter the number assosciated with the noteset you would like to access")
print("Note set #",response," was selected")
main()
After you add a new note in makeNewNoteSet(), you call main() which calls load() which overwrites the in-memory copy of the database you just changed. You probably want to call save() somewhere in there.