Best Python code snippet using playwright-python
test_celestial_scanner.py
Source: test_celestial_scanner.py
1from base_test_fixture import BaseTestFixture2import server.configurator.blueprints as blueprints3import server.configurator.world as world4from server.configurator.modules import default_ships5from server.configurator.configuration import Configuration6from server.configurator.general import General, ApplicationMode7from expansion import modules8class TestCase(BaseTestFixture):9 def __init__(self, *args, **kwargs):10 super(TestCase, self).__init__(*args, **kwargs)11 self.configuration = Configuration(12 general=General(total_threads=1,13 login_udp_port=7456,14 initial_state=ApplicationMode.e_FREEZE,15 ports_pool=(12000, 12100)),16 blueprints=blueprints.DefaultBlueprints(),17 players={18 'oreman': world.Player(19 login="oreman",20 password="thinbones",21 ships=[22 default_ships.make_miner(23 name="miner-1",24 position=world.Position(25 x=0, y=0, velocity=world.Vector(0, 0))),26 ]27 )28 },29 world=world.World(30 asteroids=world.Asteroids(asteroids=[31 world.Asteroid(position=world.Position(x=10000, y=10000),32 radius=200,33 composition={world.ResourceType.e_ICE: 20,34 world.ResourceType.e_SILICATES: 20,35 world.ResourceType.e_METALS: 20})36 ])),37 )38 def get_configuration(self) -> Configuration:39 return self.configuration40 @BaseTestFixture.run_as_sync41 async def test_get_specification(self):42 await self.system_clock_fast_forward(speed_multiplier=20)43 commutator, error = await self.login('oreman', "127.0.0.1", "127.0.0.1")44 self.assertIsNotNone(commutator)45 self.assertIsNone(error)46 miner = modules.get_ship(commutator, "Miner", "miner-1")47 self.assertIsNotNone(miner)48 scanner = modules.get_celestial_scanner(miner, "scanner")49 self.assertIsNotNone(scanner)50 spec = await scanner.get_specification()51 self.assertIsNotNone(spec)52 self.assertEqual(1000, spec.max_radius_km)53 self.assertEqual(10000, spec.processing_time_us)54 @BaseTestFixture.run_as_sync55 async def test_scanning(self):56 await self.system_clock_fast_forward(speed_multiplier=20)57 commutator, error = await self.login('oreman', "127.0.0.1", "127.0.0.1")58 self.assertIsNotNone(commutator)59 self.assertIsNone(error)60 miner = modules.get_ship(commutator, "Miner", "miner-1")61 self.assertIsNotNone(miner)62 scanner = modules.get_celestial_scanner(miner, "scanner")63 self.assertIsNotNone(scanner)64 result = []65 errors = []66 def scanning_cb(objects, e):67 if objects:68 result.extend(objects)69 else:70 errors.append(e)71 self.assertIsNone(await scanner.scan(72 scanning_radius_km=20,73 minimal_radius_m=300,74 scanning_cb=scanning_cb))75 self.assertIsNone(error)76 self.assertEqual([], result)77 self.assertIsNone(await scanner.scan(78 scanning_radius_km=20,79 minimal_radius_m=200,80 scanning_cb=scanning_cb))81 self.assertIsNone(error)82 self.assertEqual(1, len(result))83 @BaseTestFixture.run_as_sync84 async def test_scanning_sync(self):85 await self.system_clock_fast_forward(speed_multiplier=20)86 commutator, error = await self.login('oreman', "127.0.0.1", "127.0.0.1")87 self.assertIsNotNone(commutator)88 self.assertIsNone(error)89 miner = modules.get_ship(commutator, "Miner", "miner-1")90 self.assertIsNotNone(miner)91 scanner = modules.get_celestial_scanner(miner, "scanner")92 self.assertIsNotNone(scanner)93 result, error = await scanner.scan_sync(scanning_radius_km=20,94 minimal_radius_m=300)95 self.assertIsNone(error)96 self.assertEqual([], result)97 result, error = await scanner.scan_sync(scanning_radius_km=20,98 minimal_radius_m=200)99 self.assertIsNone(error)...
scripts.py
Source: scripts.py
1from pathlib import Path2import click3import ujson as json4from ray_ci_tracker.common import run_as_sync5from ray_ci_tracker.data_source.buildkite import BuildkiteSource6from ray_ci_tracker.data_source.github import GithubDataSource7from ray_ci_tracker.data_source.s3 import S3DataSource8from ray_ci_tracker.database import ResultsDBReader, ResultsDBWriter9from ray_ci_tracker.interfaces import SiteDisplayRoot, SiteFailedTest10@click.group()11@click.option("--cached-github/--no-cached-github", default=True)12@click.option("--cached-s3/--no-cached-s3", default=True)13@click.option("--cached-buildkite/--no-cached-buildkite", default=True)14@click.option("--cached-gha/--no-cached-gha", default=True)15@click.pass_context16def cli(17 ctx,18 cached_github: bool,19 cached_s3: bool,20 cached_buildkite: bool,21 cached_gha: bool,22):23 ctx.ensure_object(dict)24 ctx.obj["cached_github"] = cached_github25 ctx.obj["cached_s3"] = cached_s326 ctx.obj["cached_buildkite"] = cached_buildkite27 ctx.obj["cached_gha"] = cached_gha28async def _downloader(29 ctx,30 cache_dir: str,31):32 cache_path = Path(cache_dir)33 cache_path.mkdir(exist_ok=True)34 print("ð Fetching Commits from Github")35 commits = await GithubDataSource.fetch_commits(cache_path, ctx.obj["cached_github"])36 print("ð» Downloading Files from S3")37 build_events = await S3DataSource.fetch_all(38 cache_path, ctx.obj["cached_s3"], commits39 )40 print("ð» Downloading Files from Buildkite")41 (42 buildkite_parsed,43 macos_bazel_events,44 pr_build_time,45 ) = await BuildkiteSource.fetch_all(46 cache_path, ctx.obj["cached_buildkite"], commits47 )48 # print("ð» Downloading Github Action Status")49 # gha_status = await GithubDataSource.fetch_all(50 # cache_path, ctx.obj["cached_gha"], commits51 # )52 return {53 "commits": commits,54 "bazel_events": macos_bazel_events + build_events,55 "buildkite_status": buildkite_parsed,56 # "gha_status": gha_status,57 "pr_build_time": pr_build_time,58 }59@cli.command("download")60@click.argument("cache-dir")61@click.pass_context62@run_as_sync63async def download(ctx, cache_dir):64 await _downloader(ctx, cache_dir)65@cli.command("etl")66@click.argument("cache_dir")67@click.argument("db_path")68@click.pass_context69@run_as_sync70async def etl_process(ctx, cache_dir, db_path):71 loaded = await _downloader(ctx, cache_dir)72 print("âï¸ Writing Data")73 db = ResultsDBWriter(db_path, wipe=True)74 print("[1/n] Writing commits")75 db.write_commits(loaded["commits"])76 print("[2/n] Writing build results")77 db.write_build_results(loaded["bazel_events"])78 print("[3/n] Writing buildkite")79 db.write_buildkite_data(loaded["buildkite_status"])80 db.write_buildkite_pr_time(loaded["pr_build_time"])81 # print("[4/n] Writing github action")82 # db.write_gha_data(loaded["gha_status"])83 print("[5/n] fixing data with backfill")84 db.backfill_test_owners()85@cli.command("analysis")86@click.argument("db_path")87@click.argument("frontend_json_path")88def perform_analysis(db_path, frontend_json_path):89 print("ð® Analyzing Data")90 db = ResultsDBReader(db_path)91 failed_tests = db.list_tests_ordered()92 data_to_display = [93 SiteFailedTest(94 name=test_name,95 status_segment_bar=db.get_commit_tooltips(test_name),96 travis_links=db.get_travis_link(test_name),97 build_time_stats=db.get_recent_build_time_stats(test_name),98 is_labeled_flaky=db.get_marked_flaky_status(test_name),99 owner=db.get_test_owner(test_name),100 )101 for test_name, _ in failed_tests102 ]103 root_display = SiteDisplayRoot(104 failed_tests=data_to_display,105 stats=db.get_stats(),106 test_owners=db.get_all_owners(),107 table_stat=db.get_table_stat(),108 )109 print("âï¸ Writing Out to Frontend", frontend_json_path)110 with open(frontend_json_path, "w") as f:...
test_administrator.py
Source: test_administrator.py
1import time2from base_test_fixture import BaseTestFixture3import server.configurator.blueprints as blueprints4import server.configurator.world as world5from server.configurator.configuration import Configuration6from server.configurator.general import General, ApplicationMode7from randomizer import Randomizer8import expansion.types as types9class TestCase(BaseTestFixture):10 def __init__(self, *args, **kwargs):11 super(TestCase, self).__init__(*args, **kwargs)12 self.configuration = Configuration(13 general=General(total_threads=1,14 login_udp_port=7456,15 initial_state=ApplicationMode.e_FREEZE,16 ports_pool=(12000, 12100)),17 blueprints=blueprints.DefaultBlueprints(),18 world=world.World(),19 players={20 'spy007': world.Player(21 login="spy007",22 password="iamspy",23 ships=[]24 )25 }26 )27 def get_configuration(self) -> Configuration:28 return self.configuration29 @BaseTestFixture.run_as_sync30 async def test_time_freezed(self):31 for i in range(3):32 ingame_time = await self.system_clock_time()33 self.assertIsNotNone(ingame_time, f"Iteration {i}")34 self.assertEqual(0, ingame_time, f"Iteration {i}")35 time.sleep(0.1)36 @BaseTestFixture.run_as_sync37 async def test_time_proceed(self):38 ingame_time = await self.system_clock_time()39 assert ingame_time is not None40 self.assertEqual(0, ingame_time)41 status, new_ingame_time = await self.system_clock_proceed(proceed_ms=2000, timeout_s=1)42 self.assertTrue(status)43 time_delta = new_ingame_time - ingame_time44 self.assertAlmostEqual(2000000, time_delta, delta=1000)45 @BaseTestFixture.run_as_sync46 async def test_switch_mode(self):47 ingame_time = await self.system_clock_time()48 assert ingame_time is not None49 self.assertEqual(0, ingame_time)50 self.assertTrue(await self.system_clock_play())51 time.sleep(1)52 status, ingame_time = await self.system_clock_stop()53 self.assertTrue(status)54 # Rude check with 5% accuracy:55 self.assertAlmostEqual(1000000, ingame_time, delta=50000)56 @BaseTestFixture.run_as_sync57 async def test_spawn_asteroids(self):58 """Check that spawn.asteroid request returns asteroid id"""59 self.assertTrue(await self.system_clock_play())60 randomizer = Randomizer(2132)61 spawner = self.administrator.spawner62 for i in range(100):63 now = await self.system_clock_time()64 asteroid_id, timestamp = await spawner.spawn_asteroid(65 position=randomizer.random_position(66 rect=types.Rect(-1000, 1000, -1000, 1000),67 min_speed=0,68 max_speed=100069 ),70 composition=types.make_resources(ice=100, metals=32),71 radius=1072 )73 assert asteroid_id is not None...
__init__.py
Source: __init__.py
...7import numpy as np8from tabulate import tabulate9def utc_now():10 return datetime.datetime.now(datetime.timezone.utc)11def run_as_sync(coroutine, loop = None):12 if loop is None:13 loop = asyncio.get_event_loop()14 future = asyncio.run_coroutine_threadsafe(coroutine, loop)15 return future.result()16async def run_as_async(function, *args, **kwargs):17 loop = asyncio.get_running_loop()18 partial_function = partial(function, *args, **kwargs)19 return await loop.run_in_executor(None, partial_function)20def get_file_extension(filename):21 filename = Path(filename)22 return filename.suffix23def unit_prefix(value, prefix_name):24 prefixes = {25 'y': 1e-24,...
What are the differences between Python Playwright sync vs. async APIs?
Python Playwright pagelocator pass variable
Why does Playwright not change url once button is clicked on Uber Eats?
How to open a new tab using Python Playwright by feeding it a list of URLs?
Using Playwright for Python, how to I read the content of an input box
how to add playwright docker image to docker compose?
playwright headless chromium can't find selector, but finds it in UI mode
How to wait for element not present using Playwright
pytest file structure - where to put repeated code
Python playwright won't let me open user profile other than default profile
The sync_api
is simply a wrapper around the asyncio_api
that abstracts asyncio usage away from you. As such, the capabilities are largely the same, but the async_api
may afford some more flexibility in complex scenarios (for example, in previous playwright-python releases the only way to run instances in a multi-threaded fashion on Unix + Python 3.7 was to use the async_api
for reasons I won't get into here).
Chances are you won't need that flexibility though, so I'd just suggest using whatever you're comfortable with.
Check out the latest blogs from LambdaTest on this topic:
The speed at which tests are executed and the “dearth of smartness” in testing are the two major problems developers and testers encounter.
In today’s data-driven world, the ability to access and analyze large amounts of data can give researchers, businesses & organizations a competitive edge. One of the most important & free sources of this data is the Internet, which can be accessed and mined through web scraping.
It is essential for a team, when speaking about test automation, to take the time needed to think, analyze and try what will be the best tool, framework, and language that suits your team’s needs.
Open MCT is a next-generation mission control framework for data visualization on desktop and mobile devices. It was created at NASA’s Ames Research Center, and NASA uses it to analyze spacecraft mission data.
It’s essential to test all components of your website to see if they work as expected. Playwright’s end to end testing capability helps you achieve this easily. However, if you’re comfortable using Python, you can pair it with the Playwright testing framework to run Python end to end testing on your website.
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.
Get 100 minutes of automation test minutes FREE!!