【发布时间】:2018-01-16 12:51:48
【问题描述】:
我正在为一个 GUI 应用程序编写一个测试自动化框架,我想使用装饰器来捕获由类中的方法(例如登录)生成的弹出窗口
我有一个_BaseWindow 类,它跟踪每个窗口中的GUI 元素(例如:菜单栏、弹出窗口),它由MainWindow 类继承。 MainWindow 类跟踪主菜单上的按钮,以及单击其中一个按钮时生成的对话框。例如,如果您单击主菜单上的登录按钮,则会加载登录对话框。
class _BaseWindow(object):
def __init__(self):
self.window = "windowName"
self.popup = None
def _catch_popups(self, method):
from functools import wraps
@wraps(method)
def wrapper(*args, **kwargs):
# get a list of the open windows before the method is run
before = getwindowlist()
retval = method(*args, **kwargs)
# get a list of the open windows after the method is run
after = getwindowlist()
for window in after:
if window not in before:
self.popup = window
break
return retval
return wrapper
class MainWindow(_BaseWindow):
def __init__(self):
self.dialog = None
self.logged_in = False
# buttons
self.login_button = "btnLogin"
super(MainWindow, self).__init__()
def click_login(self):
if not self.dialog:
mouseclick(self.window, self.login_button)
self.dialog = LoginDialog()
class LoginDialog(_BaseWindow):
def __init__(self):
# buttons
self.button_ok = "btnLoginOK"
self.button_cancel = "btnLoginCancel"
# text input
self.input_username = "txtLoginUsername"
self.input_password = "txtLoginPassword"
super(LoginDialog, self).__init__()
@MainWindow._catch_popups
def perform_login(self, username, password):
input_text(self.input_username, username)
input_text(self.input_password, password)
mouseclick(self.window, self.button_ok)
当我尝试对此进行测试时,我得到:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "objects/gui.py", line 185, in <module>
class LoginDialog(_BaseWindow):
File "objects/gui.py", line 236, in LoginDialog
@MainWindow._catch_popups
TypeError: unbound method _catch_popups() must be called with
MainWindow instance as first argument (got function instance instead)
当我尝试将MainWindow instance 指定为:
@MainWindow._catch_popups(self)
我明白了:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "objects/gui.py", line 185, in <module>
class LoginDialog(_BaseWindow):
File "objects/gui.py", line 236, in LoginDialog
@MainWindow._catch_popups(self)
NameError: name 'self' is not defined
对于理解这一点的任何帮助将不胜感激。
【问题讨论】:
-
您需要将
_catch_popups设为static method。
标签: python class inheritance decorator class-method