4.30

软件测试01(源代码)

 

01

复制代码
from datetime import datetime

# 星期中英文对照表
WEEKDAY_CN = {
    "Monday": "星期一",
    "Tuesday": "星期二",
    "Wednesday": "星期三",
    "Thursday": "星期四",
    "Friday": "星期五",
    "Saturday": "星期六",
    "Sunday": "星期日"
}


def get_weekday(date_str):
    """将日期字符串转换为中文星期"""
    for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d"):
        try:
            date_obj = datetime.strptime(date_str, fmt)
            return WEEKDAY_CN[date_obj.strftime('%A')]
        except ValueError:
            continue
    return "无效日期"


def main():
    print("=== 日期转星期程序 ===")
    print("支持格式:YYYY-MM-DD / YYYY/MM/DD / YYYY.MM.DD")

    while True:
        input_str = input("\n请输入日期(输入 q 退出): ").strip()
        if input_str.lower() == 'q':
            print("程序已退出")
            break

        if not input_str:
            print("错误:输入内容不能为空")
            continue

        result = get_weekday(input_str)
        if result == "无效日期":
            print(f"错误:{input_str} 不是有效日期")
        else:
            print(f"查询结果:{input_str} 是 {result}")


if __name__ == "__main__":
    main()
复制代码

02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import tkinter as tk
from tkinter import messagebox
 
 
def calculate_change():
    # 清空结果栏
    result_text.delete(1.0, tk.END)
 
    try:
        # 获取输入值
        R = int(entry_R.get())
        P = int(entry_P.get())
 
        # 输入验证
        if R < 0 or R > 100:
            messagebox.showerror("错误""价格必须为0-100的整数")
            return
        if P < 0 or P > 100:
            messagebox.showerror("错误""付款金额必须为0-100的整数")
            return
        if P < R:
            messagebox.showerror("错误""付款金额不足")
            return
 
        # 计算找零
        change = P - R
        if change == 0:
            result_text.insert(tk.END, "无需找零")
            return
 
        # 分解货币组合
        N50 = change // 50
        remaining = change % 50
 
        N10 = remaining // 10
        remaining %= 10
 
        N5 = remaining // 5
        remaining %= 5
 
        N1 = remaining
 
        # 构建结果字符串
        result = []
        if N50 > 0:
            result.append(f"50元: {N50}张")
        if N10 > 0:
            result.append(f"10元: {N10}张")
        if N5 > 0:
            result.append(f"5元: {N5}张")
        if N1 > 0:
            result.append(f"1元: {N1}张")
 
        total = N50 + N10 + N5 + N1
        result.append(f"\n总张数: {total}")
 
        # 显示结果
        result_text.insert(tk.END, "\n".join(result))
 
    except ValueError:
        messagebox.showerror("错误""请输入整数")
 
 
# 创建主窗口
root = tk.Tk()
root.title("找零钱最佳组合计算器")
root.geometry("400x300")
 
# 输入区域
frame_input = tk.Frame(root)
frame_input.pack(pady=10)
 
tk.Label(frame_input, text="商品价格 (0-100元):").grid(row=0, column=0, padx=5)
entry_R = tk.Entry(frame_input, width=10)
entry_R.grid(row=0, column=1, padx=5)
 
tk.Label(frame_input, text="付款金额 (0-100元):").grid(row=1, column=0, padx=5)
entry_P = tk.Entry(frame_input, width=10)
entry_P.grid(row=1, column=1, padx=5)
 
# 计算按钮
btn_calculate = tk.Button(root, text="计算找零", command=calculate_change)
btn_calculate.pack(pady=5)
 
# 结果展示区域
result_text = tk.Text(root, height=8, width=30)
result_text.pack(pady=10)
 
root.mainloop()

  03

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import tkinter as tk
from tkinter import ttk, messagebox
 
 
class VendingMachine:
    @staticmethod
    def vend(coin, button):
        """自动售货机核心逻辑"""
        if coin not in [0.5, 1.0] or button not in ["橙汁""啤酒"]:
            return "无效输入:金额或按钮不合法"
 
        if coin == 0.5:
            return f"送出{button}""无找零"
        elif coin == 1.0:
            return f"送出{button}""退回5角硬币"
 
 
class ClassicVendingGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("自动售货机模拟程序")
        self.root.geometry("400x300")
 
        # 初始化变量
        self.coin = tk.DoubleVar(value=0.0)
        self.drink = tk.StringVar()
 
        # 创建界面
        self.create_widgets()
 
        # 配置样式
        self.configure_style()
 
    def configure_style(self):
        """配置经典样式"""
        style = ttk.Style()
        style.configure("TRadiobutton", font=("微软雅黑", 10))
        style.configure("TButton", font=("微软雅黑", 10), width=8)
        style.configure("TLabel", font=("微软雅黑", 10))
 
    def create_widgets(self):
        """创建经典界面组件"""
        main_frame = ttk.Frame(self.root)
        main_frame.pack(padx=20, pady=10, fill=tk.BOTH, expand=True)
 
        # 投币区域
        coin_frame = ttk.LabelFrame(main_frame, text="请拨币")
        coin_frame.pack(fill=tk.X, pady=5)
 
        ttk.Radiobutton(coin_frame, text="无", variable=self.coin, value=0.0).pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(coin_frame, text="五角", variable=self.coin, value=0.5).pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(coin_frame, text="一元", variable=self.coin, value=1.0).pack(side=tk.LEFT, padx=5)
 
        # 商品选择区域
        product_frame = ttk.LabelFrame(main_frame, text="请选择商品")
        product_frame.pack(fill=tk.X, pady=5)
 
        ttk.Button(product_frame, text="啤酒", command=lambda: self.drink.set("啤酒")).pack(side=tk.LEFT, padx=10,
                                                                                            pady=5)
        ttk.Button(product_frame, text="橙汁", command=lambda: self.drink.set("橙汁")).pack(side=tk.LEFT, padx=10,
                                                                                            pady=5)
 
        # 操作按钮
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(pady=10)
 
        ttk.Button(btn_frame, text="确定", command=self.process).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="复位", command=self.reset).pack(side=tk.LEFT, padx=5)
 
        # 输出区域
        output_frame = ttk.LabelFrame(main_frame, text="输出")
        output_frame.pack(fill=tk.X, pady=5)
 
        ttk.Label(output_frame, text="请取饮料:").pack(side=tk.LEFT, padx=5)
        self.drink_label = ttk.Label(output_frame, text="", foreground="blue")
        self.drink_label.pack(side=tk.LEFT)
 
        ttk.Label(output_frame, text="找零:").pack(side=tk.LEFT, padx=5)
        self.change_label = ttk.Label(output_frame, text="", foreground="green")
        self.change_label.pack(side=tk.LEFT)
 
    def process(self):
        """处理购买请求"""
        coin = self.coin.get()
        drink = self.drink.get()
 
        # 输入验证
        if coin == 0.0:
            messagebox.showerror("错误""请先投币!")
            return
        if not drink:
            messagebox.showerror("错误""请选择饮料!")
            return
 
        # 获取结果
        result = VendingMachine.vend(coin, drink)
 
        # 显示结果
        if isinstance(result, tuple):
            self.drink_label.config(text=result[0])
            self.change_label.config(text=result[1])
        else:
            messagebox.showerror("错误", result)
 
    def reset(self):
        """复位所有选项"""
        self.coin.set(0.0)
        self.drink.set("")
        self.drink_label.config(text="")
        self.change_label.config(text="")
 
 
if __name__ == "__main__":
    root = tk.Tk()
    app = ClassicVendingGUI(root)
    root.mainloop()

  04

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import tkinter as tk
from tkinter import ttk, messagebox
 
 
# 服务查询核心逻辑
def check_services(route, cabin, flight_time):
    if route not in ["欧美""国外非欧美""国内"] or cabin not in ["商务舱""经济舱"] or flight_time < 0:
        return ("输入错误""输入错误")
 
    if route == "欧美":
        return ("有食物""可播放电影")
    elif route == "国外非欧美":
        return ("有食物""可播放电影"if cabin == "商务舱" else ("有食物""不可播放电影")
    elif route == "国内":
        if cabin == "商务舱":
            return ("有食物""不可播放电影")
        else:
            return ("有食物""不可播放电影"if flight_time > 2 else ("无食物""不可播放电影")
 
 
class AviationApp:
    def __init__(self, root):
        self.root = root
        self.root.title("航空服务查询系统")
        self.root.geometry("800x600")
 
        self.create_widgets()
        self.setup_test_cases()
 
    def create_widgets(self):
        # 输入区域
        input_frame = ttk.LabelFrame(self.root, text="查询条件", padding=10)
        input_frame.pack(pady=10, fill="x", padx=20)
 
        # 航线选择
        ttk.Label(input_frame, text="航线:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.route_var = tk.StringVar()
        self.route_cb = ttk.Combobox(input_frame, textvariable=self.route_var,
                                     values=["欧美""国外非欧美""国内"], width=15)
        self.route_cb.grid(row=0, column=1, padx=5)
 
        # 舱位选择
        ttk.Label(input_frame, text="舱位:").grid(row=0, column=2, padx=5, pady=5, sticky="w")
        self.cabin_var = tk.StringVar()
        self.cabin_cb = ttk.Combobox(input_frame, textvariable=self.cabin_var,
                                     values=["商务舱""经济舱"], width=15)
        self.cabin_cb.grid(row=0, column=3, padx=5)
 
        # 飞行时间输入
        ttk.Label(input_frame, text="飞行时间(小时):").grid(row=0, column=4, padx=5, sticky="w")
        self.time_entry = ttk.Entry(input_frame, width=10)
        self.time_entry.grid(row=0, column=5, padx=5)
 
        # 操作按钮
        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=10)
 
        ttk.Button(btn_frame, text="查询", command=self.query).pack(side="left", padx=5)
        ttk.Button(btn_frame, text="运行所有测试", command=self.run_all_tests).pack(side="left", padx=5)
        ttk.Button(btn_frame, text="退出", command=self.root.quit).pack(side="left", padx=5)
 
        # 结果展示区域
        result_frame = ttk.LabelFrame(self.root, text="测试报告", padding=10)
        result_frame.pack(fill="both", expand=True, padx=20, pady=10)
 
        # 结果表格
        self.tree = ttk.Treeview(result_frame, columns=("状态""输入""预期""实际"), show="headings")
        self.tree.heading("状态", text="状态")
        self.tree.heading("输入", text="输入条件")
        self.tree.heading("预期", text="预期输出")
        self.tree.heading("实际", text="实际输出")
        self.tree.column("状态", width=80, anchor="center")
        self.tree.column("输入", width=200)
        self.tree.column("预期", width=150)
        self.tree.column("实际", width=150)
 
        vsb = ttk.Scrollbar(result_frame, orient="vertical", command=self.tree.yview)
        hsb = ttk.Scrollbar(result_frame, orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
 
        self.tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")
 
    def setup_test_cases(self):
        self.test_cases = [
            (("欧美""商务舱", 1), ("有食物""可播放电影")),
            (("欧美""经济舱", 5), ("有食物""可播放电影")),
            (("国外非欧美""商务舱", 3), ("有食物""可播放电影")),
            (("国外非欧美""经济舱", 4), ("有食物""不可播放电影")),
            (("国内""商务舱", 1), ("有食物""不可播放电影")),
            (("国内""经济舱", 3), ("有食物""不可播放电影")),
            (("国内""经济舱", 2), ("无食物""不可播放电影")),
            (("南极""商务舱", 5), ("输入错误""输入错误")),
            (("国内""头等舱", 4), ("输入错误""输入错误")),
        ]
 
    def query(self):
        try:
            route = self.route_var.get()
            cabin = self.cabin_var.get()
            time = float(self.time_entry.get())
            result = check_services(route, cabin, time)
            messagebox.showinfo("查询结果",
                                f"食物供应: {result[0]}\n影音服务: {result[1]}")
        except:
            messagebox.showerror("错误""请输入有效的飞行时间")
 
    def run_all_tests(self):
        self.tree.delete(*self.tree.get_children())
        for idx, (input_data, expected) in enumerate(self.test_cases, 1):
            route, cabin, time = input_data
            result = check_services(route, cabin, time)
            status = "通过" if result == expected else "失败"
 
            # 添加颜色标签
            tag = "pass" if status == "通过" else "fail"
            self.tree.insert("""end", values=(
                status,
                f"航线: {route}, 舱位: {cabin}, 时间: {time}h",
                f"{expected[0]}, {expected[1]}",
                f"{result[0]}, {result[1]}"
            ), tags=(tag,))
 
        # 配置标签样式
        self.tree.tag_configure("pass", foreground="green")
        self.tree.tag_configure("fail", foreground="red")
 
 
if __name__ == "__main__":
    root = tk.Tk()
    app = AviationApp(root)
    root.mainloop()

  

 
 
 
posted @ 2025-05-20 22:58  欧吼吼  阅读(17)  评论(0)    收藏  举报