My decorator function doesn't work. The decorator function does not seem to receive the decorated function automatically.
This is the error displayed in the terminal:
TypeError: Browser.check_if_logged() missing 1 required positional argument: 'function'
This is my code:
def check_if_logged(self, function) -> bool:
'''
Decorator class that verify if user is logged or not.\n
IF user IS NOT logged, then execute login on ERP\n
IF user IS logged, then pass.
"
'''
def wrapper():
try:
if self.browser.find_element(By.XPATH, '//*[text()="Login administrativo"]'):
function()
return True
else:
if self.browser.find_element(By.XPATH, '//*[text()="Selecione uma empresa"]'):
pass
except Exception as e:
print('Houve um erro ao validar login:', e)
return False
return wrapper()
@check_if_logged
def to_do_login_erp(self):
try:
input_login = self.browser.find_element(By.XPATH, ERP_INPUT_LOGIN_USERNAME)
input_login.send_keys(USER_NAME_LOGIN)
input_password = self.browser.find_element(By.XPATH, ERP_INPUT_LOGIN_PASSWORD)
input_password.send_keys(PASSWORD_LOGIN)
btn_login = self.browser.find_element(By.XPATH, ERP_BTN_LOGIN)
btn_login.click()
except Exception as e:
print('Erro ao realizar login: ', e)
CodePudding user response:
The question is not stated very clearly, but I would assume that those two functions are in some class.
The problem is that you create a wrapper inside the class. Your wrapper check_if_logged
expects two arguments self
and function
. When you use it as wrapper @
you give only one argument to the function check_if_logged
(this argument is to_do_login_erp
). It doesn't get the self
from the class, even though it is defined there. That is why you need to create wrappers outside the class.
One other thing that might come up later: your function
needs to be returned and not called (so not function()
). The wrapper looks normally like this:
def check_if_logged(function):
def wrapper():
check_something()
return function
return wrapper()
For your purposes I would not use the wrapper, and just directly make a check_if_logged in the function I want to call, because you as well want to use some properties or functions of your class to check if you are logged.
Hope this could help.