How to use set_geolocation method in Playwright Python

Best Python code snippet using playwright-python

geoimport_gui.py

Source:geoimport_gui.py Github

copy

Full Screen

...214 'Pixmap': 'Std_Tool1',215 'MenuText': 'Elevation Grid',216 'ToolTip': 'Create Elevation Grid '217 }218FreeCADGui.addCommand('Set Geo Location', set_geolocation())219FreeCADGui.addCommand('Import TMS', import_tms())220FreeCADGui.addCommand('Import WMS', import_wms())221FreeCADGui.addCommand('Import WFS', import_wfs())222FreeCADGui.addCommand('Import PDOK', import_pdok())223FreeCADGui.addCommand('Import OSM', import_osm())224FreeCADGui.addCommand('Import CSV', import_csv())225FreeCADGui.addCommand('Import GPX', import_gpx())226FreeCADGui.addCommand('Import Heights', importheights())227FreeCADGui.addCommand('Import SRTM', importsrtm())228FreeCADGui.addCommand('Import XYZ', import_xyz())229FreeCADGui.addCommand('Import LatLonZ', import_latlony())230FreeCADGui.addCommand('Import Image', import_image())231FreeCADGui.addCommand('Import ASTER', import_aster())232FreeCADGui.addCommand('Import LIDAR', import_lidar())...

Full Screen

Full Screen

test_geolocation.py

Source:test_geolocation.py Github

copy

Full Screen

...15from playwright.async_api import BrowserContext, Error, Page16async def test_should_work(page: Page, server, context: BrowserContext):17 await context.grant_permissions(["geolocation"])18 await page.goto(server.EMPTY_PAGE)19 await context.set_geolocation({"latitude": 10, "longitude": 10})20 geolocation = await page.evaluate(21 """() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {22 resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});23 }))"""24 )25 assert geolocation == {"latitude": 10, "longitude": 10}26async def test_should_throw_when_invalid_longitude(context):27 with pytest.raises(Error) as exc:28 await context.set_geolocation({"latitude": 10, "longitude": 200})29 assert (30 "geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed."31 in exc.value.message32 )33async def test_should_isolate_contexts(page, server, context, browser):34 await context.grant_permissions(["geolocation"])35 await context.set_geolocation({"latitude": 10, "longitude": 10})36 await page.goto(server.EMPTY_PAGE)37 context2 = await browser.new_context(38 permissions=["geolocation"], geolocation={"latitude": 20, "longitude": 20}39 )40 page2 = await context2.new_page()41 await page2.goto(server.EMPTY_PAGE)42 geolocation = await page.evaluate(43 """() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {44 resolve({latitude: position.coords.latitude, longitude: position.coords.longitude})45 }))"""46 )47 assert geolocation == {"latitude": 10, "longitude": 10}48 geolocation2 = await page2.evaluate(49 """() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {50 resolve({latitude: position.coords.latitude, longitude: position.coords.longitude})51 }))"""52 )53 assert geolocation2 == {"latitude": 20, "longitude": 20}54 await context2.close()55async def test_should_use_context_options(browser, server):56 options = {57 "geolocation": {"latitude": 10, "longitude": 10},58 "permissions": ["geolocation"],59 }60 context = await browser.new_context(**options)61 page = await context.new_page()62 await page.goto(server.EMPTY_PAGE)63 geolocation = await page.evaluate(64 """() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {65 resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});66 }))"""67 )68 assert geolocation == {"latitude": 10, "longitude": 10}69 await context.close()70async def test_watch_position_should_be_notified(page, server, context):71 await context.grant_permissions(["geolocation"])72 await page.goto(server.EMPTY_PAGE)73 messages = []74 page.on("console", lambda message: messages.append(message.text))75 await context.set_geolocation({"latitude": 0, "longitude": 0})76 await page.evaluate(77 """() => {78 navigator.geolocation.watchPosition(pos => {79 const coords = pos.coords;80 console.log(`lat=${coords.latitude} lng=${coords.longitude}`);81 }, err => {});82 }"""83 )84 async with page.expect_console_message(lambda m: "lat=0 lng=10" in m.text):85 await context.set_geolocation({"latitude": 0, "longitude": 10})86 async with page.expect_console_message(lambda m: "lat=20 lng=30" in m.text):87 await context.set_geolocation({"latitude": 20, "longitude": 30})88 async with page.expect_console_message(lambda m: "lat=40 lng=50" in m.text):89 await context.set_geolocation({"latitude": 40, "longitude": 50})90 all_messages = "|".join(messages)91 "latitude=0 lng=10" in all_messages92 "latitude=20 lng=30" in all_messages93 "latitude=40 lng=50" in all_messages94async def test_should_use_context_options_for_popup(page, context, server):95 await context.grant_permissions(["geolocation"])96 await context.set_geolocation({"latitude": 10, "longitude": 10})97 async with page.expect_popup() as popup_info:98 await page.evaluate(99 "url => window._popup = window.open(url)",100 server.PREFIX + "/geolocation.html",101 )102 popup = await popup_info.value103 await popup.wait_for_load_state()104 geolocation = await popup.evaluate("() => window.geolocationPromise")...

Full Screen

Full Screen

startbot.py

Source:startbot.py Github

copy

Full Screen

1from asyncio.windows_events import NULL2from typing import Set3from aiogram.types import location4from aiogram.types.message import Message5from aiogram.types.reply_keyboard import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove6from aiogram.contrib.fsm_storage.memory import MemoryStorage7from django.core.management.base import BaseCommand8import logging9import os10from aiogram import Bot, Dispatcher, executor, types11from aiogram.dispatcher.filters.state import State, StatesGroup12from aiogram.dispatcher import FSMContext13class Command(BaseCommand):14 help = "Start telegram bot"15 def handle(self, *args, **kwargs):16 17 API_TOKEN = str(os.getenv('BOT_TOKEN'))18 # Initialize bot and dispatcher19 bot = Bot(token=API_TOKEN)20 dp = Dispatcher(bot, storage=MemoryStorage())21 logging.basicConfig(level=logging.INFO)22 '''23 Конечный автомат для настроек:24 Если пользователь новый:25 #/start -> menu -> button-geo -> set_geolocation -> menu -> button-time -> set_sendtime -> menu26 Если пользователь сущесвует:27 #/settings -> menu -> button-geo/button-time -> add -> set_geolocation/set_sendtime28 #/settings -> menu -> button-geo/button-time -> delete -> delete_geolocation/delete_sendtime29 #30 '''31 keyboard = ReplyKeyboardMarkup(resize_keyboard=True)32 geo_button = KeyboardButton(text='Geolocation')33 alert_time = KeyboardButton(text='Time')34 buttons = [geo_button, alert_time]35 keyboard.add(*buttons)36 37 class Settings(StatesGroup):38 show_menu_settings = State()39 set_location = State()40 set_time = State()41 42 @dp.message_handler(commands=['start'])43 #при нажатии кнопки, информация о пользователе должна падать в логи и создавать в моделях запись о юзере44 async def send_welcome(message: types.Message):45 """46 This handler will be called when user sends `/start`47 """48 logging.info(f"User: {message.from_user.first_name}")49 await message.answer(f"Welcome to the weather app, {message.from_user.username}!\nPlease, set your location and alert time", reply_markup=keyboard)50 await Settings.show_menu_settings.set()51 @dp.message_handler(state=Settings.show_menu_settings)52 async def settings_menu(message:types.Message, state: FSMContext): 53 async with state.proxy():54 if message.text == "Geolocation":55 await Settings.set_location.set()56 await message.answer(f"Please, send your location:", reply_markup=ReplyKeyboardRemove())57 elif message.text == "Time":58 await message.answer("Does not support")59 @dp.message_handler(state=Settings.set_location, content_types=types.ContentType.LOCATION)60 async def send_location(message: types.Message):61 if message.location:62 await message.answer(f'Your location is: {message.location}')63 await Settings.show_menu_settings.set()64 else:65 await message.answer(f"Please, send your location:")66 @dp.message_handler(commands=["settings"])67 async def settings(message: types.Message):68 """69 This handler allows you to change user preferences70 """71 keyboard = ReplyKeyboardMarkup(resize_keyboard=True)72 geo_button = KeyboardButton(text='Geolocation')73 alert_time = KeyboardButton(text='Time')74 buttons = [geo_button, alert_time]75 keyboard.add(*buttons)76 await message.answer("Settings are updated")77 ...

Full Screen

Full Screen

Node.py

Source:Node.py Github

copy

Full Screen

1from graph.GeoLocation import GeoLocation2class Node(object):3 """4 This class represent a vertex in a graph.5 """6 def __init__(self, pos: GeoLocation = None, key: int = None):7 """8 a constructor for the Node class.9 :param pos: GeoLocation of the Node.10 :param key: the ID of the Node11 """12 self.key: int = key13 self.pos: GeoLocation = pos14 self.tag: int = 015 self.edges_in = {}16 self.edges_out = {}17 self.weight: float = 0.018 self.info: str = ""19 @classmethod20 def from_dict(cls, data: dict) -> 'Node':21 """22 this method creates a Node from a dictionary.23 :param data: Data dict24 :return: Node25 """26 # check for None values and raise exception27 # if 'id' not in data or 'key' not in data:28 # raise ValueError("Cant create a Node without id and data")29 key: int = data.get('id') # initialize the node ID30 # initialize the node location31 pos = data.get('pos')32 if pos is not None:33 pos = GeoLocation(*pos.split(',')) # create new GeoLocation34 node: Node = Node(pos, key)35 return node36 def to_dict(self) -> dict:37 """38 this method return a dict representing the Node39 :return: dict with the Node values40 """41 dic = {42 'pos': self.pos.__repr__(),43 'id': self.key44 }45 return dic46 def get_geoLocation(self) -> GeoLocation:47 """48 return the position of the Node49 :return: GeoLocation object50 """51 return self.pos52 def set_geoLocation(self, geo: GeoLocation):53 """54 set the position of the Node to a new position55 :param geo: GeoLocation object56 """57 if not isinstance(geo, GeoLocation):58 raise ValueError("should be GeoLocation type")59 self.pos = geo60 def get_key(self) -> int:61 return self.key62 def get_pos(self) -> GeoLocation:63 return self.pos64 def set_tag(self, tag: int):65 self.tag = tag66 def get_tag(self):67 return self.tag68 def __repr__(self):...

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