from pysat.sat_test import TestCase, CaseInfo
from pysat.sat_result import ResultInfo
from pysat import sat_conf
from pysat import rpc3
import os # 添加os模块用于文件操作
import logging
from PyNetConfig import NetConfig as net
from PyPing import my_ping as ping
import PyScapy as capture
import time
logger = logging.getLogger(__name__)
_gcfg = sat_conf.TestbedConfig()
def get_config(name):
'''get the testbed config info, return the value'''
return _gcfg.get(name.lower())
class Test(TestCase):
def __init__(self):
TestCase.__init__(self)
self.logger = logging.getLogger(self.__class__.__name__)
self.case_info = CaseInfo()
self.case_info.name = 'cdent_class_test'
self.case_info.id = 'FG999992'
self.case_info.version = '202508150002'
self.case_info.author = 'suihaoyu@tp-link.com.hk'
self.case_info.runtime = '4min'
self.case_info.testbeds = self.get_testbed_list()
self.case_info.description = ''' '''
def add_task(self):
self.register_case(self.FG999992__cdent_class_test, self.case_info)
def FG999992__cdent_class_test(self):
try:
result = ResultInfo()
self.logger.info('前置操作:从数据库中读取预期的参数信息')
nic_name = get_config('pc_nic_name')
nic_ip = get_config('pc_nic_ip')
nic_mask = get_config('pc_nic_mask')
nic_gateway = get_config('pc_nic_gateway')
nic_dns1 = get_config('pc_nic_dns1')
nic_dns2 = get_config('pc_nic_dns2')
self.logger.info(f'nic_ip {nic_ip}')
# 实例化网卡
pc_nic = net(nic_name)
self.logger.step('步骤1: 读取当前pc网卡的IP/MASK/gateway/dns信息')
ip_list = pc_nic.get_ip_list()
ip = ip_list[0]['ip']
mask = ip_list[0]['mask']
flag = True
if ip != nic_ip:
flag = False
result.add_result(passfail=ResultInfo.FAIL, actual_result=ip,
expected_result=nic_ip,
test_comment='读取当前pc的网卡IP地址', item_id='步骤1.1')
if mask != nic_mask:
flag = False
result.add_result(passfail=ResultInfo.FAIL, actual_result=mask,
expected_result=nic_mask,
test_comment='读取当前pc的网卡mask', item_id='步骤1.2')
gateway = pc_nic.get_gateway_list()[0]
if gateway != nic_gateway:
flag = False
result.add_result(passfail=ResultInfo.FAIL, actual_result=gateway,
expected_result=nic_gateway,
test_comment='读取当前pc的网卡gateway', item_id='步骤1.3')
dns = pc_nic.get_dns_list()
dns1 = dns[0]
dns2 = dns[1]
if dns1 != nic_dns1:
flag = False
result.add_result(passfail=ResultInfo.FAIL, actual_result=dns1,
expected_result=nic_dns1,
test_comment='读取当前pc的网卡dns1', item_id='步骤1.4')
if dns2 != nic_dns2:
flag = False
result.add_result(passfail=ResultInfo.FAIL, actual_result=dns2,
expected_result=nic_dns2,
test_comment='读取当前pc的网卡dns2', item_id='步骤1.5')
if flag:
result.add_result(passfail=ResultInfo.PASS,
actual_result=f'ip:{ip}, mask:{mask}, gateway:{gateway}, dns1:{dns1}, dns2:{dns2}',
expected_result=f'ip:{nic_ip}, mask:{nic_mask}, gateway:{nic_gateway}, dns1:{nic_dns1}, dns2:{nic_dns2}',
test_comment='读取当前pc网卡的IP/MASK/gateway/dns信息', item_id='步骤1')
self.logger.step('步骤2: 存储网卡信息到文件')
# 创建result文件夹(如果不存在)
result_dir = "result"
if not os.path.exists(result_dir):
os.makedirs(result_dir)
self.logger.info(f"创建目录: {result_dir}")
# 创建带时间戳的文件名
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"nic_info_{timestamp}.txt"
file_path = os.path.join(result_dir, filename)
# 准备要写入的内容
content = f"""网卡信息报告
==============
测试时间: {time.ctime()}
网卡名称: {nic_name}
IP地址: {ip}
子网掩码: {mask}
默认网关: {gateway}
DNS服务器1: {dns1}
DNS服务器2: {dns2}
测试状态: {'通过' if flag else '失败'}"""
# 写入文件
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
self.logger.info(f"网卡信息已保存到: {file_path}")
# 将文件路径添加到测试结果
result.add_result(
passfail=ResultInfo.PASS if flag else ResultInfo.FAIL,
actual_result=f"信息已保存到 {file_path}",
test_comment='网卡信息存储',
item_id='步骤2'
)
self.logger.step('步骤3: 获取盘符')
# 获取所有盘符
drives = []
if os.name == 'nt': # Windows系统
import string
for letter in string.ascii_uppercase:
drive = f"{letter}:\\"
if os.path.exists(drive):
drives.append(drive)
else: # Linux/Mac系统
drives.append("/") # 根目录作为主要盘符
# 添加其他挂载点
for root, dirs, files in os.walk("/mnt"):
drives.append(root)
for root, dirs, files in os.walk("/media"):
drives.append(root)
# 记录到测试结果
if drives:
drive_str = ", ".join(drives[:3] + ['...'] if len(drives) > 3 else drives)
result.add_result(
passfail=ResultInfo.PASS,
actual_result=f"检测到盘符: {drive_str} (共{len(drives)}个)",
expected_result="至少一个有效盘符",
test_comment='获取PC盘符',
item_id='步骤3'
)
self.logger.info(f"检测到盘符: {drive_str}")
else:
result.add_result(
passfail=ResultInfo.FAIL,
actual_result="未检测到任何盘符",
expected_result="至少一个有效盘符",
test_comment='获取PC盘符',
item_id='步骤3'
)
self.logger.error("未检测到任何盘符")
self.logger.step('步骤4: 获取当前时间并判断是否早于2024年中秋')
# 获取当前时间并格式化为"YYYY-MM-DD hh:mm:ss"
current_time = time.strftime("%Y-%m-%d %H:%M:%S")
# 定义2024年中秋节时间点 (2024年9月17日 00:00:00)
mid_autumn_2024 = time.mktime(time.strptime("2024-09-17 00:00:00", "%Y-%m-%d %H:%M:%S"))
current_timestamp = time.time()
# 判断当前时间是否早于2024年中秋
is_early = current_timestamp < mid_autumn_2024
status = "早于" if is_early else "不早于"
# 记录测试结果
result.add_result(
passfail=ResultInfo.FAIL if is_early else ResultInfo.PASS,
actual_result=f"当前时间: {current_time} ({status}2024年中秋)",
expected_result="当前时间不早于2024-09-17",
test_comment='时间判断',
item_id='步骤4'
)
self.logger.info(f"当前时间: {current_time}, 状态: {status}2024年中秋")
self.logger.step('步骤5: 高精度计算斐波那契数列前100位总和')
# 使用perf_counter获取高精度时间戳
start_time = time.perf_counter()
# 高效计算斐波那契数列前100位
a, b = 1, 1
fib_sum = a + b # 初始总和
for _ in range(2, 100):
a, b = b, a + b # 同时更新两个变量
fib_sum += b
# 获取结束时间并计算耗时
end_time = time.perf_counter()
elapsed_ns = (end_time - start_time) * 1e9 # 转换为纳秒
# 记录测试结果
result.add_result(
passfail=ResultInfo.PASS,
actual_result=f"总和: {fib_sum} | 耗时: {elapsed_ns:.3f}ns",
expected_result="斐波那契数列前100位总和",
test_comment='高精度斐波那契计算',
item_id='步骤5'
)
self.logger.info(f"斐波那契总和: {fib_sum}")
self.logger.info(f"高精度耗时: {elapsed_ns:.3f}纳秒")
return result
except Exception as e:
result = ResultInfo()
result.add_result(passfail=ResultInfo.FAIL, test_comment='Test fail: %s' % e)
self.break_test('Test fail: %s' % 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 维持该代码不变 编写步骤6代码:有线网卡抓包30s 分别统计其中TCP、UDP、ICMP报文的数量,预期能抓到TCP和UDP报文,但抓不到ICMP报文
最新发布