Notebook半自动化测试(上传数据)
import os,sys,time,functools,datetime,subprocess,requests,wmi,computer_info,shutil,configparser,barcode,ctypes from pymysql import connect from barcode.writer import ImageWriter import matplotlib.pyplot as plt sys.path.append("..") kernel32 = ctypes.windll.kernel32 kernel32.SetConsoleMode(kernel32.GetStdHandle(-10), (0x4|0x80|0x20|0x2|0x10|0x1|0x00|0x100)) print('半自动功能测试工具©2024 By xcsg') print('技术博客https://www.cnblogs.com/xcsg') def database(): config.read(file_path,encoding='utf-8') port = int(config['mysql']['prot']) conn = connect(host='%s'%config['mysql']['ip'],port=port,user='root',password='',database='uhaw',charset="utf8mb4") cur = conn.cursor() return cur,conn def set_system_time_from_server(url): try: response = requests.head(url, timeout=5) server_time = response.headers.get('Date') # 解析服务器时间(格林威治时间) server_time = datetime.datetime.strptime(server_time, '%a, %d %b %Y %H:%M:%S %Z') # 增加8小时,转换为北京时间 server_time = server_time + datetime.timedelta(hours=8) server_time = server_time + datetime.timedelta(seconds=1) # 格式化为适合设置系统时间的字符串格式 system_time_str = server_time.strftime('%Y-%m-%d %H:%M:%S') # 分割日期和时间 date_str, time_str = system_time_str.split() # 设置日期 subprocess.call(['cmd', '/c', 'date', date_str]) # 设置时间 subprocess.call(['cmd', '/c', 'time', time_str]) print(u"本地系统时间已更新为北京时间") except Exception as e: print(u"出现错误:", str(e)) def run(q,m): T = subprocess.Popen("%s" %q) time.sleep(m) T.kill() def mstl(): os.system('powercfg -change -monitor-timeout-ac 180') os.system('powercfg -change -monitor-timeout-dc 180') os.system('powercfg -change -standby-timeout-ac 180') os.system('powercfg -change -standby-timeout-dc 180') print(u"正在查看系统激活状态") os.system('start ms-settings:activation') time.sleep(4) os.system('taskkill /f /im SystemSettings.exe') print(u"正在监测系统硬件") os.system('test\TEST_TOOL\SystemInfoTest.exe') os.system('devmgmt.msc') print(u"正在测试摄像头") os.system('test\VideoCap.exe') print(u"正在测试指纹识别") os.system('test\TEST_TOOL\Biometric.exe') print(u"正在测试wifi ") os.system('test\TEST_TOOL\WiFi.exe') print(u"正在测试蓝牙") os.system('test\TEST_TOOL\Bluetooth.exe') print(u"正在测试麦克风") os.system(r'test\aaa.exe') print(u"正在测试喇叭和声音") os.system('test\spt.exe') print(u"正在测试键盘") os.system('test\TEST_TOOL\Keyboard.exe') print(u"正在测试触控板") os.system('test\TEST_TOOL\Touchpad.exe') print(u"正在测试显示屏度明暗") os.system('test\TEST_TOOL\Brightness.exe') print(u"正在测试显示屏") os.system('test\LCD.EXE') os.system('start diskmgmt.msc') print(u"正在测试系统稳定性") os.system(r'test\ida64.exe') #展示条形码 def barcode_(barcode_value): bar = barcode.get(u'code128', barcode_value,writer=ImageWriter()) output = bar.render(writer_options={"format": "PNG"}) #渲染生成图像对象 plt.imshow(output) plt.axis('off') # 不显示坐标轴 plt.show() def clear_temp(): try: desktop_path = os.path.join(os.environ['USERPROFILE']) path = desktop_path+"\AppData\Local\Temp" subprocess.call(['cmd', '/c', 'rd', '/s', '/q', path]) os.mkdir(path) except: pass def out(): a = list(range(11)) for i in range(len(a)-1,-1,-1): time.sleep(1) print('******************************************************剩余%d秒退出******************************************************'%i) @ApplicationInstance def main(): # 替换下面的url变量为你要获取时间的网站 exit_code = os.system('ping www.baidu.com') if exit_code: print("网络测试失败,请连接网络...") res = input(" 数字1进入离线测试,数字2进入稳定性测试,按任意键退出:") if res =='1': mstl() #关闭wifi os.system('netsh wlan disconnect') #重启测试 os.system('reboot.bat') elif res =='2': print(u"正在测试系统稳定性") os.system(r'test\ida64.exe') os.system('reboot.bat') else: out() os.remove(file_path) clear_temp() else: print("网络测试成功") set_system_time_from_server(url) start_t = time.time() #mac地址 macadd = computer_info.net_mac() snmacadd =macadd[-5:].replace(':','') macadd = macadd.replace(':','-') c = wmi.WMI() processor = c.Win32_Processor()[0] #cpu型号 cpu= processor.Name.strip() #内存 m = [] for Memory in c.Win32_PhysicalMemory(): m.append(round(int(Memory.Capacity)/1048576/1024)) mz = '+'.join(map(str,m)) snm = sum(m) m = str(sum(m))+"(%s)"%mz #硬盘 disk = [] for i in c.Win32_DiskDrive(): d = str(round(int(i.Size) / (1024 * 1024 * 1024))) d_len= len(str(d)) if d_len ==3: if d[0] == '2': d1 ='256' elif d[0]=='1': d1='128' elif d[0]=='4': d1='512' elif d[0]=='9': d1='1024' elif d_len ==4: if d[0]=='1': d1='2048' elif d[0]=='3': d1='4096' elif d[0]=='7': d1='8196' elif d_len ==2: print("===================================================请拔掉u盘,重新测试===================================================") out() clear_temp() os._exit(-1) disk.append(d1) d1 = '+'.join(map(str,disk)) d_num = [int(x) for x in disk] d_num = sum(d_num) #操作系统 for sys in c.Win32_OperatingSystem(): s =sys.Caption y =sys.OSArchitecture #sn obj = c.Win32_OperatingSystem()[0] sn = obj.SerialNumber #型号 obj = c.Win32_BaseBoard()[0] zh = obj.Manufacturer +'-'+ obj.Product # # # 设置条形码的值 sndata = snmacadd +str(time.strftime("%y%m",time.localtime())) + str(snm) + str(d) try: cur,conn = database() cur.execute("SELECT * FROM testdata WHERE sn = '%s'"%sndata) mdata = cur.fetchall() cur.close() conn.close() if len(mdata) == 0: mstl() #显卡 v = [] for xk in c.Win32_VideoController(): v.append(xk.name) v = ', '.join(map(str,v)) t = divmod(time.time()-start_t,60) run_time = '%s分%s秒'%(round(t[0]),round(t[1])) #测试时长 d_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) #入库时间 data = time.strftime("%Y%m",time.localtime()) cur,conn = database() cur.execute("insert into testdata values(0,'"+sndata+"','"+d_time+"','"+macadd+"','"+cpu+"','"+m+"','"+str(d_num)+"','"+v+"','"+s+"','"+'1'+"','','"+zh+"','','','"+run_time+"')") conn.commit() config.read(file_path,encoding='utf-8') with open(r'\\%s\DATA\%s.txt'%(config['sn_ip']['ip'],data), 'a') as f: f.write('%s\n' %sndata) barcode_(sndata) #关闭wifi os.system('netsh wlan disconnect') # #重启测试 os.system('reboot.bat') else: print('=================================================此产品已测试ok,请勿重复测试=================================================') barcode_(sndata) os.remove(file_path) clear_temp() except OSError or FileNotFoundError: print('================================================链接服务器失败,数据上传失败,请检查网络================================================') clear_temp() out() os._exit(-1) if __name__ == '__main__': desktop_path = os.path.join(os.environ['USERPROFILE'], 'Desktop') file_path = desktop_path+'\config.ini' r_path = os.path.join(os.environ['USERPROFILE'])+"\AppData\Local\Temp" a = 'DejaVuSansMono.ttf' traget = 'C:\Windows\Fonts' shutil.copy(a,os.path.join(traget, a)) b = 'readini.bat' shutil.copy(b,os.path.join(r_path, b)) # # 获取ini文件对象 config = configparser.ConfigParser() if os.path.exists(file_path): pass else: f = open(file_path,'w') f.close() config.add_section('sn_ip') config.set('sn_ip','ip','192.168.2.222') config.add_section('mysql') config.set('mysql','ip','192.168.2.223') config.set('mysql','prot','3306') config.add_section('aida64') config.set('aida64','time','120') config.add_section('reboot') config.set('reboot','num','100') config.write(open(file_path,'w')) url = 'http://www.qq.com/' # # 获取ini文件对象 main() sys.exit()