#012_重构用户名 PART3

本文通过一个具体的例子展示了如何简化冗长复杂的单元测试代码,并探讨了每项测试只包含一个断言的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

require File.dirname(__FILE__) + '/../test_helper'      

class UserTest < Test::Unit::TestCase
fixtures :users

def test_full_name_without_middle_initial
user = User.new(:first_name => 'John', :last_name => 'Doe')
assert_equal 'John Doe', user.full_name
end

def test_full_name_with_middle_initial
user = User.new(:first_name => 'John', :middle_initial => 'H', :last_name => 'Doe')
assert_equal 'John H. Doe', user.full_name
end

def test_full_name_with_blank_middle_initial
user = User.new(:first_name => 'John', :middle_initial => '', :last_name => 'Doe')
assert_equal 'John Doe', user.full_name
end
end

这是011中的单元测试代码,是不是很复杂冗长,好吧,让我们来重构一下
# user_test.rb
def test_full_name
assert_equal 'John Doe', full_name('John', nil, 'Doe'), "nil middle initial"
assert_equal 'John H. Doe', full_name('John', 'H', 'Doe'), "H middle initial"
assert_equal 'John Doe', full_name('John', '', 'Doe'), "blank middle initial"
end

def full_name(first, middle, last)
User.new(:first_name => first, :middle_initial => middle, :last_name => last).full_name
end

代码是清晰多了,但有人提出来testing one assertion per test
详见:[url]http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html[/url]
import platform import socket import psutil import wmi from datetime import datetime def get_system_info(): """获取系统和主板信息""" c = wmi.WMI() system_info = { "记录时间": datetime.now().strftime("%Y/%m/%d %A %H:%M:%S.%f")[:-3], "计算机名": socket.gethostname(), "用户名": psutil.users()[0].name, "系统": f"{platform.system()} {platform.release()} {platform.version()}", "系统安装日期": c.Win32_OperatingSystem()[0].InstallDate.split(&#39;.&#39;)[0], "型号": c.Win32_ComputerSystem()[0].Model.strip(), "主板": { "制造商": c.Win32_BaseBoard()[0].Manufacturer, "型号": c.Win32_BaseBoard()[0].Product, "序列号": c.Win32_BaseBoard()[0].SerialNumber }, "BIOS信息": { "版本": c.Win32_BIOS()[0].SMBIOSBIOSVersion, "日期": c.Win32_BIOS()[0].ReleaseDate.split(&#39;.&#39;)[0] } } return system_info def get_cpu_info(): """获取CPU信息""" c = wmi.WMI() cpu = c.Win32_Processor()[0] return { "CPU": f"{cpu.Name} @ {cpu.MaxClockSpeed}MHz", "核心数": cpu.NumberOfCores, "逻辑处理器": cpu.NumberOfLogicalProcessors } def get_memory_info(): """获取内存信息""" c = wmi.WMI() mem_modules = c.Win32_PhysicalMemory() total_mem = sum(int(m.Capacity) for m in mem_modules) // (1024**3) return { "内存": [ f"[{int(m.Capacity)//1024**3}G] {m.Manufacturer} {m.PartNumber.strip()}" for m in mem_modules ], "总内存": f"{total_mem}GB" } def get_disk_info(): """获取存储设备信息""" c = wmi.WMI() disks = c.Win32_DiskDrive() disk_info = [] for disk in disks: if disk.Size: size_gb = int(disk.Size) // (1000**3) disk_info.append( f"[{size_gb}G] {disk.Model.strip()}" ) return {"硬盘": disk_info} def get_gpu_info(): """获取显卡信息""" c = wmi.WMI() gpus = c.Win32_VideoController() return { "显卡": [gpu.Name for gpu in gpus] } def get_network_info(): """获取网络适配器信息""" c = wmi.WMI() adapters = c.Win32_NetworkAdapterConfiguration(IPEnabled=True) net_info = [] for adapter in adapters: if adapter.MACAddress: net_info.append({ "网卡": adapter.Description, "IP地址": adapter.IPAddress[0] if adapter.IPAddress else "", "MAC地址": adapter.MACAddress }) return {"网络适配器": net_info} def collect_system_info(): """收集所有系统信息""" try: full_info = {} full_info.update(get_system_info()) full_info.update({"CPU信息": get_cpu_info()}) full_info.update({"内存信息": get_memory_info()}) full_info.update({"存储信息": get_disk_info()}) full_info.update({"显卡信息": get_gpu_info()}) full_info.update({"网络信息": get_network_info()}) return full_info except Exception as e: return {"error": str(e)} if __name__ == "__main__": info = collect_system_info() for category, details in info.items(): print(f"■■■ {category} ■■■") if isinstance(details, dict): for k, v in details.items(): print(f"{k:>20}: {v}") else: print("\n".join(details)) print()输出的■■■ 记录时间 ■■■ 2 0 2 5 / 0 5 / 1 0 S a t u r d a y 0 0 : 0 3 : 1 2 . 7 9 2 ■■■ 计算机名 ■■■ T h i n k P a d 5 2 ■■■ 用户名 ■■■ x j ■■■ 系统 ■■■ W i n d o w s 1 0 1 0 . 0 . 1 9 0 4 5 ■■■ 系统安装日期 ■■■ 2 0 2 3 1 2 0 2 1 9 2 1 4 2 ■■■ 型号 ■■■ 2 0 M A S 1 7 2 0 0 ■■■ 主板 ■■■ 制造商: LENOVO 型号: 20MAS17200 序列号: L1HF99402GZ ■■■ BIOS信息 ■■■ 版本: N2CET50W (1.33 ) 日期: 20200115000000 ■■■ CPU信息 ■■■ CPU: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz @ 2592MHz 核心数: 6 逻辑处理器: 12 ■■■ 内存信息 ■■■ 内存: [&#39;[16G] Micron 16ATF2G64HZ-2G6E1&#39;, &#39;[16G] Micron 16ATF2G64HZ-2G6E1&#39;, &#39;[16G] Micron 16ATF2G64HZ-2G6E1&#39;, &#39;[16G] Micron 16ATF2G64HZ-2G6E1&#39;] 总内存: 64GB ■■■ 存储信息 ■■■ 硬盘: [&#39;[2048G] ZHITAI TiPlus5000 2TB&#39;, &#39;[1024G] INTEL HBRPEKNX0203AH&#39;] ■■■ 显卡信息 ■■■ 显卡: [&#39;Intel(R) UHD Graphics 630&#39;, &#39;NVIDIA Quadro P1000&#39;] ■■■ 网络信息 ■■■ 网络适配器: [{&#39;网卡&#39;: &#39;Intel(R) Wireless-AC 9560 160MHz&#39;, &#39;IP地址&#39;: &#39;192.168.100.100&#39;, &#39;MAC地址&#39;: &#39;40:74:E0:09:1F:14&#39;}, {&#39;网卡&#39;: &#39;VMware Virtual Ethernet Adapter for VMnet1&#39;, &#39;IP地址&#39;: &#39;192.168.80.1&#39;, &#39;MAC地址&#39;: &#39;00:50:56:C0:00:01&#39;}, {&#39;网卡&#39;: &#39;VMware Virtual Ethernet Adapter for VMnet8&#39;, &#39;IP地址&#39;: &#39;192.168.83.1&#39;, &#39;MAC地址&#39;: &#39;00:50:56:C0:00:08&#39;}] Process finished with exit code 0请出输出改成以下样式,更方便读记录时间: 2024/06/20 周四 14:30:12.45 ■ 计算机名: OFFICE-PC01 ■ 用户名: Admin ■ 系统: Microsoft Windows 11 专业版 10.0.22621 ■ 系统安装日期: 05/03/2023 ■ 型号: Dell OptiPlex 7080 ■ BIOS日期: 11/15/2022 ■ 序列号: 123XYZ456 ■ CPU: Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz ■ 主板: 0W0PGJ ■ 内存: [16G] Samsung M471A2K43DB1-CWE (总计 32GB) ■ 硬盘: [512G] Samsung SSD 870 EVO 500GB/[1T] WDC WD1003FZEX-00K3CA0 (总计 1512GB) ■ 硬盘序列号: S4AZNB0N123456/WD-WMC6S0P78901 ■ 显卡: NVIDIA Quadro P1000/Intel(R) UHD Graphics 630 ■ 网卡1: Intel(R) Ethernet Connection (11) I219-LM IP地址: 192.168.1.100 MAC地址: 00:23:24:99:37:55 ■■■ 收集完成于 2024/06/20 周四 14:31:05.12 ■■■ 请给出完整的代码,我好复制出来进行打包
05-11
void mqtt_parser(CircularQueue *q) { static uint8_t State = 0; // 解析状态 static uint32_t total_length = 0; // 报文长度 static uint8_t remaining_length_bytes = 0; // 剩余长度字节数 static uint8_t timeup_count; // 超时计数器 uint8_t packet_type; uint8_t byte; uint8_t multiplier; uint8_t remaining_length; uint32_t i; uint8_t packet_buff[128]; printf("timeup_count状态 %d\n", timeup_count); while (!Queue_Empty(q)) { printf("\n队列状态 %d\n", State); switch (State) { case 0: // 解析固定报头和剩余长度 if (Queue_Length(q) < 2) return; // 获取第一个字节(偏移量0) Queue_PeekAt(q, 0, &packet_type); packet_type >>= 4; /* 报文类型验证 */ if (packet_type < 1 || packet_type > 14) { Queue_MoveReadIndex(q, 1); // 仅丢弃错误字节 return; } /* 剩余长度解析 */ multiplier = 1; total_length = 0; remaining_length_bytes = 0; remaining_length = 0; do { /* 协议合规性检查 */ if (remaining_length_bytes >= 4)// 协议规定最多4字节 { Queue_MoveReadIndex(q, 1 + remaining_length_bytes); // 丢弃错误报文 State = 0; return;// 立即退出避免死循环 } // 计算当前字节的物理偏移量 Queue_PeekAt(q, 1 + remaining_length_bytes, &byte); remaining_length += (byte & 0x7F) * multiplier; multiplier *= 128; remaining_length_bytes++; } while (byte & 0x80); total_length = 1 + remaining_length_bytes + remaining_length; // 计算报文长度 State = 1; break; case 1: if (Queue_Length(q) < total_length) { if (++timeup_count >= 5) { // 连续5次检测失败 // 仅丢弃当前报文已解析部分 Queue_MoveReadIndex(q, 1 + remaining_length_bytes); State = 0; timeup_count = 0; BUZZER_Test(); /* 蜂鸣器播放音乐 */ } return; } else { timeup_count = 0; // 成功获取数据时清零 } // 批量拷贝数据(使用PeekAt实现零拷贝) for (i = 0; i < total_length; i++) { Queue_PeekAt(q, i, &packet_buff[i]); } for (i = 0; i < total_length; i++) { printf("0x%02X ", packet_buff[i]); } // delay_ms(3000); // 打印调试时,使2个报文产生间隔 // Aliyun_Iot((char *)packet_buff); Queue_MoveReadIndex(q, total_length); // 一次性移除已读取数据 State = 0; total_length = 0; remaining_length_bytes = 0; timeup_count = 0; break; } } }修改为零拷贝方案,怎么调用下面的函数/* 2、服务端确认连接建立 S -> C */ char MQTT_ConnAck(char *redata) { char data[] = {0x20, 0x02}; char i = 0; if (redata[0] == data[0] && redata[1] == data[1]) // 确保收到的是合法的CONNACK响应包 { if ((redata[2] & 0xFE) != 0) // 保留位校验 return 0; // 不是合法的CONNACK包 printf("\r\n2、服务端确认连接建立 S -> C\r\n"); switch (redata[3]) { case 0x00: printf("\r\n连接已接受\r\n"); printf("\r\n服务器%s会话\r\n", (redata[2] & 0x01) ? "保留" : "不保留"); // 解析会话标志位 i = 1; break; case 0x01: printf("\r\n协议版本不支持\r\n"); break; case 0x02: printf("\r\n客户端标识符不合格\r\n"); break; case 0x03: printf("\r\n服务端不可用\r\n"); break; case 0x04: printf("\r\n用户名密码无效\r\n"); break; case 0x05: printf("\r\n未授权\r\n"); break; default: printf("\r\n未知错误\r\n"); break; } } return i; // 返回0,不是合法的CONNACK包 }
06-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值