gpt4 book ai didi

python-3.x - 如何测试使用用户界面的功能

转载 作者:行者123 更新时间:2023-11-28 20:36:57 25 4
gpt4 key购买 nike

我正在尝试测试需要用户交互的功能。问题是我怎样才能以编程方式做到这一点?

这是一个示例,我们要求用户在列表 (main.py) 中选择一个项目:

import tkinter as tk
from tkinter import Button, OptionMenu, StringVar


def ask_for_item_in_list(lst, title, default_index=0):

root, item = tk.Tk(), None
WIDTH, HEIGHT = 300, 120

root.title(title)

root.maxsize(width=WIDTH, height=HEIGHT)
root.minsize(width=WIDTH, height=HEIGHT)
root.resizable(0, 0)

variable = StringVar(root)
variable.set(lst[default_index])

option_menu = OptionMenu(root, variable, *lst)
option_menu.pack(fill="none", expand=True)

def on_close():
# The window has been closed by the user
variable.set(None)
close()

def close():
# It quits mainloop()
root.quit()
# It closes the window
root.destroy()

button_ok = Button(root, text='OK', command=close)
button_ok.pack(fill='none', expand=True)

root.protocol('WM_DELETE_WINDOW', on_close)

# Execution stops here as long as the user has not closed the window or
# pressed ok
root.mainloop()

# We retrieve the selected item
item = variable.get()
if item == 'None':
item = None

return item

if __name__ == '__main__':
lst = ['Item 1', 'Item 2', 'Item 3']
title = 'Select an item'
default_selected_idx = lst.index('Item 2')

selected_item = ask_for_item_in_list(lst, title, default_selected_idx)

print(selected_item)

我使用 pytest 编写所有测试,因为我不能使用面向对象的编程。实际上,代码必须由非专业开发人员维护。

如您所见,我无法以这种方式测试此函数,因为它将等待用户输入 (test_main.py):

from main import ask_for_item_in_list


def test_ask_for_item_in_list():
lst = ['Item 1', 'Item 2', 'Item 3']
title = 'Select an item'

# Here TRY to test if changing the default selected index works
default_selected_idx = lst.index('Item 2')

# Code to simualte that the user as clicked on OK ?
# user.click_button('OK') ?
selected_item = ask_for_item_in_list(lst, title, default_selected_idx)

assert selected_item == 'Item 2'
  • 我需要改变我的编码方式吗?
  • 测试这种功能是否相关?

我多次遇到这个问题(无论使用什么语言),我想知道应该如何以干净的方式完成。

感谢阅读! :)

最佳答案

通常会预先用预期值或特殊值填充用户输入,然后多次调用测试函数。您也可以使用各种工具模拟点击。

在 C++ 中你可以这样做:

int number_of_tests = 10;
int tests_passed = 0;
tests_passed += my_test_function_int(0);
tests_passed += my_test_function_int(-1);
...
tests_passed += my_test_function_string("foo");
tests_passed += my_test_function_string("");
tests_passed += my_test_function_string(" ");
...
return (tests_passed == number_of_tests);

这只是一个如何做到这一点的例子(在我们公司,我们就是这样做的)。此外,为非程序员或新人添加新测试也不是很难。

关于python-3.x - 如何测试使用用户界面的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com