computer半自动化测试(upload)

import os,sys,time,functools,datetime,subprocess,requests,wmi,shutil,configparser,ctypes,json,pyttsx3,win32gui,win32con,threading,psutil
from pymysql import connect

global test_data
test_data = {}
def ApplicationInstance(func):
  @functools.wraps(func)
  def fun(*args,**kwargs):
    import socket
    try:
      global s
      s = socket.socket()
      host = socket.gethostname()
      s.bind((host, 60123))
    except:
      return show_message_box('不能重复打开已存在的程序...',"提示")
    return func(*args,**kwargs)
  return fun

# 弹出消息框的函数
def show_message_box(message, title):
    win32gui.MessageBox(0, message, title, win32con.MB_OK)
   
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='',charset="utf8mb4",connect_timeout=60)
  conn.autocommit(True)
  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)
    os.system('taskkill /f /im TM5.exe')
def pyttsx(au):
    engine.say('%s'%au)
    engine.runAndWait()
def mstl():  
  print(u"正在查看系统激活状态")
  os.system('start ms-settings:activation')
  time.sleep(5)
  os.system('taskkill /f /im SystemSettings.exe')
  print(u"正在监测系统硬件")
  SystemInfoTest = os.system('test\TEST_TOOL\SystemInfoTest.exe')
  if SystemInfoTest == 0:
    pyttsx('硬件检测通过')
  elif SystemInfoTest == 255:
    pyttsx('硬件检测失败')
  test_data['sysinfo'] = SystemInfoTest
  os.system('devmgmt.msc')
  print(u"正在测试摄像头")
  VideoCap = os.system('test\VideoCap.exe')
  if VideoCap == 0:
    pyttsx('摄像头检测通过')
  else:
    pass
  test_data['VideoCap'] = VideoCap
  print(u"正在测试指纹识别")
  Biometric =os.system('test\TEST_TOOL\Biometric.exe')
  if Biometric== 0:
    pyttsx('指纹检测通过')
  elif Biometric == 255:
    pyttsx('指纹检测失败')
  test_data['Biometric'] = Biometric
  print(u"正在测试wifi ")
  WiFi = os.system('test\TEST_TOOL\WiFi.exe')
  if WiFi== 0:
    pyttsx('wifi检测通过')
  elif WiFi == 255:
    pyttsx('wifi检测失败')
  test_data['wifi'] = WiFi
  print(u"正在测试蓝牙")
  Bluetooth = os.system('test\TEST_TOOL\Bluetooth.exe')
  if Bluetooth == 0:
    pyttsx('蓝牙检测通过')
  elif Bluetooth  == 255:
    pyttsx('蓝牙检测失败')
  test_data['Bluetooth'] = Bluetooth
  os.system(r'test\aaa.exe')
  print(u"正在测试喇叭和声音")
  os.system('test\spt.exe')
  print(u"正在测试键盘")
  Keyboard = os.system('test\TEST_TOOL\Keyboard.exe')
  if Keyboard== 0:
    pyttsx('键盘检测通过')
  elif Keyboard == 255:
    pyttsx('键盘检测失败')
  test_data['Keyboard'] = Keyboard
  print(u"正在测试触控板")
  Touchpad = os.system('test\TEST_TOOL\Touchpad.exe')
  if Touchpad== 0:
    pyttsx('触控板检测通过')
  elif Touchpad == 255:
    pyttsx('触控板检测失败')
  test_data['Touchpad'] = Touchpad
  print(u"正在测试显示屏明暗度")
  Brightness = os.system('test\TEST_TOOL\Brightness.exe')
  if Brightness== 0:
    pyttsx('明暗度检测通过')
  elif Brightness == 255:
    pyttsx('明暗度检测失败')
  test_data['Brightness'] = Brightness
  print(u"正在测试显示屏")
  os.system('test\LCD.EXE')  
  os.system('start diskmgmt.msc')  
 
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():
    exit_code = os.system('ping www.baidu.com')
    if exit_code:
      print("网络测试失败,请连接网络...")
      print("======================================================================================================")
      print('1,笔记本离线测试')
      print('2,台式机离线测试')
      print('3,稳定性测试')
      print('4,重启测试')
      print('5,内存测试')
      print('6,甜甜圈显卡测试')
      print('7,任意键退出')
      print("======================================================================================================")
      res = input("请输入:")
      if res =='1':
        mstl()
        print(u"正在测试内存")
        run('test\TM5.exe',1200)
        print(u"正在测试系统稳定性")
        os.system(r'test\ida64.exe')
        os.system('reboot.bat')
      elif res =='2':
        os.system('devmgmt.msc')
        os.system('start diskmgmt.msc')  
        subprocess.Popen(r'test\dd.exe')
        subprocess.Popen(r'test\FurMark.exe')
        print(u"正在测试内存")
        run(r'test\TM5.exe',1200)
        print(u"正在测试系统稳定性")
        os.system(r'test\ida64.exe')
        os.system('reboot.bat')
      elif res =='3':
        subprocess.Popen('test\cpu_Monitor.exe')
        os.system(r'test\ida64.exe')
        clear_temp()
      elif res =='4':
        os.system('reboot.bat')
      elif res =='5':
        os.system(r'test\TM5.exe')
        clear_temp()
      elif res =='6':
        os.system(r'test\FurMark.exe')
        clear_temp()
      else:
        out()
       
    else:
      print("网络测试成功")
      set_system_time_from_server(url)
      c = wmi.WMI()
      processor = c.Win32_Processor()[0]
        #cpu型号
      cpu=  processor.Name.strip()
      # # 获取网络适配器信息
      for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
        # 打印每个启用的网络适配器的MAC地址
        macadd = interface.MACAddress
      snmacadd =macadd[-5:].replace(':','') + macadd[0:5].replace(':','')
      macadd = macadd.replace(':','-')
     
      #内存
      m = []
      m_info = []
      for Memory in c.Win32_PhysicalMemory():
        m.append(round(int(Memory.Capacity)/1048576/1024))
        m_info.append({'size':round(int(Memory.Capacity)/1048576/1024),'Manufacturer':Memory.Manufacturer,'SerialNumber':Memory.SerialNumber,'Speed':Memory.Speed})
      mz = '+'.join(map(str,m))
      snm = sum(m)
      m = str(sum(m))+"(%s)"%mz
     
      #硬盘
      disk = []
      d_info = []
      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:
          show_message_box('请拔掉u盘,重新测试',"提示")
          clear_temp()
          os._exit(-1)
        disk.append(d1)
        d_info.append({'size':d1,'Manufacturer':i.Manufacturer,'SerialNumber':i.SerialNumber,'label':i.Model})
      d1 = '+'.join(map(str,disk))
      d_num = [int(x) for x in disk]
      d_num = sum(d_num)
      #显卡
      v = []
      for xk in  c.Win32_VideoController():
        v.append(xk.name)
      v = ', '.join(map(str,v))
      #操作系统
      for sys in c.Win32_OperatingSystem():
        s =sys.Caption
        y =sys.OSArchitecture
      #sn
      obj = c.Win32_OperatingSystem()[0]
      systemboard_sn = obj.SerialNumber

      #型号
      obj = c.Win32_BaseBoard()[0]
      zh = obj.Manufacturer +'-'+ obj.Product
      # # # 设置条形码的值
      sndata = snmacadd + str(snm) + str(d)
      if len(sndata) == 13:
        sndata =sndata
      elif len(sndata) > 13:
        sndata = sndata[:13]
         
      try:
        cur,conn = database()
        cur.execute("SELECT * FROM testdata WHERE sn = '%s'"%sndata)
        mdata = cur.fetchall()
        cur.close()
        conn.close()
        if len(mdata) == 0:
          config.read(file_path,encoding='utf-8')
          battery = psutil.sensors_battery()
          if battery is None:
              if config['is_test']['state'] == '0':
                os.system('devmgmt.msc')
                os.system('start diskmgmt.msc')  
                subprocess.Popen(r'test\dd.exe')
                subprocess.Popen(r'test\FurMark.exe')
                start_t = time.time()
                print(u"正在测试内存")
                run(r'test\TM5.exe',1200)
                print(u"正在测试系统稳定性")
                os.system(r'test\ida64.exe')
                config.set('is_test','state','1')
                config.write(open(file_path,'w'))
                t = divmod(time.time()-start_t,60)
                run_time = '%sm%ss'%(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()
                try:
                  cur.execute("insert into testdata values(0,'"+sndata+"','"+d_time+"','"+macadd+"','"+cpu+"','"+m+"','"+str(d_num)+"','"+v+"','"+s+"','"+'1'+"','','"+zh+"','','','"+run_time+"','"+systemboard_sn+"','"+'2'+"','"+json.dumps(m_info)+"','"+json.dumps(d_info)+"')")
                  conn.commit()
                except Exception as e:
                    # 如果发生错误,回滚事务
                    conn.rollback()
                    raise e
                finally:
                    cur.close()
                    conn.close()
 
                 
          else:
            subprocess.Popen('test\cpu_Monitor.exe')
            if config['is_test']['state'] == '0':
              mstl()
              config.set('is_test','state','1')
              config.write(open(file_path,'w'))
              start_t = time.time()
              print(u"正在测试内存")
              run('test/TM5.exe',1200)
              print(u"正在测试系统稳定性")
              os.system(r'test\ida64.exe')
              t = divmod(time.time()-start_t,60)
              run_time = '%sm%ss'%(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()
              try:
                cur.execute("insert into testdata values(0,'"+sndata+"','"+d_time+"','"+macadd+"','"+cpu+"','"+m+"','"+str(d_num)+"','"+v+"','"+s+"','"+'1'+"','','"+zh+"','','','"+run_time+"','"+systemboard_sn+"','"+json.dumps(test_data)+"','"+json.dumps(m_info)+"','"+json.dumps(d_info)+"')")
                conn.commit()
              except Exception as e:
                  # 如果发生错误,回滚事务
                  conn.rollback()
                  raise e
              finally:
                  cur.close()
                  conn.close()
            else:
              start_t = time.time()
              print(u"正在测试内存")
              run('test/TM5.exe',1200)
              print(u"正在测试系统稳定性")
              os.system(r'test\ida64.exe')
              t = divmod(time.time()-start_t,60)
              run_time = '%sm%ss'%(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()
              try:
                cur.execute("insert into testdata values(0,'"+sndata+"','"+d_time+"','"+macadd+"','"+cpu+"','"+m+"','"+str(d_num)+"','"+v+"','"+s+"','"+'1'+"','','"+zh+"','','','"+run_time+"','"+systemboard_sn+"','1','"+json.dumps(m_info)+"','"+json.dumps(d_info)+"')")
                conn.commit()
              except Exception as e:
                  conn.rollback()
                  raise e
              finally:
                  cur.close()
                  conn.close()
          lock = threading.Lock()  
          with lock:
              with open(r'\\%s\DATA\%s.txt'%(config['sn_ip']['ip'],data), 'a') as f:
                  f.write('%s\n' %sndata)
                 
          os.system('reboot.bat')
        else:
          show_message_box('此产品已测试ok,请勿重复测试',"提示")
          subprocess.Popen('wininfo.exe')
          os.remove(file_path)
          clear_temp()
      except:
        show_message_box('链接服务器失败,数据上传失败,请检查网络或服务器',"提示")
        clear_temp()
        os._exit(-1)
         


if __name__ == '__main__':
    print('半自动功能测试工具©2024 By xcsg')
    print('技术博客https://www.cnblogs.com/xcsg')
   
    kernel32 = ctypes.windll.kernel32
    kernel32.SetConsoleMode(kernel32.GetStdHandle(-10), (0x4|0x80|0x20|0x2|0x10|0x1|0x00|0x100))
       
    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"
    e_path = os.path.join(os.environ['USERPROFILE'])+"\AppData\Local"
    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')

    b = 'readini.bat'
    shutil.copy(b,os.path.join(r_path, b))
    c = 'Countdown.wav'
    shutil.copy(c,os.path.join(r_path, c))
    e = 'wininfo.exe'
    shutil.copy(e,os.path.join(e_path, e))
   
 
    engine = pyttsx3.init()
    # 设置音量(0到1之间)
    engine.setProperty('volume', 1)
    # 设置语速
    rate = engine.getProperty('rate')
    engine.setProperty('rate', rate-50)
    voices = engine.getProperty('voices')
    newVoice = voices[0]
    engine.setProperty('voice', newVoice.id)
    # # 获取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.223')
        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','70')
        config.add_section('reboot')
        config.set('reboot','num','50')
        config.add_section('is_test')
        config.set('is_test','state','0')
        config.write(open(file_path,'w'))
    url = 'http://www.qq.com/'  
    main()
    sys.exit()
posted @ 2023-08-31 18:53  Xcsg  Views(35)  Comments(0Edit  收藏  举报