How to use to_be_enabled method in Playwright Python

Best Python code snippet using playwright-python

SDO_Gui.py

Source:SDO_Gui.py Github

copy

Full Screen

1import tkinter as tk2from tkinter import filedialog3from tkinter import messagebox4import os5import sys6import json7sys.path.append("..")8import Extracteur as Extracteur9import Tools.Find_all_PE10import Trainer as Trainer11import SDO as SDO12from watchdog.observers import Observer13import time14from watchdog.events import PatternMatchingEventHandler15import CaracStats as CaracStats16from tkinter import ttk17import admin18def clean(observers):19 """20 Libère les observeur de watchdog21 """22 for o in observers:23 o.unschedule_all()24 # stop observer if interrupted25 o.stop()26 for o in observers:27 # Wait until the thread terminates before exit28 o.join()29def getObservers(paths, event_handler):30 """31 Prépare les observeurs de watchdog (récursif sur la liste des chemins données en premier paramètre)32 Les observeurs appelleront les fonctions dans le event_handler donné33 """34 # take in list of paths.35 # Empty list of observers.36 observers = []37 38 # iterate through paths and attach observers39 for line in paths:40 # convert line into string and strip newline character41 targetPath = str(line).rstrip()42 # Schedules watching of a given path43 if targetPath[0]=="%":44 #targetPath=targetPath[1:len(targetPath)-1]45 #Isolate the environment variable46 targetPath=targetPath.replace("%","")47 #Trying to find something like "APPDATA\Something"48 if targetPath.find("\\") != -1:49 #Isolation of the environment variable50 targetPath=targetPath[0:len(targetPath)]51 pourcent=targetPath.find("\\")52 var_debut=targetPath[0:pourcent]53 #Get the rest of the path back54 var_suite=targetPath[pourcent:len(targetPath)]55 #Get the full path of the environment variable56 var_env=os.getenv(var_debut)57 #slash="\\"58 #Adding \ if we have something after the environment variable59 #var_env=str(var_env)+slash60 #Concatenation of the result of our environment variable and the rest of the path61 var_path=str(var_env+var_suite)62 #Get the real path and not something like "User\Local\..\Downloads"63 real_path=os.path.realpath(var_path)64 #Running our observer65 # Create Observer to watch directories66 observer = Observer()67 observer.schedule(event_handler,real_path, recursive=True)68 else:69 env=os.getenv(targetPath)70 # Create Observer to watch directories71 observer = Observer()72 observer.schedule(event_handler,env, recursive=True)73 else:74 # Create Observer to watch directories75 observer = Observer()76 observer.schedule(event_handler, targetPath, recursive=True)77 # Add observable to list of observers78 observers.append(observer)79 # start observers80 for observer in observers:81 observer.start()82 return observers83def execute_detect_one_file(model_name, file_to_extract):84 """85 Renvoie la probabilité que le fichier donné soit un fichier sain selon le modèle entraîné donné86 """87 caracs = Extracteur.extract_one(file_to_extract)88 89 if caracs == None:90 return -191 probas = SDO.classify_proba(model_name, [caracs], [file_to_extract])92 proba_sain = probas[0][0]93 return proba_sain94class VirusWindow(object):95 root = None96 alreadyOpen = False97 def __init__(self, path_prob_virus,proba_sain):98 99 100 tki = tk101 self.top = tki.Toplevel(VirusWindow.root)102 if VirusWindow.alreadyOpen == False:103 VirusWindow.alreadyOpen = True104 else:105 self.quit_window(True)106 107 abs_path = os.path.dirname(os.path.abspath(__file__))108 img_path = os.path.join(abs_path,"images\\computer-virus.gif")109 self.background_image = tk.PhotoImage(file=img_path)110 w = self.background_image.width()111 h = self.background_image.height()112 # size the window so the image will fill it113 self.top.geometry("%dx%d" % (w, h))114 self.panel1 = tk.Label(self.top, image=self.background_image)115 self.panel1.place(x=0,y=0,relheight=1,relwidth=1)116 #self.panel1.pack()117 frm = tki.Frame(self.panel1, borderwidth=4, relief='ridge')118 frm.pack(side=tk.BOTTOM, expand=True)119 msg = "/!\ Le fichier "+str(os.path.basename(path_prob_virus))+ " est un malware ("+str(round(1-proba_sain,3)*100)+" % de confiance). Voulez vous le supprimer?"120 label = tki.Label(frm, text=msg)121 label.pack(padx=4, pady=4)122 b_submit = tki.Button(frm, text='Oui')123 b_submit['command'] = lambda: self.delete_approved(path_prob_virus)124 b_submit.pack(side=tk.BOTTOM)125 b_cancel = tki.Button(frm, text='Cancel')126 b_cancel['command'] = lambda: self.quit_window(False)127 b_cancel.pack(padx=4, pady=4,side=tk.BOTTOM)128 def delete_approved(self, path_prob_virus):129 try:130 os.remove(path_prob_virus)131 132 except:133 pass134 self.quit_window(False)135 def quit_window(self,already_opened):136 VirusWindow.alreadyOpen = already_opened137 self.top.destroy()138 139class SDO_Handler(PatternMatchingEventHandler):140 """141 Classe définisant les fonctions à appeler pour les observeurs watchdog142 """143 def __init__(self,master, model,**kwargs):144 super().__init__(**kwargs)145 self.model = model146 self.master = master147 def apply_removal(self,path_to_remove,proba_sain):148 """149 Fonction appelé une fois la probabilité que le chemin donné soit calculée.150 Demandera confirmation pour la suppression du fichier s'il est potentiellement malveillant151 """152 if proba_sain == -1:153 return154 if 1-proba_sain >= 0.5:155 try:156 if VirusWindow.alreadyOpen == False:157 reiconify = False158 if self.master.state() == "iconic":159 reiconify = True160 self.master.deiconify()161 #rep=messagebox.askquestion("Malware", " /!\ Le fichier "+str(os.path.basename(path_to_remove))+ " est un malware ("+str(round(1-proba_sain,3)*100)+" % de confiance). Voulez vous le supprimer?")162 VirusWindow(path_to_remove,proba_sain)163 if reiconify == True:164 self.master.iconify()165 except Exception as e:166 pass167 def on_modified(self, event):168 """169 Fonction appelée par les observeurs de watchdog lorsqu'un fichier est modifié170 """171 print("Modifier "+event.src_path)172 proba_sain = execute_detect_one_file(self.model, event.src_path)173 self.apply_removal(event.src_path,proba_sain)174 175 176 def on_created(self, event):177 """178 Fonction appelée par les observeurs de watchdog lorsqu'un fichier est crée179 """180 print("Créer "+event.src_path)181 proba_sain = execute_detect_one_file(self.model, event.src_path)182 self.apply_removal(event.src_path,proba_sain)183 def on_moved(self, event):184 """185 Fonction appelée par les observeurs de watchdog lorsqu'un fichier est déplacé186 """187 print("Déplacer "+event.dest_path)188 proba_sain = execute_detect_one_file(self.model, event.dest_path)189 self.apply_removal(event.dest_path,proba_sain)190 def on_deleted(self, event):191 """192 Fonction appelée par les observeurs de watchdog lorsqu'un fichier est supprimé193 """194 pass195class SDO_GUI:196 """197 Classe définissant la fenêtre principale de l'interface graphique198 """199 def __init__(self, master, model_name):200 """201 Initialisation de tous composants graphique de la fenêtre principale202 Les Frames sont nombreuses et le code très similaire pour chaque section203 """204 self.master = master205 self.master.protocol("WM_DELETE_WINDOW", self.quit)206 self.wantToQuit = False207 self.watcher_started = False208 master.title("Projet SDO")209 self.notebook = ttk.Notebook(master)210 self.notebook_p1 = ttk.Frame(self.notebook)211 self.notebook_p2 = ttk.Frame(self.notebook)212 self.label = ttk.Label(master, text="Projet SDO")213 self.label.pack()214 separator = ttk.Separator(master)215 separator.pack(fill=tk.X, padx=5, pady=9)216 #Extraction217 panel_extraction = ttk.Frame(self.notebook_p1,relief=tk.SUNKEN)218 lbl_extraction = ttk.Label(panel_extraction, text="Extraire des caracteristiques :")219 lbl_extraction.pack(side=tk.LEFT)220 btn_import_one = ttk.Button(panel_extraction, text="D'un fichier", command=self.add_one_file)221 btn_import_list = ttk.Button(panel_extraction, text="D'une liste fichier Json ", command=self.add_json_list)222 btn_import_whole_dir = ttk.Button(panel_extraction, text="D'un dossier", command=self.add_whole_dir)223 btn_import_one.pack(side=tk.LEFT,padx=5,pady=9)224 btn_import_list.pack(side=tk.LEFT,padx=5,pady=9)225 btn_import_whole_dir.pack(side=tk.LEFT,padx=5,pady=9)226 panel_extraction.pack(fill=tk.X, padx=5, pady=9)227 separator = ttk.Separator(self.notebook_p1)228 separator.pack(fill=tk.X, padx=5, pady=9)229 #Entrainement230 panel_entrainement = ttk.Frame(self.notebook_p1,relief=tk.SUNKEN)231 lbl_entrainement = ttk.Label(panel_entrainement, text="Entrainement modèle :")232 lbl_entrainement.pack(side=tk.LEFT)233 panel_path_clean = ttk.Frame(panel_entrainement)234 lbl_path_clean = ttk.Label(panel_path_clean, text="Caractéristiques de fichiers sains:")235 lbl_path_clean.pack(side=tk.LEFT)236 self.ent_path_clean = tk.Entry(panel_path_clean)237 self.ent_path_clean.pack(side=tk.LEFT)238 btn_path_clean = ttk.Button(panel_path_clean, text="...", command=self.renseigneFichierClean)239 btn_path_clean.pack(side=tk.LEFT)240 panel_path_clean.pack(fill=tk.X, padx=5, pady=9)241 panel_path_malware= ttk.Frame(panel_entrainement)242 lbl_path_malware = ttk.Label(panel_path_malware, text="Caractéristiques de malwares:")243 lbl_path_malware.pack(side=tk.LEFT)244 self.ent_path_malware = tk.Entry(panel_path_malware)245 self.ent_path_malware.pack(side=tk.LEFT)246 btn_path_malware = ttk.Button(panel_path_malware, text="...", command=self.renseigneFichierMalware)247 btn_path_malware.pack(side=tk.LEFT)248 panel_path_malware.pack(fill=tk.X, padx=5, pady=9)249 panel_ratio_clean= ttk.Frame(panel_entrainement)250 lbl_ratio_clean = ttk.Label(panel_ratio_clean, text="Ratio entrainement / test sains :")251 lbl_ratio_clean.pack(side=tk.LEFT)252 self.ent_ratio_clean = tk.Entry(panel_ratio_clean, width=5)253 self.ent_ratio_clean.insert(tk.END, '0.8')254 self.ent_ratio_clean.pack(side=tk.LEFT)255 panel_ratio_clean.pack(fill=tk.X)256 panel_ratio_malware = ttk.Frame(panel_entrainement)257 lbl_ratio_malware = ttk.Label(panel_ratio_malware, text="Ratio entrainement / test malware :")258 lbl_ratio_malware.pack(side=tk.LEFT)259 self.ent_ratio_malware = tk.Entry(panel_ratio_malware, width=5)260 self.ent_ratio_malware.insert(tk.END, '0.8')261 self.ent_ratio_malware.pack(side=tk.LEFT)262 panel_ratio_malware.pack(fill=tk.X)263 panel_model = ttk.Frame(panel_entrainement)264 lbl_model = ttk.Label(panel_model, text="Nom du futur modèle:")265 lbl_model.pack(side=tk.LEFT)266 self.ent_model = tk.Entry(panel_model)267 self.ent_model.insert(tk.END, 'SDO_model')268 self.ent_model.pack(side=tk.LEFT)269 panel_model.pack(fill=tk.X)270 panel_model_old = ttk.Frame(panel_entrainement)271 lbl_model_old = ttk.Label(panel_model_old, text="(optionel) partir d'un modèle existant:")272 lbl_model_old.pack(side=tk.LEFT)273 self.ent_model_old = tk.Entry(panel_model_old)274 self.ent_model_old.pack(side=tk.LEFT)275 btn_path_model_old = ttk.Button(panel_model_old, text="...", command=self.renseigneFichierModelOld)276 btn_path_model_old.pack(side=tk.LEFT)277 panel_model_old.pack(fill=tk.X)278 self.check_basic = tk.IntVar()279 self.check_te = tk.IntVar()280 self.check_fn = tk.IntVar()281 chk_simple = ttk.Checkbutton(panel_entrainement, text="Rapide", variable=self.check_basic)282 chk_te = ttk.Checkbutton(panel_entrainement, text="Optimiser le TE", variable=self.check_te)283 chk_fn = ttk.Checkbutton(panel_entrainement, text="Optimiser les FN", variable=self.check_fn)284 btn_training = ttk.Button(panel_entrainement, text="Entraînement!", command=self.training)285 btn_training.pack(side=tk.RIGHT,padx=5,pady=9)286 chk_fn.pack(side=tk.RIGHT,padx=5,pady=9)287 chk_te.pack(side=tk.RIGHT,padx=5,pady=9)288 chk_simple.pack(side=tk.RIGHT,padx=5,pady=9)289 panel_entrainement.pack(fill=tk.X, padx=5, pady=9)290 291 #Detection292 panel_detection = ttk.Frame(self.notebook_p2)293 294 panel_sel_modele = ttk.Frame(panel_detection)295 lbl_model_ent = ttk.Label(panel_sel_modele, text="Sélection du modèle :")296 lbl_model_ent.pack(side=tk.LEFT)297 self.ent_path_model = tk.Entry(panel_sel_modele)298 self.ent_path_model.pack(side=tk.LEFT)299 if model_name != None:300 self.ent_path_model.insert(0,model_name)301 btn_path_model = ttk.Button(panel_sel_modele, text="...", command=self.renseigneFichierModel)302 btn_path_model.pack(side=tk.LEFT)303 panel_sel_modele.pack(fill=tk.X, padx=5, pady=9)304 lbl_detection = ttk.Label(panel_detection, text="Appliquer le modèle :")305 lbl_detection.pack(side=tk.LEFT)306 btn_detect_one = ttk.Button(panel_detection, text="Sur un fichier", command=self.detect_one_file)307 btn_detect_list = ttk.Button(panel_detection, text="Sur un fichier de caracs", command=self.detect_list_file)308 btn_detect_one.pack(side=tk.LEFT,padx=5)309 btn_detect_list.pack(side=tk.LEFT,padx=5)310 panel_detection.pack(fill=tk.X, padx=5, pady=9)311 # Watcher312 panel_start_stop = ttk.Frame(self.notebook_p2)313 lbl_watcher = ttk.Label(panel_start_stop, text="Démarrer le watcher :")314 lbl_watcher.pack(side=tk.LEFT)315 self.btn_start_stop = ttk.Button(panel_start_stop, text="Start", command=self.start_stop_watcher)316 self.btn_start_stop.pack(side=tk.LEFT,padx=5)317 panel_start_stop.pack(fill=tk.X, padx=5, pady=9)318 import win32com.client as win32com_client319 scheduler = win32com_client.Dispatch("Schedule.Service")320 scheduler.Connect("" or None, "" or None, "" or None, "" or None)321 rootFolder = scheduler.GetFolder("\\")322 try:323 task = rootFolder.GetTask("SDO_GUI_TASK")324 except:325 task = None326 if task is None:327 self.btn_persist = ttk.Button(panel_start_stop, text="Start on boot", command=self.start_on_boot)328 else:329 if task.Enabled == False:330 self.btn_persist = ttk.Button(panel_start_stop, text="Start on boot", command=self.start_on_boot)331 else:332 self.btn_persist = ttk.Button(panel_start_stop, text="Remove start on boot", command=self.start_on_boot)333 self.btn_persist.pack(side=tk.LEFT,padx=5)334 self.notebook.add(self.notebook_p1,text="Entrainement")335 self.notebook.add(self.notebook_p2,text="Utilisation")336 self.notebook.pack(padx=5,pady=5)337 separator = ttk.Separator(master)338 separator.pack(fill=tk.X, padx=5, pady=9,side=tk.BOTTOM)339 self.close_button = ttk.Button(master, text="Fermer", command=self.quit)340 self.close_button.pack()341 if model_name != None:342 self.start_stop_watcher()343 def start_on_boot(self):344 import win32com.client as win32com_client345 scheduler = win32com_client.Dispatch("Schedule.Service")346 scheduler.Connect("" or None, "" or None, "" or None, "" or None)347 rootFolder = scheduler.GetFolder("\\")348 try:349 task = rootFolder.GetTask("SDO_GUI_TASK")350 except:351 task = None352 to_be_enabled = True353 if task is not None:354 if task.Enabled == True:355 to_be_enabled = False356 if to_be_enabled:357 model = self.ent_path_model.get()358 if model == "":359 messagebox.showerror("Erreur", "Un modèle doit être renseigné.")360 return361 computer_name = "" #leave all blank for current computer, current user362 computer_username = ""363 computer_userdomain = ""364 computer_password = ""365 abs_path = os.path.dirname(os.path.abspath(__file__))366 action_path = abs_path+"\\SDO_Gui.exe" #executable path (could be python.exe)367 action_workdir = abs_path #working directory for action executable368 action_id = "SDO_GUI" #arbitrary action ID369 370 action_arguments = model #arguments (could be something.py)371 author = "SDO TEAM" #so that end users know who you are372 description = "START SDO watcher" #so that end users can identify the task373 task_id = "SDO_GUI_TASK"374 task_hidden = False #set this to True to hide the task in the interface375 username = ""376 password = ""377 run_flags = "TASK_RUN_NO_FLAGS" #see dict below, use in combo with username/password378 #define constants379 TASK_TRIGGER_LOGON = 9380 TASK_CREATE = 2381 TASK_CREATE_OR_UPDATE = 6382 TASK_ACTION_EXEC = 0383 TASK_LOGON_INTERACTIVE_TOKEN = 3384 IID_ITask = "{148BD524-A2AB-11CE-B11F-00AA00530503}"385 RUNFLAGSENUM = {386 "TASK_RUN_NO_FLAGS" : 0,387 "TASK_RUN_AS_SELF" : 1,388 "TASK_RUN_IGNORE_CONSTRAINTS" : 2,389 "TASK_RUN_USE_SESSION_ID" : 4,390 "TASK_RUN_USER_SID" : 8 391 }392 #connect to the scheduler (Vista/Server 2008 and above only)393 import win32com.client as win32com_client394 scheduler = win32com_client.Dispatch("Schedule.Service")395 scheduler.Connect(computer_name or None, computer_username or None, computer_userdomain or None, computer_password or None)396 rootFolder = scheduler.GetFolder("\\")397 398 #(re)define the task399 taskDef = scheduler.NewTask(0)400 colTriggers = taskDef.Triggers401 trigger = colTriggers.Create(TASK_TRIGGER_LOGON)402 trigger.Id = "LogonTriggerId"403 #trigger.UserId = os.environ.get('USERNAME') # current user account404 #trigger.Enabled = False405 colActions = taskDef.Actions406 action = colActions.Create(TASK_ACTION_EXEC)407 action.ID = action_id408 action.Path = action_path409 action.WorkingDirectory = action_workdir410 action.Arguments = action_arguments411 info = taskDef.RegistrationInfo412 info.Author = author413 info.Description = description414 settings = taskDef.Settings415 settings.Enabled = False416 settings.Hidden = task_hidden417 principal = taskDef.Principal418 principal.RunLevel = 1419 #register the task (create or update, just keep the task name the same)420 result = rootFolder.RegisterTaskDefinition(task_id, taskDef, TASK_CREATE_OR_UPDATE, "", "", TASK_LOGON_INTERACTIVE_TOKEN)421 task = rootFolder.GetTask(task_id)422 task.Enabled = True423 self.btn_persist["text"] = "Remove start on boot"424 else:425 self.btn_persist["text"] = "Start on boot"426 task.Enabled = False427 def start_stop_watcher(self):428 """429 Fonction appelé lorsque le bouton start/stop de la section watcher est appuyé430 Démarre les observeurs watchdog ou les arrêtes431 """432 # Si les watchers n'étaient pas lancés alors il s'agit d'un start433 if self.watcher_started == False:434 model = self.ent_path_model.get()435 if model == "":436 messagebox.showerror("Erreur", "Un modèle doit être renseigné.")437 return438 439 self.event_handler = SDO_Handler(self.master,model,patterns=["*.exe","*.dll"],ignore_directories=False)440 self.watcher_started = True441 self.btn_start_stop["text"] = "Stop"442 try:443 paths = open("../path.txt", "r")444 except:445 paths = ["%APPDATA%","%APPDATA%\\..\\Local\\Temp","%PUBLIC%","%ALLUSERSPROFILE%","C:\\Windows\\System32","C:\\Windows\\Temp","%CommonProgramFiles%","%ProgramFiles%","%APPDATA%\\Microsoft\\Windows\\AccountPictures","%APPDATA%\\Microsoft\\Windows\\CloudStore","%APPDATA%\\Microsoft\\Windows\\Libraries","%APPDATA%\\Microsoft\\Windows\\Start Menu","%APPDATA%\\Microsoft\\Windows\\Network Shortcuts","%APPDATA%\\Microsoft\\Windows\\Printer Shortcuts","%APPDATA%\\Microsoft\\Windows\\SendTo","%APPDATA%\\Microsoft\\Windows\\Templates","%APPDATA%\\Microsoft\\Windows\\Themes"]446 self.observers = getObservers(paths, self.event_handler)447 self.master.iconify()448 else:449 # Si les watchers étaient lancés alors il s'agit d'un stop450 self.watcher_started = False451 self.btn_start_stop["text"] = "Start"452 clean(self.observers)453 self.master.deiconify()454 def quit(self):455 """456 Fonction de fermeture de la fenêtre457 """458 self.wantToQuit = True459 self.master.quit()460 def add_one_file(self):461 """462 Fonction appelé lorsque le bouton d'Extraction des caractéristiques d'un fichier est appuyé:463 Demande à l'utilisateur le fichier à extraire avec une fenêtre de dialogue464 Puis demande à l'utilisateur le nom du fichier qui contiendra les caractéristiques extraites.465 Enfin extrait les caractéristiques et les places au format json.466 """467 file_to_extract = filedialog.askopenfilename(initialdir = ".",title = "Choisir un PE",filetypes = (("exe","*.exe"),("dll","*.dll"),("all files","*.*")))468 if file_to_extract == "":469 return470 save_file = filedialog.asksaveasfilename(initialdir = ".",title = "Sauvegardez sous",defaultextension = 'json',filetypes = (("json files","*.json"),("all files","*.*")))471 if save_file == "":472 return473 values = dict()474 caracs = Extracteur.extract_one(file_to_extract)475 values[file_to_extract] = caracs476 with open(save_file,"w") as f:477 f.write(json.dumps(values))478 messagebox.showinfo("Succès", file_to_extract+" a été extrait vers "+save_file)479 def add_json_list(self):480 """481 Fonction appelé lorsque le bouton d'Extraction des caractéristiques d'une liste de fichier est appuyé:482 Demande à l'utilisateur la liste de chemin de fichier à extraire avec une fenêtre de dialogue483 Puis demande à l'utilisateur le nom du fichier qui contiendra les caractéristiques extraites.484 Enfin extrait les caractéristiques pour chaque fichier et les places au format json.485 """486 list_to_extract = filedialog.askopenfilename(initialdir = ".",title = "Choisir une liste de PE",filetypes = (("json files","*.json"),("all files","*.*")))487 if list_to_extract == "":488 return489 save_file = filedialog.asksaveasfilename(initialdir = ".",title = "Sauvegardez sous",defaultextension = 'json',filetypes = (("json files","*.json"),("all files","*.*")))490 if save_file == "":491 return492 compteur = Extracteur.extract_list(list_to_extract,save_file)493 messagebox.showinfo("Succès", str(compteur)+"fichiers ont été extraits vers "+save_file)494 def add_whole_dir(self):495 """496 Fonction appelé lorsque le bouton d'Extraction des caractéristiques de tous les fichiers d'un dossier est appuyé:497 Demande à l'utilisateur le chemin du dossier à extraire avec une fenêtre de dialogue498 Puis demande à l'utilisateur le nom du fichier qui contiendra les caractéristiques extraites.499 Enfin extrait les caractéristiques pour chaque fichier du dossier et les places au format json.500 """501 dir_to_extract = filedialog.askdirectory(initialdir = ".", title = "Choisir un dossier d'import")502 if dir_to_extract == "":503 return504 save_file = filedialog.asksaveasfilename(initialdir = ".",title = "Sauvegardez sous",defaultextension = 'json',filetypes = (("json files","*.json"),("all files","*.*")))505 if save_file == "":506 return507 print("Listing des fichiers...")508 exe_liste = Tools.Find_all_PE.recursListPath(dir_to_extract,10)509 compteur = Extracteur.extract_list_from_list(exe_liste,save_file)510 messagebox.showinfo("Succès", str(compteur)+"fichiers ont été extraits vers "+save_file)511 def renseigneFichierClean(self):512 """513 Fonction appelé lorsque le bouton "..." à côté de l'entrée de chemin pour les fichiers sains est appuyé514 Ouvre une fenêtre de dialogue demandant un fichier515 Puis insère le chemin du fichier dans l'entrée utilisateur correspondante.516 """517 list_clean = filedialog.askopenfilename(initialdir = "../Models",title = "Choisir une extraction de fichier sains",filetypes = (("json files","*.json"),("all files","*.*")))518 self.ent_path_clean.delete(0,tk.END)519 self.ent_path_clean.insert(0,list_clean)520 def renseigneFichierMalware(self):521 """522 Fonction appelé lorsque le bouton "..." à côté de l'entrée de chemin pour les fichiers malwares est appuyé523 Ouvre une fenêtre de dialogue demandant un fichier524 Puis insère le chemin du fichier dans l'entrée utilisateur correspondante.525 """526 list_malware = filedialog.askopenfilename(initialdir = "../Models",title = "Choisir une extraction de malware",filetypes = (("json files","*.json"),("all files","*.*")))527 self.ent_path_malware.delete(0,tk.END)528 self.ent_path_malware.insert(0,list_malware)529 def renseigneFichierModel(self):530 """531 Fonction appelé lorsque le bouton "..." à côté de l'entrée de chemin pour le modèle est appuyé532 Ouvre une fenêtre de dialogue demandant un fichier533 Puis insère le chemin du fichier dans l'entrée utilisateur correspondante.534 """535 path_model = filedialog.askopenfilename(initialdir = "../Models",title = "Choisir un modèle entraîné",filetypes = (("json files","*.json"),("all files","*.*")))536 self.ent_path_model.delete(0,tk.END)537 self.ent_path_model.insert(0,path_model)538 def renseigneFichierModelOld(self):539 """540 Fonction appelé lorsque le bouton "..." à côté de l'entrée de chemin pour le modèle préexistant est appuyé541 Ouvre une fenêtre de dialogue demandant un fichier542 Puis insère le chemin du fichier dans l'entrée utilisateur correspondante.543 """544 path_model = filedialog.askopenfilename(initialdir = "../Models",title = "Choisir un modèle entraîné",filetypes = (("json files","*.json"),("all files","*.*")))545 self.ent_model_old.delete(0,tk.END)546 self.ent_model_old.insert(0,path_model)547 def trainingTE(self):548 """549 Fonction appelée lorsque le bouton d'entraînement optimisé T.E est appuyé550 Récupère les informations pour l'entrainement551 puis entraîne (2^nombre de stats ici 9) modèles puis selectionne celui obtenant le plus faible taux d'erreur552 """553 cleans, malwares, ratio_clean, ratio_malware, nom_model, model_old = self.get_data_training()554 results = CaracStats.trainingTE(cleans, malwares,ratio_clean,ratio_malware,nom_model,model_old)555 taux_faux_pos = float(results["Clean_incorrect"])/float(results["Clean_incorrect"]+results["Clean_correct"])556 taux_faux_neg = float(results["Malware_incorrect"])/float(results["Malware_incorrect"]+results["Malware_correct"])557 558 messagebox.showinfo("Succès", "Test du modèle avec données non utilisées : "+str(round(taux_faux_neg,3)*100)+ "% malwares non détectés "+str(round(taux_faux_pos,3)*100)+" % de sains flaggés")559 self.ent_path_model.delete(0,tk.END)560 self.ent_path_model.insert(0,nom_model)561 562 def trainingFN(self):563 """564 Fonction appelée lorsque le bouton d'entraînement optimisé F.N est appuyé565 Récupère les informations pour l'entrainement566 puis entraîne (2^nombre de stats ici 9) modèles puis selectionne celui obtenant le plus faible taux de faux négatif567 """568 cleans, malwares, ratio_clean, ratio_malware, nom_model, model_old = self.get_data_training()569 results = CaracStats.trainingFN(cleans, malwares,ratio_clean,ratio_malware,nom_model,model_old)570 taux_faux_pos = float(results["Clean_incorrect"])/float(results["Clean_incorrect"]+results["Clean_correct"])571 taux_faux_neg = float(results["Malware_incorrect"])/float(results["Malware_incorrect"]+results["Malware_correct"])572 573 messagebox.showinfo("Succès", "Test du modèle avec données non utilisées : "+str(round(taux_faux_neg,3)*100)+ "% malwares non détectés "+str(round(taux_faux_pos,3)*100)+" % de sains flaggés")574 self.ent_path_model.delete(0,tk.END)575 self.ent_path_model.insert(0,nom_model)576 def doTraining(self, cleans, malwares, ratio_clean, ratio_malware, nom_model, model_old):577 """578 entraîne le modèle [1,1,1,1,1,1,1,1,1] avec les caractéristiques données579 """580 results = Trainer.training(cleans, malwares,ratio_clean,ratio_malware,[1,1,1,1,1,1,1,1,1],nom_model,model_old)581 taux_faux_pos = float(results["Clean_incorrect"])/float(results["Clean_incorrect"]+results["Clean_correct"])582 taux_faux_neg = float(results["Malware_incorrect"])/float(results["Malware_incorrect"]+results["Malware_correct"])583 584 messagebox.showinfo("Succès entraînement rapide", "Test du modèle avec données non utilisées : "+str(round(taux_faux_neg,3)*100)+ "% malwares non détectés "+str(round(taux_faux_pos,3)*100)+" % de sains flaggés")585 def training(self):586 """587 Fonction appelée lorsque le bouton d'entraînement classique est appuyé588 Récupère les informations pour l'entrainement589 puis entraîne un modèle communément le meilleur590 """591 cleans, malwares, ratio_clean, ratio_malware, nom_model, model_old, opti_simple, opti_te, opti_fn = self.get_data_training()592 if opti_simple:593 self.doTraining(cleans, malwares, ratio_clean, ratio_malware, nom_model+"_rapide", model_old)594 if opti_te or opti_fn:595 opti_results = CaracStats.getTrainingsResults(cleans, malwares,9,ratio_clean,ratio_malware)596 if opti_te:597 top = CaracStats.getTopLowestError(opti_results,1)598 selecter_used = top[0][0]599 results = Trainer.training(cleans,malwares,ratio_clean,ratio_malware,selecter_used,nom_model+"_te",model_old)600 taux_faux_pos = float(results["Clean_incorrect"])/float(results["Clean_incorrect"]+results["Clean_correct"])601 taux_faux_neg = float(results["Malware_incorrect"])/float(results["Malware_incorrect"]+results["Malware_correct"])602 603 messagebox.showinfo("Succès entraînement taux erreur", "Test du modèle avec données non utilisées : "+str(round(taux_faux_neg,3)*100)+ "% malwares non détectés "+str(round(taux_faux_pos,3)*100)+" % de sains flaggés")604 if opti_fn:605 top = CaracStats.getTopLowestFalseNeg(opti_results,1)606 selecter_used = top[0][0]607 results = Trainer.training(cleans,malwares,ratio_clean,ratio_malware,selecter_used,nom_model+"_fn",model_old)608 taux_faux_pos = float(results["Clean_incorrect"])/float(results["Clean_incorrect"]+results["Clean_correct"])609 taux_faux_neg = float(results["Malware_incorrect"])/float(results["Malware_incorrect"]+results["Malware_correct"])610 611 messagebox.showinfo("Succès entraînement faux négatifs", "Test du modèle avec données non utilisées : "+str(round(taux_faux_neg,3)*100)+ "% malwares non détectés "+str(round(taux_faux_pos,3)*100)+" % de sains flaggés")612 613 def get_data_training(self):614 """615 Récupère les informations données par l'utilisateur pour l'entrainement616 """617 path_clean = self.ent_path_clean.get()618 path_malware = self.ent_path_malware.get()619 nom_model = self.ent_model.get()620 model_old = self.ent_model_old.get()621 opti_simple = self.check_basic.get()622 opti_te = self.check_te.get()623 opti_fn = self.check_fn.get()624 if opti_simple + opti_fn + opti_te == 0:625 messagebox.showinfo("Erreur", "Au moins un type d'entraînement doit être sélectionné")626 return627 if nom_model == "":628 nom_model = "SDO_model"629 nom_model = nom_model+".joblib"630 try:631 ratio_clean = float(self.ent_ratio_clean.get())632 ratio_malware = float(self.ent_ratio_malware.get())633 if ratio_clean > 1 or ratio_malware > 1 or ratio_clean < 0 or ratio_clean < 0:634 messagebox.showinfo("Erreur", "Les ratios sont entre 0 et 1")635 return636 except:637 messagebox.showinfo("Erreur", "Les ratios sont des flottants entre 0 et 1")638 return639 if path_clean == "" and path_malware == "":640 messagebox.showinfo("Erreur", "Au moins un fichier de caractéristique doit être renseigné.")641 return642 with open(path_clean, "r") as f:643 cleans = json.loads(f.read())644 with open(path_malware, "r") as f:645 malwares = json.loads(f.read())646 return cleans, malwares, ratio_clean, ratio_malware, nom_model, model_old, opti_simple, opti_te, opti_fn647 648 649 def detect_one_file(self):650 """651 Fonction appelé lorsque le bouton d'analyse d'un fichier est appuyé652 Demande à l'utilisateur le chemin du fichier à analyser puis lance l'analyse653 """654 model_name = self.ent_path_model.get()655 file_to_extract = filedialog.askopenfilename(initialdir = ".",title = "Choisir un PE",filetypes = (("exe","*.exe"),("dll","*.dll"),("all files","*.*")))656 if file_to_extract == "":657 return658 proba_sain = execute_detect_one_file(model_name, file_to_extract)659 if proba_sain >0.5:660 messagebox.showinfo("Sain", file_to_extract+" : est un fichier sain avec "+str(proba_sain*100)+"% de confiance")661 else:662 messagebox.showinfo("Malware", file_to_extract+" : est un malware avec "+str((1-proba_sain)*100)+"% de confiance")663 664 def detect_list_file(self):665 """666 Fonction appelé lorsque le bouton d'analyse d'une lsite de caractéristiques pré-extraite est appuyé667 Demande à l'utilisateur le chemin de la liste à analyser puis lance l'analyse668 Demande ensuite à l'utilisateur s'il souhaite sauvegardés les résultats pour vérification669 """670 model_name = self.ent_path_model.get()671 file_to_extract = filedialog.askopenfilename(initialdir = ".",title = "Choisir une liste de caractéristique",filetypes = (("json","*.json"),("all files","*.*")))672 if file_to_extract == "":673 return674 with open(file_to_extract, "r") as f:675 values = json.loads(f.read())676 values_only = []677 names_only = []678 for key,val in values.items():679 values_only.append(val)680 names_only.append(key)681 probas_list = SDO.classify_proba(model_name, values_only, names_only)682 clean_list = []683 malware_list = []684 for i,elem in enumerate(probas_list):685 if elem[0] > 0.5:686 clean_list.append([names_only[i], elem[0]])687 else:688 malware_list.append([names_only[i], elem[1]])689 import operator690 clean_list.sort(key=operator.itemgetter(1),reverse=True)691 malware_list.sort(key=operator.itemgetter(1),reverse=True)692 result = messagebox.askquestion("Résultats", str(len(clean_list))+ " fichiers sains et "+str(len(malware_list))+" malwares identifiés. Voulez vous extraire la liste des fichiers sains ?")693 if result == "yes":694 save_file = filedialog.asksaveasfilename(initialdir = ".",title = "Sauvegardez sous",defaultextension = 'json',filetypes = (("json files","*.json"),("all files","*.*")))695 if save_file != "":696 with open(save_file,"w") as f:697 f.write(json.dumps(clean_list))698 699 result = messagebox.askquestion("Résultats", "Rappel : "+str(len(clean_list))+ " fichiers sains et "+str(len(malware_list))+" malwares identifiés. Voulez vous extraire la liste des malwares ?")700 if result == "yes":701 save_file = filedialog.asksaveasfilename(initialdir = ".",title = "Sauvegardez sous",defaultextension = 'json',filetypes = (("json files","*.json"),("all files","*.*")))702 if save_file != "":703 with open(save_file,"w") as f:704 f.write(json.dumps(malware_list))705 706if not admin.isUserAdmin():707 admin.runAsAdmin()708else:709 model_name = None710 if len(sys.argv) >= 2:711 if type(sys.argv[-1]) == str:712 if sys.argv[-1].endswith(".joblib.json"):713 model_name = sys.argv[-1]714 root = tk.Tk()715 style = ttk.Style(root)716 style.theme_use("vista")717 root.geometry("600x430")718 my_gui = SDO_GUI(root,model_name)...

Full Screen

Full Screen

_assertions.py

Source:_assertions.py Github

copy

Full Screen

...416 timeout: float = None,417 ) -> None:418 __tracebackhide__ = True419 await self._not.to_be_empty(timeout)420 async def to_be_enabled(421 self,422 timeout: float = None,423 ) -> None:424 __tracebackhide__ = True425 await self._expect_impl(426 "to.be.enabled",427 FrameExpectOptions(timeout=timeout),428 None,429 "Locator expected to be enabled",430 )431 async def not_to_be_enabled(432 self,433 timeout: float = None,434 ) -> None:435 __tracebackhide__ = True436 await self._not.to_be_enabled(timeout)437 async def to_be_hidden(438 self,439 timeout: float = None,440 ) -> None:441 __tracebackhide__ = True442 await self._expect_impl(443 "to.be.hidden",444 FrameExpectOptions(timeout=timeout),445 None,446 "Locator expected to be hidden",447 )448 async def not_to_be_hidden(449 self,450 timeout: float = None,...

Full Screen

Full Screen

gnome-extensions-loader

Source:gnome-extensions-loader Github

copy

Full Screen

1#!/usr/bin/python32import ast3import configparser4import os5import re6import subprocess7import sys8from glob import glob9import xml.etree.ElementTree as ET10from PyQt5.QtWidgets import (11 QApplication,12 QInputDialog,13 QMainWindow,14 QMessageBox,15)16from ui.UI import Ui_MainWindow17from utils.download_extension import download_extension18class Window(QMainWindow, Ui_MainWindow):19 def __init__(self, parent=None):20 super().__init__(parent)21 self.setupUi(self)22 self.setFixedSize(250, 300)23 self.connectSignalsSlots()24 self.view_conf_files()25 self.config = configparser.ConfigParser()26 self.shell_version = get_shell_version()27 self.session = get_session_type()28 def connectSignalsSlots(self):29 self.action_Add.triggered.connect(self.add_layout)30 self.action_Remove.triggered.connect(self.remove_layout)31 self.action_About.triggered.connect(show_about)32 self.action_Overwrite.triggered.connect(self.overwrite_layout)33 self.action_Apply.triggered.connect(self.apply_layout)34 self.action_Exit.triggered.connect(self.close)35 def apply_layout(self):36 listItems = self.listWidget.selectedItems()37 if not listItems:38 show_message(39 message="Select a layout to apply.",40 title="Apply Layout",41 style="warning",42 )43 return44 for item in listItems:45 self.config.read(f"{LAYOUT_DIR}/{item.text()}.conf")46 (47 extensions_to_enable,48 extensions_to_disable,49 missing_extensions,50 ) = self.check_extensions()51 verify_installation = self.pre_installation_message(52 extensions_to_enable, extensions_to_disable, missing_extensions53 )54 if verify_installation == QMessageBox.Ok:55 (56 installation_success,57 installation_fail,58 ) = self.install_missing_extensions(missing_extensions)59 bash_command(60 [61 f"{SETUP_DIR}/utils/load_conf.sh",62 f"{item.text()}",63 f"{LAYOUT_DIR}",64 ]65 )66 post_installation_message = self.post_installation_message(67 installation_success,68 installation_fail,69 extensions_to_enable,70 extensions_to_disable,71 )72 if post_installation_message:73 show_message(74 message=f"{post_installation_message}",75 title="Applied Changes",76 style="information",77 )78 else:79 show_message(80 message="Extension configurations are loaded.",81 title="Done",82 style="information",83 )84 if installation_success:85 if re.search("wayland", self.session):86 show_message(87 message="You may need to log out for the changes to take effect.",88 title="Log out",89 style="information",90 )91 else:92 answer = show_message(93 message="Would you like to restart gnome shell?",94 title="Restart Shell",95 style="question",96 )97 if answer == QMessageBox.Ok:98 bash_command([f"{SETUP_DIR}/utils/restart_shell.sh"])99 def add_layout(self):100 text, ok = QInputDialog.getText(101 self, "Add Layout", "Enter the name of your layout:"102 )103 if ok:104 if text:105 if not os.path.isfile(f"{LAYOUT_DIR}/{str(text)}.conf"):106 self.listWidget.addItem(str(text))107 self.write_conf(text)108 else:109 show_message(110 message="Layout name exists!",111 title="Existing Name",112 style="warning",113 )114 else:115 show_message(116 message="Layout name is missing!",117 title="Missing Name",118 style="warning",119 )120 def overwrite_layout(self):121 listItems = self.listWidget.selectedItems()122 if not listItems:123 show_message(124 message="Select a layout to overwrite.",125 title="Overwrite Layout",126 style="warning",127 )128 return129 answer = show_message(130 message="Are you sure?", title="Owerwrite Layout", style="question"131 )132 if answer == QMessageBox.Ok:133 for item in listItems:134 self.write_conf(item.text())135 show_message(136 message="Layout overwritten successfully.",137 title="Overwrite Layout",138 style="information",139 )140 def write_conf(self, text):141 enabled = enabled_extensions()142 disabled = disabled_extensions()143 self.config.read_string(bash_command("dconf dump /org/gnome/shell/".split()))144 self.config.set("/", "enabled-extensions", str(enabled))145 self.config.set("/", "disabled-extensions", str(disabled))146 opts = self.config.options("/")147 for o in opts:148 if o not in ["enabled-extensions", "disabled-extensions"]:149 self.config.remove_option("/", o)150 keys = set([k for k in self.config.keys()])151 exts = ["/"]152 for e in enabled:153 xml_path = glob(154 f"{get_home()}/.local/share/gnome-shell/extensions/{e}/schemas/*.xml"155 )156 if xml_path:157 root_node = ET.parse(xml_path[0]).getroot()158 for s in root_node.findall("schema"):159 path = s.get("path")160 if path:161 sect = path.split("/")[5:-1]162 exts.append("/".join(sect))163 else:164 id = s.get("id")165 name = id.split(".")[4]166 for k in list(keys)[:]:167 if k.startswith(name):168 keys.discard(k)169 for k in keys:170 if k not in exts:171 self.config.remove_section(k)172 with open(f"{LAYOUT_DIR}/{str(text)}.conf", "w") as configfile:173 self.config.write(configfile)174 def install_missing_extensions(self, missing_extensions):175 installation_fail = set()176 installation_success = set()177 for uuid in missing_extensions:178 check_download = download_extension(LAYOUT_DIR, uuid, self.shell_version)179 if check_download:180 bash_command(181 [182 f"{SETUP_DIR}/utils/install_extension.sh",183 f"{uuid}",184 f"{LAYOUT_DIR}",185 ]186 )187 installation_success.add(uuid)188 else:189 installation_fail.add(uuid)190 return installation_success, installation_fail191 def pre_installation_message(192 self, extensions_to_enable, extensions_to_disable, missing_extensions193 ):194 # print("MISSING\n", missing_extensions)195 # print("ENABLE\n", extensions_to_enable)196 # print("DISABLE\n", extensions_to_disable)197 message = ""198 if missing_extensions:199 message += "Extensions to Install:"200 for uuid in missing_extensions:201 if uuid:202 message += f"\n- {uuid.split('@')[0]}"203 if extensions_to_enable or extensions_to_disable:204 message += "\n\n"205 if extensions_to_enable:206 message += "Extensions to Enable:"207 for uuid in extensions_to_enable:208 if uuid:209 message += f"\n- {uuid.split('@')[0]}"210 if extensions_to_disable:211 message += "\n\n"212 if extensions_to_disable:213 message += "Extensions to Disable:"214 for uuid in extensions_to_disable:215 if uuid:216 message += f"\n- {uuid.split('@')[0]}"217 if message:218 return show_message(219 message=f"{message}",220 title="Extensions",221 style="question",222 )223 return QMessageBox.Ok224 def post_installation_message(225 self,226 installation_success,227 installation_fail,228 extensions_to_enable,229 extensions_to_disable,230 ):231 post_installation_message = ""232 if installation_success:233 post_installation_message += "Installed:"234 for uuid in installation_success:235 post_installation_message += f"\n- {uuid.split('@')[0]}"236 if installation_fail or extensions_to_enable or extensions_to_disable:237 post_installation_message += "\n\n"238 # print("INSTALLED\n", installation_success)239 if installation_fail:240 post_installation_message += "Failed to Install:"241 for uuid in installation_fail:242 post_installation_message += f"\n- {uuid.split('@')[0]}"243 if extensions_to_enable or extensions_to_disable:244 post_installation_message += "\n\n"245 # print("FAILED TO INSTALL\n", installation_fail)246 extensions_to_enable = extensions_to_enable.difference(installation_fail)247 if extensions_to_enable:248 post_installation_message += "Enabled:"249 for uuid in extensions_to_enable:250 post_installation_message += f"\n- {uuid.split('@')[0]}"251 if extensions_to_disable:252 post_installation_message += "\n\n"253 # print("ENABLED\n", extensions_to_enable)254 if extensions_to_disable:255 post_installation_message += "Disabled:"256 for uuid in extensions_to_disable:257 post_installation_message += f"\n- {uuid.split('@')[0]}"258 # print("DISABLED\n", extensions_to_disable)259 return post_installation_message260 def check_extensions(self):261 to_be_enabled = set(262 ast.literal_eval(self.config.get("/", "enabled-extensions"))263 )264 currently_enabled = set(enabled_extensions())265 installed_extensions = set(all_extensions())266 to_be_enabled.discard("")267 currently_enabled.discard("")268 installed_extensions.discard("")269 missing_extensions = to_be_enabled.difference(installed_extensions)270 extensions_to_enable = to_be_enabled.difference(currently_enabled)271 extensions_to_disable = currently_enabled.difference(to_be_enabled)272 return extensions_to_enable, extensions_to_disable, missing_extensions273 def remove_layout(self):274 listItems = self.listWidget.selectedItems()275 if not listItems:276 show_message(277 message="Select a layout to remove.",278 title="Remove Layout",279 style="warning",280 )281 return282 answer = show_message(283 message="Are you sure?", title="Remove Layout", style="question"284 )285 if answer == QMessageBox.Ok:286 for item in listItems:287 self.listWidget.takeItem(self.listWidget.row(item))288 bash_command(["rm", f"{LAYOUT_DIR}/{item.text()}.conf"])289 def view_conf_files(self):290 conf_files = glob(f"{LAYOUT_DIR}/*.conf")291 conf_file_names = [i.split("/")[-1].split(".")[0] for i in conf_files]292 for name in conf_file_names:293 self.listWidget.addItem(name)294def all_extensions():295 return [296 ext for ext in bash_command(["gnome-extensions", "list"]).split("\n") if ext297 ]298def enabled_extensions():299 return [300 ext301 for ext in bash_command(["gnome-extensions", "list", "--enabled"]).split("\n")302 if ext303 ]304def disabled_extensions():305 return [306 ext307 for ext in bash_command(["gnome-extensions", "list", "--disabled"]).split("\n")308 if ext309 ]310def bash_command(bashCmd):311 with subprocess.Popen(bashCmd, stdout=subprocess.PIPE) as process:312 output, error = process.communicate()313 if not error:314 return output.decode("utf-8")315 return None316def get_shell_version():317 shell = bash_command(["gnome-shell", "--version"])318 shell = re.sub("[^0-9.]", "", shell).split(".")319 return ".".join(shell[0:2])320def get_session_type():321 session = bash_command([f"{SETUP_DIR}/utils/get_session.sh"])322 return session323def get_home():324 home_dir = bash_command(["whoami"])325 return f"/home/{home_dir[:-1]}"326def show_about():327 show_message(328 message="<p>Gnome extensions loader:</p>"329 "<p>Version: 1.0</p>"330 "<p>Emrecan Altinsoy</p>",331 title="About",332 style="information",333 )334def show_message(message=None, title=None, style=None):335 msgBox = QMessageBox()336 if style == "critical":337 msgBox.setIcon(QMessageBox.Critical)338 msgBox.setStandardButtons(QMessageBox.Ok)339 elif style == "question":340 msgBox.setIcon(QMessageBox.Question)341 msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)342 elif style == "information":343 msgBox.setIcon(QMessageBox.Information)344 msgBox.setStandardButtons(QMessageBox.Ok)345 elif style == "warning":346 msgBox.setIcon(QMessageBox.Warning)347 msgBox.setStandardButtons(QMessageBox.Ok)348 msgBox.setText(message)349 msgBox.setWindowTitle(title)350 return msgBox.exec()351if __name__ == "__main__":352 LAYOUT_DIR = f"{get_home()}/.config/gnome-extensions-loader"353 SETUP_DIR = "/usr/share/gnome-extensions-loader"354 os.makedirs(f"{LAYOUT_DIR}", exist_ok=True)355 os.makedirs(f"{LAYOUT_DIR}/extensions", exist_ok=True)356 app = QApplication(sys.argv)357 win = Window()358 win.show()...

Full Screen

Full Screen

test_assertions.py

Source:test_assertions.py Github

copy

Full Screen

...167 page.goto(server.EMPTY_PAGE)168 page.set_content("<input type=checkbox>")169 my_checkbox = page.locator("input")170 expect(my_checkbox).not_to_be_disabled()171 expect(my_checkbox).to_be_enabled()172 with pytest.raises(AssertionError):173 expect(my_checkbox).to_be_disabled(timeout=100)174 my_checkbox.evaluate("e => e.disabled = true")175 expect(my_checkbox).to_be_disabled()176 with pytest.raises(AssertionError):177 expect(my_checkbox).to_be_enabled(timeout=100)178def test_assertions_locator_to_be_editable(page: Page, server: Server) -> None:179 page.goto(server.EMPTY_PAGE)180 page.set_content("<input></input><button disabled>Text</button>")181 expect(page.locator("button")).not_to_be_editable()182 expect(page.locator("input")).to_be_editable()183 with pytest.raises(AssertionError):184 expect(page.locator("button")).to_be_editable(timeout=100)185def test_assertions_locator_to_be_empty(page: Page, server: Server) -> None:186 page.goto(server.EMPTY_PAGE)187 page.set_content(188 "<input value=text name=input1></input><input name=input2></input>"189 )190 expect(page.locator("input[name=input1]")).not_to_be_empty()191 expect(page.locator("input[name=input2]")).to_be_empty()...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful