#!/usr/bin/env python #指定使用Python解释器执行此脚本
# -*- coding: UTF-8 -*- #声明文件使用UTF-8编码
###############################################################################
# Copyright (C), 2018, TP-Link Technologies Co., Ltd.
#
# File Name: zhaomiaotong__test.py
# Author : zhaomiaotong
# History:
# 1. 2025-08-14, zhaomiaotong, create
###############################################################################
from pysat.sat_test import TestCase, CaseInfo #测试用例基类和测试用例元信息容器
from pysat.sat_result import ResultInfo #测试结果容器
from pysat import sat_conf #测试配置管理
from pysat import rpc3 #远程过程调用模块
import logging #Python标准日志模块
from datetime import datetime
import time
import os
import ctypes
from scapy.all import sniff, TCP, UDP, ICMP
import socket
import netifaces
import ctypes
import sys
import wmi
import threading
import psutil
logger = logging.getLogger(__name__) #创建模块级日志记录器,名称为当前模块名(__name__)
_gcfg = sat_conf.TestbedConfig() #创建测试床配置对象实例 _gcfg
#从测试床配置中获取指定名称(不区分大小写)的配置值
def get_config(name):
'''get the testbed config info, return the value'''
return _gcfg.get(name.lower())
# return _gcfg.get('testbed.cd_bvt_smbrouter.' + name.lower())
"""
获取网卡信息
"""
def get_network_info():
interfaces = netifaces.interfaces()
out_lines = []
for interface in interfaces:
addresses = netifaces.ifaddresses(interface)
ip_info = addresses.get(netifaces.AF_INET)
if ip_info:
for info in ip_info:
ip = info.get('addr')
netmask = info.get('netmask')
out_lines.append(f"IP Address:{ip}")
out_lines.append(f"Subnet Mask:{netmask}")
# print(f" IP Address: {ip}")
# print(f" Subnet Mask: {netmask}")
gateways = netifaces.gateways()
default_gateway = gateways.get('default', {}).get(netifaces.AF_INET)
if default_gateway and default_gateway[1] == interface:
out_lines.append(f"Gateway: {default_gateway[0]}")
# print(f" Gateway: {default_gateway[0]}")
# def get_dns_servers():
c = wmi.WMI()
# adapters = []
for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=True):
dns_servers = interface.DNSServerSearchOrder
description = interface.Description
if dns_servers:
out_lines.append(f"Subnet Mask:{description, dns_servers}")
# adapters.append((description, dns_servers))
# return adapters
# print("\n".join(out_lines))
return out_lines
#测试类 Test 继承自 TestCase
class Test(TestCase):
def __init__(self):
#创建类专属日志记录器(使用类名)
TestCase.__init__(self)
self.logger = logging.getLogger(self.__class__.__name__)
#创建 CaseInfo 实例并设置测试用例元数据:
self.case_info = CaseInfo()
self.case_info.name = 'test' #测试名称
self.case_info.id = 'zhaomiaotong' #测试ID
self.case_info.version = '202306271536' #版本号
self.case_info.author = 'zhaomiaotong@tp-link.com.hk' #作者邮箱
self.case_info.runtime = '80min' #预计执行时间
self.case_info.testbeds = self.get_testbed_list() #适用的测试环境列表
self.case_info.description = ''' ''' #测试描述(当前为空)
def add_task(self):
#调用 register_case 注册测试用例
self.register_case(self.zhaomiaotong__test, self.case_info)
def _start_sniffer(cls):
"""类方法:启动抓包任务"""
def packet_handler(packet):
if packet.haslayer('IP'):
if packet.haslayer('TCP'):
cls.packet_count['TCP'] += 1
elif packet.haslayer('UDP'):
cls.packet_count['UDP'] += 1
elif packet.haslayer('ICMP'):
cls.packet_count['ICMP'] += 1
def stop_sniffer():
cls.stop_sniffing = True
# 启动定时器
sniffing_time = 30 # 抓包5秒
timer = threading.Timer(sniffing_time, stop_sniffer)
timer.daemon = True
timer.start()
# 开始抓包
sniff(prn=packet_handler, filter="ip", store=0, stop_filter=lambda x: cls.stop_sniffing)
#定义执行测试函数FG999999__test
def zhaomiaotong__test(self):
try:
self.logger.info('[Pre-condition]: Process db data')
result = ResultInfo()
"""
获取网卡信息
"""
out_lines = get_network_info()
self.logger.info("网卡信息为:\n","\n".join(out_lines))
if out_lines:
result.add_result(
passfail=ResultInfo.PASS,
actual_result=("\n".join(out_lines)),
expected_result="预期IP、Mask、Gateway、DNS服务器均不为空",
test_comment='获取网卡的IP、Mask、Gateway、DNS服务器信息',
item_id='step1'
)
else:
result.add_result(
passfail=ResultInfo.FAIL,
actual_result=("\n".join(out_lines)),
expected_result="预期IP、Mask、Gateway、DNS服务器均不为空",
test_comment='获取网卡的IP、Mask、Gateway、DNS服务器信息',
item_id='step1'
)
"""
斐波那契数列求和
"""
n = 100
a, b = 1, 1
total = 2 # 前两项的和
# 计算从第3项到第n项
for i in range(3,n+1):
a, b = b, a + b # 更新斐波那契数列的值
total += b
start_time = time.perf_counter_ns()
end_time = time.perf_counter_ns()
# 计算耗时(纳秒转换为毫秒)
elapsed_time_ms = (end_time - start_time) / 1_000_000
self.logger.info(f"计算结束,斐波那契数列前100项和为:{total}\n耗时:{elapsed_time_ms}")
if total == 927372692193078999175:
result.add_result(
passfail=ResultInfo.PASS,
actual_result=(f"和为{total}\n耗时为{elapsed_time_ms}"),
expected_result="927372692193078999175",
test_comment='斐波那契数列前100项求和',
item_id='step2'
)
else:
result.add_result(
passfail=ResultInfo.FAIL,
actual_result=(f"和为{total}\n耗时为{elapsed_time_ms}"),
expected_result="927372692193078999175",
test_comment='斐波那契数列前100项求和',
item_id='step2'
)
"""
输出盘符
"""
# 获取当前系统中的盘符
drives = [partition.device for partition in psutil.disk_partitions()]
dri = 0
for drive in drives:
dri = dri + 1
self.logger.info(f"PC盘符有:{drives}")
if dri > 1:
result.add_result(
passfail=ResultInfo.PASS,
actual_result=(drives),
expected_result="盘符数量大于1",
test_comment='PC盘符',
item_id='step3'
)
else:
result.add_result(
passfail=ResultInfo.FAIL,
actual_result=(drives),
expected_result="盘符数量大于1",
test_comment='PC盘符',
item_id='step3'
)
"""
获取当前时间并格式化输出
"""
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
target_date = datetime(2024, 9, 17)
if datetime.now() > target_date:
result.add_result(
passfail=ResultInfo.PASS,
actual_result=(f"当前时间:{current_time}"),
expected_result="当前时间,在2024年中秋节之后则PASS",
test_comment='当前时间',
item_id='step4'
)
self.logger.info(f"当前时间为:{current_time}\n在2024年中秋节之后")
else:
result.add_result(
passfail=ResultInfo.FAIL,
actual_result=(f"当前时间:{current_time}"),
expected_result="当前时间,在2024年中秋节之后则PASS",
test_comment='当前时间',
item_id='step4'
)
self.logger.info(f"当前时间为:{current_time}\n在2024年中秋节之前")
"""
有线抓包
"""
# 重置抓包计数器
Test.packet_count = {'TCP': 0, 'UDP': 0, 'ICMP': 0}
Test.stop_sniffing= False
# 启动抓包线程
self._start_sniffer()
self.logger.info(f"抓包结束,统计结果:TCP={Test.packet_count['TCP']}, UDP={Test.packet_count['UDP']} ,ICMP={Test.packet_count['ICMP']}")
if Test.packet_count['TCP']!=0 and Test.packet_count['UDP']!=0 and Test.packet_count['ICMP']==0:
result.add_result(
passfail=ResultInfo.PASS,
actual_result=(f"TCP:{Test.packet_count['TCP']}\nUDP:{Test.packet_count['UDP']}\nICMP:{Test.packet_count['ICMP']}"),
expected_result="各种包数量不为0",
test_comment='有线抓包',
item_id='step5'
)
else:
result.add_result(
passfail=ResultInfo.FAIL,
actual_result=(f"TCP:{Test.packet_count['TCP']}\nUDP:{Test.packet_count['UDP']}\nICMP:{Test.packet_count['ICMP']}"),
expected_result="各种包数量不为0",
test_comment='有线抓包',
item_id='step5'
)
return result
except Exception as e:
result = ResultInfo()
result.add_result(
passfail=ResultInfo.FAIL,
test_comment=f'测试失败: {str(e)}'
)
self.break_test(f'测试失败: {str(e)}')
#测试清理
def clean_test(self):
try:
self.logger.info('[clean_test] start to clean test...')
except Exception as e:
self.logger.error('[clean_test] clean test failed: %s' % e)
raise e
这段python代码的亮点是什么?请从语法、功能实现函数、输出方式等方面阐述,要求详细且一语中的