Best Python code snippet using play_selenium_python
playwright.py
Source:playwright.py
1from asyncio import as_completed2from pathlib import Path3from typing import Dict, Optional4import translators as ts5from attr import attrs, attrib6from attr.validators import instance_of7from playwright.async_api import Browser, Playwright, Page, BrowserContext, ElementHandle8from playwright.async_api import async_playwright, TimeoutError9from rich.progress import track10from utils import settings11from utils.console import print_step, print_substep12import webdriver.common as common13common.default_exception = TimeoutError14@attrs15class Browser:16 """17 Args:18 default_Viewport (dict):Pyppeteer Browser default_Viewport options19 browser (BrowserCls): Pyppeteer Browser instance20 """21 default_Viewport: dict = attrib(22 validator=instance_of(dict),23 default={24 # 9x21 to see long posts25 "width": 500,26 "height": 1200,27 },28 kw_only=True,29 )30 playwright: Playwright31 browser: Browser32 context: BrowserContext33 async def get_browser(34 self,35 ) -> None:36 """37 Creates Playwright instance & browser38 """39 self.playwright = await async_playwright().start()40 self.browser = await self.playwright.chromium.launch()41 self.context = await self.browser.new_context(viewport=self.default_Viewport)42 async def close_browser(43 self,44 ) -> None:45 """46 Closes Playwright stuff47 """48 await self.context.close()49 await self.browser.close()50 await self.playwright.stop()51class Flaky:52 """53 All methods decorated with function catching default exceptions and writing logs54 """55 @staticmethod56 @common.catch_exception57 async def find_element(58 selector: str,59 page_instance: Page,60 options: Optional[dict] = None,61 ) -> ElementHandle:62 return (63 await page_instance.wait_for_selector(selector, **options)64 if options65 else await page_instance.wait_for_selector(selector)66 )67 @common.catch_exception68 async def click(69 self,70 page_instance: Optional[Page] = None,71 query: Optional[str] = None,72 options: Optional[dict] = None,73 *,74 find_options: Optional[dict] = None,75 element: Optional[ElementHandle] = None,76 ) -> None:77 if element:78 await element.click(**options) if options else await element.click()79 else:80 results = (81 await self.find_element(query, page_instance, **find_options)82 if find_options83 else await self.find_element(query, page_instance)84 )85 await results.click(**options) if options else await results.click()86 @common.catch_exception87 async def screenshot(88 self,89 page_instance: Optional[Page] = None,90 query: Optional[str] = None,91 options: Optional[dict] = None,92 *,93 find_options: Optional[dict] = None,94 element: Optional[ElementHandle] = None,95 ) -> None:96 if element:97 await element.screenshot(**options) if options else await element.screenshot()98 else:99 results = (100 await self.find_element(query, page_instance, **find_options)101 if find_options102 else await self.find_element(query, page_instance)103 )104 await results.screenshot(**options) if options else await results.screenshot()105@attrs(auto_attribs=True)106class RedditScreenshot(Flaky, Browser):107 """108 Args:109 reddit_object (Dict): Reddit object received from reddit/subreddit.py110 screenshot_idx (int): List with indexes of voiced comments111 story_mode (bool): If submission is a story takes screenshot of the story112 """113 reddit_object: dict114 screenshot_idx: list115 story_mode: Optional[bool] = attrib(116 validator=instance_of(bool),117 default=False,118 kw_only=True119 )120 def __attrs_post_init__(121 self122 ):123 self.post_lang: Optional[bool] = settings.config["reddit"]["thread"]["post_lang"]124 async def __dark_theme( # TODO isn't working125 self,126 page_instance: Page,127 ) -> None:128 """129 Enables dark theme in Reddit130 Args:131 page_instance: Pyppeteer page instance with reddit page opened132 """133 await self.click(134 page_instance,135 ".header-user-dropdown",136 )137 # It's normal not to find it, sometimes there is none :shrug:138 await self.click(139 page_instance,140 "button >> span:has-text('Settings')",141 )142 await self.click(143 page_instance,144 "button >> span:has-text('Dark Mode')",145 )146 # Closes settings147 await self.click(148 page_instance,149 ".header-user-dropdown"150 )151 async def __close_nsfw(152 self,153 page_instance: Page,154 ) -> None:155 """156 Closes NSFW stuff157 Args:158 page_instance: Instance of main page159 """160 print_substep("Post is NSFW. You are spicy...")161 # Triggers indirectly reload162 await self.click(163 page_instance,164 "button:has-text('Yes')",165 {"timeout": 5000},166 )167 # Await indirect reload168 await page_instance.wait_for_load_state()169 await self.click(170 page_instance,171 "button:has-text('Click to see nsfw')",172 {"timeout": 5000},173 )174 async def __collect_comment(175 self,176 comment_obj: dict,177 filename_idx: int,178 ) -> None:179 """180 Makes a screenshot of the comment181 Args:182 comment_obj: prew comment object183 filename_idx: index for the filename184 """185 comment_page = await self.context.new_page()186 await comment_page.goto(187 f'https://reddit.com{comment_obj["comment_url"]}',188 timeout=0, # Fix for Navigation TimeoutError189 )190 # Translates submission' comment191 if self.post_lang:192 comment_tl = ts.google(193 comment_obj["comment_body"],194 to_language=self.post_lang,195 )196 await comment_page.evaluate(197 '([comment_id, comment_tl]) => document.querySelector(`#t1_${comment_id} > div:nth-child(2) > div > div[data-testid="comment"] > div`).textContent = comment_tl', # noqa198 [comment_obj["comment_id"], comment_tl],199 )200 await self.screenshot(201 comment_page,202 f"id=t1_{comment_obj['comment_id']}",203 {"path": f"assets/temp/png/comment_{filename_idx}.png"},204 )205 # WIP TODO test it206 async def __collect_story(207 self,208 main_page: Page,209 ):210 # Translates submission text211 if self.post_lang:212 story_tl = ts.google(213 self.reddit_object["thread_post"],214 to_language=self.post_lang,215 )216 split_story_tl = story_tl.split('\n')217 await main_page.evaluate(218 "(split_story_tl) => split_story_tl.map(function(element, i) { return [element, document.querySelectorAll('[data-test-id=\"post-content\"] > [data-click-id=\"text\"] > div > p')[i]]; }).forEach(mappedElement => mappedElement[1].textContent = mappedElement[0])", # noqa219 split_story_tl,220 )221 await self.screenshot(222 main_page,223 "//div[@data-test-id='post-content']//div[@data-click-id='text']",224 {"path": "assets/temp/png/story_content.png"},225 )226 async def download(227 self,228 ):229 """230 Downloads screenshots of reddit posts as seen on the web. Downloads to assets/temp/png231 """232 print_step("Downloading screenshots of reddit posts...")233 print_substep("Launching Headless Browser...")234 await self.get_browser()235 # ! Make sure the reddit screenshots folder exists236 Path("assets/temp/png").mkdir(parents=True, exist_ok=True)237 # Get the thread screenshot238 reddit_main = await self.context.new_page()239 await reddit_main.goto( # noqa240 self.reddit_object["thread_url"],241 timeout=0, # Fix for Navigation TimeoutError242 )243 if settings.config["settings"]["theme"] == "dark":244 await self.__dark_theme(reddit_main)245 if self.reddit_object["is_nsfw"]:246 # This means the post is NSFW and requires to click the proceed button.247 await self.__close_nsfw(reddit_main)248 # Translates submission title249 if self.post_lang:250 print_substep("Translating post...")251 texts_in_tl = ts.google(252 self.reddit_object["thread_title"],253 to_language=self.post_lang,254 )255 await reddit_main.evaluate(256 f"(texts_in_tl) => document.querySelector('[data-test-id=\"post-content\"] > div:nth-child(3) > div > div').textContent = texts_in_tl", # noqa257 texts_in_tl,258 )259 else:260 print_substep("Skipping translation...")261 # No sense to move it to common.py262 async_tasks_primary = ( # noqa263 [264 self.__collect_comment(self.reddit_object["comments"][idx], idx) for idx in265 self.screenshot_idx266 ]267 if not self.story_mode268 else [269 self.__collect_story(reddit_main)270 ]271 )272 async_tasks_primary.append(273 self.screenshot(274 reddit_main,275 f"id=t3_{self.reddit_object['thread_id']}",276 {"path": "assets/temp/png/title.png"},277 )278 )279 for idx, chunked_tasks in enumerate(280 [chunk for chunk in common.chunks(async_tasks_primary, 10)],281 start=1,282 ):283 chunk_list = async_tasks_primary.__len__() // 10 + (1 if async_tasks_primary.__len__() % 10 != 0 else 0)284 for task in track(285 as_completed(chunked_tasks),286 description=f"Downloading comments: Chunk {idx}/{chunk_list}",287 total=chunked_tasks.__len__(),288 ):289 await task290 print_substep("Comments downloaded Successfully.", style="bold green")...
model_tests.py
Source:model_tests.py
1from __future__ import print_function2from __future__ import unicode_literals3from __future__ import division4from __future__ import absolute_import5from mycms import wingdbstub6# Imports7import unittest8import mock9from random import randint10import loremipsum11# Django Imports12from django.test import TestCase13from django.template.defaultfilters import slugify14from django.http import HttpRequest15# Local Application Imports16import mycms17from mycms import exceptions18from mycms import pageview19from mycms.models import Pages20from mycms.models import Paths21from mycms import YACMS_BASE_URL22from django.conf import settings23class ModelTests(unittest.TestCase):24 def test_can_create_default_base_path(self):25 """Ensure that we can create a base path, where entry 26 is at / and has no parent"""27 # In order to be able to do this test, we need to delete all the28 # Paths29 for entry in Pages.objects.all():30 entry.delete()31 for entry in Paths.objects.all():32 entry.delete()33 path_instance = Paths()34 path_instance.save()35 self.assertEqual(path_instance.path, "/")36 def test_can_create_root_path(self):37 """Ensure we can create a basic Path entry"""38 path_instance = Paths(path="/sysadmin")39 path_instance.save()40 retrieved_path_instance = Paths.objects.get(path="/sysadmin")41 self.assertEqual(retrieved_path_instance, path_instance)42 def test_can_create_parent_paths_recursively(self):43 path_instance = Paths(path="/foo/bar/baz")44 path_instance.save()45 foo_bar_baz = Paths.objects.get(path="/foo/bar/baz")46 foo_bar = Paths.objects.get(path="/foo/bar")47 foo = Paths.objects.get(path="/foo")48 self.assertEqual(foo_bar_baz.path, "/foo/bar/baz")49 self.assertEqual(foo_bar.path, "/foo/bar")50 self.assertEqual(foo.path, "/foo")51 def test_can_create_a_page_entry(self):52 """53 Ensure that given a path, we can create a page. This test54 provides all the required values. 55 """56 path_instance = Paths(path="/this/is/a/test/article")57 path_instance.save()58 page_instance = Pages()59 page_values = {60 "title": "This is the title",61 "content": "This is just some content.",62 "page_type": "HTMLPAGE",63 "template": "index.html",64 "frontpage": True,65 "published": True,66 "meta_description": "This is the meta description.",67 "article_logo": "fedora-logo.png",68 }69 page_instance.path = path_instance70 page_instance.title = page_values.get("title")71 page_instance.slug = slugify(page_values.get("title"))72 page_instance.content = page_values.get("content")73 page_instance.page_type = page_values.get("page_type")74 page_instance.template = page_values.get("template")75 page_instance.frontpage = page_values.get("frontpage")76 page_instance.published = page_values.get("published")77 page_instance.meta_description = page_values.get("meta_description")78 page_instance.article_logo = page_values.get("article_logo")79 page_instance.save()80 # The use cases is to load by path so we try to do the same here.81 page_instance_from_db = Pages.objects.get(path=path_instance)82 # Now ensure that everything was saved properly.83 for key in page_values.keys():84 page_value = page_values.get(key)85 db_value = getattr(page_instance_from_db, key)86 print("Comparing \t'{}' \t: \t db '{}'".format(page_value, db_value))87 self.assertEqual(page_value, db_value)88 def test_can_create_a_page_with_default_values_via_save_override(self):89 """90 This test creates a page given a minimum amount of values. 91 """92 path_instance = Paths(path="/this/is/a/test/mimimal_article")93 path_instance.save()94 page_instance = Pages()95 page_values = {96 "title": "This is the title",97 "content": "This is just some content.",98 "page_type": "HTMLPAGE",99 "template": "index.html",100 "frontpage": True,101 "published": True,102 "meta_description": "This is the meta description.",103 "article_logo": "fedora-logo.png",104 }105 page_instance.path = path_instance106 page_instance.title = page_values.get("title")107 # Do not set the slug because it should be filled automatically108 # page_instance.slug = slugify(page_values.get("title"))109 page_instance.content = page_values.get("content")110 page_instance.page_type = page_values.get("page_type")111 # Do not set the template because ave should fill it in automatically112 # page_instance.template = page_values.get("template")113 page_instance.frontpage = page_values.get("frontpage")114 page_instance.published = page_values.get("published")115 page_instance.meta_description = page_values.get("meta_description")116 page_instance.article_logo = page_values.get("article_logo")117 page_instance.save()118 print(page_instance.slug)119 self.assertEqual(page_instance.slug, slugify(page_values.get("title")))120 self.assertEqual(121 page_instance.template, "{}.html".format(page_instance.page_type.lower())122 )123class ExtendedModelTests(unittest.TestCase):124 """Test the rest of the attributes."""125 def setUp(self):126 """Create a base url"""127 self.path_inst = Paths(path="/articles/my-test-article")128 self.path_inst.save()129 page = Pages()130 page.path = self.path_inst131 page.title = "My Test Article"132 page.content = "This is just a dummy content"133 page.page_type = "HTMLVIEW"134 page.frontpage = True135 page.published = True136 page.meta_description = ""137 page.save()138 self.page_instance = page139 def test_get_absoloute_url(self):140 """Tests to show that we can get a correct absolute URL."""141 # Ensure that we can get a correct absolute URL142 # Override the settings.YACMS_BASE_URL with our value143 url = self.page_instance.get_absolute_url()144 expected_url = "/{}{}".format(145 mycms.YACMS_BASE_URL, self.page_instance.path.path.lstrip("/")146 )147 self.assertEqual(url, expected_url)148 # def test_introduction(self):149 # self.fail()150 # def test_logo(self):151 # self.fail()152 # def test_data_dict(self):153 # self.fail()154 # def test_view(self):155 # """A simple test to show that view returns a PageView. This will156 # fail if something is wrong with the pageview module which has its157 # own set of tests."""...
InstallerHelper.py
Source:InstallerHelper.py
1import subprocess2import os3import threading4#Class to help installer page5class Helper:6 def __init__(self, json_instance, programs_selected, page_instance):7 self.json_instance = json_instance8 self.programs_selected = programs_selected9 self.page_instance = page_instance10 self.commands_to_execute = []11 self.programs_to_execute = []12 self.select_deselect_all = 013 self.select_deselect_basic = 014 self.select_deselect_essential = 015 #Downloads the selected programs16 def download(self):17 i = 018 while i < len(self.json_instance.json_keys):19 if self.get_button_status(i):20 print(self.json_instance.json_commands[i])21 self.commands_to_execute.append(self.json_instance.json_commands[i])22 self.programs_to_execute.append(self.json_instance.json_names[i])23 i+=124 25 if(len(self.commands_to_execute)):26 print("Existem processos!")27 self.update_label()28 29 #Get button status30 def get_button_status(self, key):31 return self.programs_selected.programs_selected[key].get()32 #Function to change progress label33 def update_label(self):34 self.process_checker()35 self.page_instance.download_label['text'] = "Aplicativos Instalados!"36 #Function to check the process37 def process_checker(self):38 bar_checker = 100/len(self.commands_to_execute)39 self.page_instance.pb["value"] = 040 self.page_instance.pb.update()41 while(len(self.commands_to_execute) > 0):42 self.page_instance.download_label['text'] = f"Instalando {self.programs_to_execute[0]}..."43 self.page_instance.pb.update()44 threading.Thread(target=os.system(self.commands_to_execute[0]))45 self.page_instance.pb["value"] += bar_checker46 del self.commands_to_execute[0]47 del self.programs_to_execute[0]48 self.page_instance.pb.update()49 50 #Split executable commands 51 def __split_commands(self, command):52 commands_splitted = []53 commands_splitted = command.split(' ')54 return commands_splitted55 def install_all_programs(self):56 i=057 self.select_deselect_all += 158 while i < len(self.programs_selected.programs_selected):59 if self.select_deselect_all % 2 == 0:60 self.programs_selected.programs_selected[i].set(0)61 else:62 self.programs_selected.programs_selected[i].set(1)63 i += 164 65 def install_basic_programs(self):66 i=067 self.select_deselect_basic += 168 while i < len(self.json_instance.data):69 if(self.json_instance.json_keys[i] in self.programs_selected.basic_programs):70 if self.select_deselect_basic % 2 == 0:71 self.programs_selected.programs_selected[i].set(0)72 else:73 self.programs_selected.programs_selected[i].set(1)74 i += 175 def install_essential_programs(self):76 i=077 self.select_deselect_essential += 178 while i < len(self.json_instance.data):79 if(self.json_instance.json_keys[i] in self.programs_selected.essential_programs):80 if self.select_deselect_essential % 2 == 0:81 self.programs_selected.programs_selected[i].set(0)82 else:83 self.programs_selected.programs_selected[i].set(1)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!