I currently have a problem where I just do not know how to solve it.
In the controller I run a measurement, in the view I want to implement a progressbar.
To implement the progressbar in the view with the help of a StepValue, so how many steps per second, I need two values from the controller.
In the constructor in the controller I instantiate two StringVars, which are empty at the beginning. In the measurement, with the help of a method from the DeviceLibary, the method is to be called, which returns the times and these are to update the StringVars with the help of the set method.
In the view, the step value should be calculated from this, but apparently the StringVars are not updated.
class Controller():
def __init__(self):
super().__init__()
self.paramset = Paramset() #get parameters
self.get_test_done_time = tkinter.StringVar()
self.get_sample_period = tkinter.StringVar()
def measure_data(self, port):
try:
self.dev = Device(port) #Device is a libary
except Exception:
messagebox.showerror("Error", "No COM-Port")
return None
try:
self.dev.set_curr_range(self.paramset.curr_range[0].get())
self.dev.set_sample_rate(float(self.paramset.sampleRate[0].get()))
t, volt, curr = self.dev.run_test("cyclic", display='pbar',
filename=self.paramset.textdata[0].get())
self.get_test_done_time.set(self.dev.get_test_done_time())
self.get_sample_period.set(self.dev.get_sample_period())
self.dev.stop_test()
self.dev.close()
def start_test(self, port):
self.worker = threading.Thread(target=self.measure_data, args=(port,))
self.worker.start()
Class View:
def __init__(self):
self.controller = Controller()
self.percentLabel = Label(textvariable=self.percent)
self.progress_frame = ttk.Frame(self)
self.pb = ttk.Progressbar(self.progress_frame, orient=tk.HORIZONTAL, length=200)
self.pb.pack()
self.progress_frame.grid(row=len(vars(self.controller.paramset)) - 6, column=0)
self.start_button = ttk.Button(self.buttonframe, text="Start Test", command=lambda: self.start_measurement(self.portVar.get()) or self.start_progress_bar()) #start measurement = start_test in controller
def progress(self):
if self.variable.get() == "Cyclo":
if self.controller.worker.is_alive():
self.stepValue = float(self.controller.get_test_done_time.get())/ float(self.controller.get_sample_period.get())
while self.pb["value"] < 100:
self.pb['value'] += self.stepValue
self.percentLabel['text'] = self.update_progress_label()
time.sleep(1.2)
self.update_idletasks()
if self.pb["value"] == 100:
self.pb["value"] = 0
self.percentLabel['text'] = "Current Progress: 0.0%"
self.pb.stop()
self.update_idletasks()
def start_progress_bar(self):
self.progress_worker = threading.Thread(target = lambda:self.progress())
self.progress_worker.start()
Error:
Exception in thread Thread-2 (<lambda>):
Traceback (most recent call last):
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
self.run()
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\xxx\xxx\xxx\xxx\View.py", line 265, in <lambda>
self.progress_worker = threading.Thread(target = lambda:self.progress())
File "C:\Users\xxx\xxx\xxx\xxx\xxx\View.py", line 252, in progress
self.stepValue = float(self.controller.get_test_done_time.get())/ float(self.controller.get_sample_period.get())
ValueError: could not convert string to float: ''
Related
I need to loadtest an Odoo Environment and I have written a test class with different methods in it. Currently I'm trying to test this stuff locally but I'm running in a error that I don't understand right now.
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 908, in gevent._gevent_cgreenlet.Greenlet.run
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/users.py", line 175, in run_user
user.run()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/users.py", line 143, in run
self._taskset_instance.run()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 365, in run
self.wait()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 443, in wait
self._sleep(self.wait_time())
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 418, in wait_time
return self.user.wait_time()
TypeError: <lambda>() missing 1 required positional argument: 'instance'
2022-10-20T11:30:13Z <Greenlet at 0x7f49e55376a0: run_user(<__main__.OdooTestCasesUser object at 0x7f49e51f46)> failed with TypeError
I have written the following test classes
class OdooTestCases(TaskSet):
weight = 10
fixed_count = 1
min_wait = 0.5
max_wait = 5.0
#task(20)
def read_partners(self):
customer_model = self.client.get_model("res.partner")
customer_ids = customer_model.search([], limit=80)
#task(10)
def read_product_template_qty(self):
customer_model = self.client.get_model("product.template")
customer_ids = customer_model.search([], limit=80)
#task(10)
def read_sale_orders(self):
so_model = self.client.get_model("sale.order")
so_ids = so_model.search([], limit=100)
#task(20)
def read_stock_pickings(self):
stock_picking_model = self.client.get_model("stock.picking")
stock_pickings = stock_picking_model.search([], limit=100)
#task(20)
def read_stock_movings(self):
stock_moving_model = self.client.get_model("stock.move")
stock_movings = stock_moving_model.search([], limit=100)
#task(30)
def read_stock_locations(self):
stock_location_model = self.client.get_model("stock.location")
stock_locations = stock_location_model.search([], limit=100)
#task(25)
def read_stock_picking_types(self):
stock_picking_type_model = self.client.get_model("stock.picking.type")
stock_picking_types = stock_picking_type_model.search([], limit=100)
def stop(self):
self.interrupt()
class OdooTestCasesUser(OdooLocustUser):
wait_time = between(0.500, 5)
host = "localhost"
database = "demo"
login = "test"
password = "test"
def __init__(self, parent):
super().__init__(parent)
self.login = "test"
self.password = "test"
self.wait_time = between(0.500, 5)
self.tasks = [OdooTestCases]
Another problem is that I don't get test results returned on my CLI.
I tried everything to fix this, what I've found on the internet, but without any success.
I would be really happy if someone could give me a guess or a solution.
Just hit me up if someone needs more information about this case.
Looks like you are using legacy style wait times:
min_wait = 0.5
max_wait = 5.0
AND new style
wait_time = ...
Maybe remove the legacy ones?
When I type into the entrybox, while i expect the console to print what i've typed the following error is raised:
Traceback (most recent call last):
File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
TypeError: callback() takes 1 positional argument but 4 were given
class Editor:
def __init__(self,master):
self.master = master
self.edit_frame = tk.Frame(self.master)
self.elem_frame = tk.Frame(self.master)
self.naz = Nazioni()
paesi = [*self.naz.iso3]
print(paesi)
self.comb_paese = ttk.Combobox(self.edit_frame, value = paesi)
self.comb_paese.current(1)
self.kwordvar= tk.StringVar()
entry_keyword = tk.Entry(self.edit_frame, textvariable=self.kwordvar)
self.kwordvar.trace_add("write",self.callback)
writer = tk.Text(self.edit_frame)
writer.grid(row=0,column=0)
entry_keyword.grid(row=1, column=1)
self.comb_paese.grid(row=1, column = 0)
self.elem_frame.grid(row=0, column = 1)
self.edit_frame.grid(row=0,column=0)
def callback(self):
print(self.kwordvar)
The Editor class is being called with self.newWindow= tk.Toplevel(self.master) as argument, don't know if it has anything to do here but while searching for a solution I've read something about it.
I am trying to upload some files to a website and so far I've tried everything I could find and nothing is working. The html input element won't let me sendKeys to it so I found this class to try and use it.
class SystemDialog:
RECURSION_LIMIT = 20
def __init__(self, application_pid, dialog_title=None):
self.__path_to_file = None
self.__recursions = 0
self.dialog_title = "Open" if dialog_title is None else dialog_title
self.accept_button = "&SaveButton" if self.dialog_title == "Save As" else "&OpenButton"
self.decline_button = "&CancelButton"
app = pywinauto.application.Application()
app.connect(process=application_pid)
self.dialog = app.window(title=self.dialog_title)
def __wait_for_dialog(self):
start = time.time()
while not self.dialog.exists() and (time.time() - start) <= 10:
time.sleep(1)
if not self.dialog.exists():
raise Exception("System Dialog did not show in 10 seconds")
def input_file_path(self, path_to_file):
self.__wait_for_dialog()
self.__path_to_file = path_to_file
if path_to_file is not None:
self.dialog.set_focus()
self.dialog.Edit.type_keys(self.__path_to_file)
return self
def accept(self):
if self.__recursions == SystemDialog.RECURSION_LIMIT:
raise Exception("Not able to accept the System dialog.")
self.__wait_for_dialog()
self.dialog.set_focus()
self.dialog[self.accept_button].click()
if self.dialog.exists():
self.__recursions += 1
if self.__path_to_file is not None:
return self.input_file_path(self.__path_to_file).accept() # <--- FYI Recursion
else:
raise Exception("Trying to accept dialog without any inputs, not gonna work.")
self.__recursions = 0
def decline(self):
if self.__recursions == SystemDialog.RECURSION_LIMIT:
raise Exception("Not able to decline the System dialog.")
self.__wait_for_dialog()
self.dialog.set_focus()
self.dialog[self.decline_button].click()
if self.dialog.exists():
self.__recursions += 1
return self.decline() # <--- Recursion
self.__recursions = 0
Here is the HTML as well
HTML
Here is me trying to send the files in my python code:
#Upload files
click(driver, 5, By.XPATH, '//*[#id="dm-react-shared-container"]/div/div[10]/div/div[1]/div[1]/div[2]/div[1]/div/div/div[5]/div/div[2]/div/div[2]', False)
click(driver, 5, By.XPATH, '//*[#id="downshift-0-label"]/div[1]/button', False)
process = psutil.Process(driver.service.process.pid) # chromedriver pid
pid = process.children()[0].pid # chrome tab pid
dialog = SystemDialog(application_pid=pid)
dialog.input_file_path(path)
dialog.accept()
I am met with this error:
Traceback (most recent call last):
File "blaineus_v2.py", line 331, in <module>
main()
File "blaineus_v2.py", line 64, in main
uploadPDFs(destination, driver, email, password, projectName)
File "blaineus_v2.py", line 324, in uploadPDFs
dialog.input_file_path(path)
File "blaineus_v2.py", line 91, in input_file_path
self.__wait_for_dialog()
File "blaineus_v2.py", line 88, in __wait_for_dialog
raise Exception("System Dialog did not show in 10 seconds")
Exception: System Dialog did not show in 10 seconds
Suppose I am adding a large number of lines to a curses screen.
Minimal non-working example:
import curses
class MyApp(object):
def __init__(self, stdscreen):
self.screen = stdscreen
for i in range(0,100):
self.screen.addstr(str(i) + '\n')
self.screen.refresh()
self.screen.getch()
if __name__ == '__main__':
curses.wrapper(MyApp)
The above code returns:
Traceback (most recent call last):
File "test.py", line 17, in <module>
curses.wrapper(MyApp)
File "/usr/lib/python3.7/curses/__init__.py", line 94, in wrapper
return func(stdscr, *args, **kwds)
File "test.py", line 11, in __init__
self.screen.addstr(str(i) + '\n')
_curses.error: addwstr() returned ERR
Press ENTER to continue
1) What is this error?
2) If the error is because I am adding too many lines to the screen, how could I list those entries with curses? Perhaps with a scroll view of some sort?
It occurred to me that I could use try/except to determine the maximum number of lines that can be printed on the screen to avoid this error:
import curses
class MyApp(object):
def __init__(self, stdscreen):
self.screen = stdscreen
maximum = self.maxlines()
for i in range(maximum):
self.screen.addstr(str(i) + '\n')
self.screen.refresh()
self.screen.getch()
def maxlines(self):
n = 0
try:
for i in range(100):
self.screen.addstr(str(i) + '\n')
n += 1
except:
pass
self.screen.erase()
return n
if __name__ == '__main__':
curses.wrapper(MyApp)
I'm working with Tkinter and I'm trying to create an attribute called wordlist for a main object that belongs to the Main1 class.
This is the Main1 class:
class Main1(Instructions):
def __init__(self, master, wordlist):
super(Main1,self).__init__(master)
self.wordlist = self.readwords()
self.textbox.insert(0.0,self.wordlist)
def create_wdgts(self):
mainlbl = Label(self,text="Tänk på ett ord!")
mainlbl.grid(row=0,column=2)
self.textbox = Text(self, width = 50, height = 5, wrap = WORD)
self.textbox.grid(column=2,row=1)
self.backbttn = Button(self,text="Tillbaka")
self.backbttn["command"] = self.back
self.backbttn.grid(column=5,row=0)
self.pointentry = Entry(self)
self.pointentry.grid(column=2, row=2)
self.pointlbl = Label(self,text = "Poäng:")
self.pointlbl.grid(column = 1, row= 2)
self.pointbttn = Button(self, text="skicka poäng")
self.pointbttn.grid(row= 2, column = 3)
self.pointbttn["command"]= self.pointhndlr()
self.crrctlbl = Label(self, text = "Rätt ord:")
self.crrctlbl.grid(column = 1, row = 3)
self.crrctentry = Entry(self)
self.crrctentry.grid(column = 2, row= 3)
self.crrctbttn = Button(self, text="skicka rätt ord")
self.crrctbttn.grid(row= 3, column = 3)
self.yesbttn = Button(self, text="Ja")
self.yesbttn.grid(row = 4, column=4)
self.nobttn = Button(self, text = "Nej")
self.nobttn.grid(row=4, column=5)
def readwords(self):
"""Returns list with all words in words.txt"""
file = codecs.open("words.txt","r","utf8")
wordlist = []
for word in file:
wordlist.append(word.strip())
return wordlist
def guess(self):
self.guesstemp = random.choice(wordlist)
self.textbox.insert(0.0,"Ange poäng för ordet '"+guesstemp+"': ")
def pointhndlr(self):
pointtemp = self.pointentry.get()
self.pointentry.delete(0)
self.wordlist = remvwords(self.wordlist,self.guesstemp,self.pointtemp,self.guesslist,self.pointlist)
I hope I don't need to post more of the program as this is already a lot of code. Anyway, I get an error message saying that my Main1 object has no wordlist attribute. Why? I created it in the init method!
Grateful for all help.
Sahand
EDIT: The error is traced back to the last line, where I try to change the value of self.wordlist.
The error message is:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", line 1475, in __call__
return self.func(*args)
File "/Users/SahandZarrinkoub/Documents/graphics.py", line 294, in main1
main1.guess()
File "/Users/SahandZarrinkoub/Documents/graphics.py", line 364, in guess
self.textbox.insert(0.0,"Ange poäng för ordet '"+guesstemp+"': ")
NameError: global name 'guesstemp' is not defined
The reason here is that this:
super(Main1,self).__init__(master)
will in turn call this:
def create_wdgts(self):
which will in turn do this:
self.pointbttn["command"]= self.pointhndlr()
This does not assign the function self.pointhndlr to self.pointbttn["command"], instead it calls self.pointhndlr, and assigns the result to self.pointbttn["command"].
The solution: remove the parenthesis:
self.pointbttn["command"]= self.pointhndlr
The way you call super.init is wrong.
You used:
super(Main1,self).__init__(master)
You should use:
super(Main1,self).__init__(self, master)
The way you called it, the object you are creating is not initialized as an Instructions instance. Instead, the master object gets re-initialized or re-cast as an Instructions instance.