Best Python code snippet using playwright-python
mach_bootstrap.py
Source:mach_bootstrap.py
1# This Source Code Form is subject to the terms of the Mozilla Public2# License, v. 2.0. If a copy of the MPL was not distributed with this3# file, You can obtain one at http://mozilla.org/MPL/2.0/.4from __future__ import print_function, unicode_literals5import os6import platform7import sys8from distutils.spawn import find_executable9from subprocess import PIPE, Popen10SEARCH_PATHS = [11 os.path.join("python", "tidy"),12]13# Individual files providing mach commands.14MACH_MODULES = [15 os.path.join('python', 'servo', 'bootstrap_commands.py'),16 os.path.join('python', 'servo', 'build_commands.py'),17 os.path.join('python', 'servo', 'testing_commands.py'),18 os.path.join('python', 'servo', 'post_build_commands.py'),19 os.path.join('python', 'servo', 'package_commands.py'),20 os.path.join('python', 'servo', 'devenv_commands.py'),21]22CATEGORIES = {23 'bootstrap': {24 'short': 'Bootstrap Commands',25 'long': 'Bootstrap the build system',26 'priority': 90,27 },28 'build': {29 'short': 'Build Commands',30 'long': 'Interact with the build system',31 'priority': 80,32 },33 'post-build': {34 'short': 'Post-build Commands',35 'long': 'Common actions performed after completing a build.',36 'priority': 70,37 },38 'testing': {39 'short': 'Testing',40 'long': 'Run tests.',41 'priority': 60,42 },43 'devenv': {44 'short': 'Development Environment',45 'long': 'Set up and configure your development environment.',46 'priority': 50,47 },48 'build-dev': {49 'short': 'Low-level Build System Interaction',50 'long': 'Interact with specific parts of the build system.',51 'priority': 20,52 },53 'package': {54 'short': 'Package',55 'long': 'Create objects to distribute',56 'priority': 15,57 },58 'misc': {59 'short': 'Potpourri',60 'long': 'Potent potables and assorted snacks.',61 'priority': 10,62 },63 'disabled': {64 'short': 'Disabled',65 'long': 'The disabled commands are hidden by default. Use -v to display them. These commands are unavailable '66 'for your current context, run "mach <command>" to see why.',67 'priority': 0,68 }69}70# Possible names of executables71# NOTE: Windows Python doesn't provide versioned executables, so we must use72# the plain names. On MSYS, we still use Windows Python.73if sys.platform in ['msys', 'win32']:74 PYTHON_NAMES = ["python"]75 VIRTUALENV_NAMES = ["virtualenv"]76 PIP_NAMES = ["pip"]77else:78 PYTHON_NAMES = ["python-2.7", "python2.7", "python2", "python"]79 VIRTUALENV_NAMES = ["virtualenv-2.7", "virtualenv2.7", "virtualenv2", "virtualenv"]80 PIP_NAMES = ["pip-2.7", "pip2.7", "pip2", "pip"]81def _get_exec_path(names, is_valid_path=lambda _path: True):82 for name in names:83 path = find_executable(name)84 if path and is_valid_path(path):85 return path86 return None87def _get_virtualenv_script_dir():88 # Virtualenv calls its scripts folder "bin" on linux/OSX/MSYS64 but "Scripts" on Windows89 if os.name == "nt" and os.sep != "/":90 return "Scripts"91 return "bin"92def wpt_path(is_firefox, topdir, *paths):93 if is_firefox:94 rel = os.path.join("..", "testing", "web-platform")95 else:96 rel = os.path.join("tests", "wpt")97 return os.path.join(topdir, rel, *paths)98def wpt_harness_path(is_firefox, topdir, *paths):99 wpt_root = wpt_path(is_firefox, topdir)100 if is_firefox:101 rel = os.path.join(wpt_root, "tests", "tools", "wptrunner")102 else:103 rel = os.path.join(wpt_root, "harness")104 return os.path.join(topdir, rel, *paths)105def _activate_virtualenv(topdir, is_firefox):106 virtualenv_path = os.path.join(topdir, "python", "_virtualenv")107 check_exec_path = lambda path: path.startswith(virtualenv_path)108 python = _get_exec_path(PYTHON_NAMES) # If there was no python, mach wouldn't have run at all!109 if not python:110 sys.exit('Failed to find python executable for starting virtualenv.')111 script_dir = _get_virtualenv_script_dir()112 activate_path = os.path.join(virtualenv_path, script_dir, "activate_this.py")113 need_pip_upgrade = False114 if not (os.path.exists(virtualenv_path) and os.path.exists(activate_path)):115 virtualenv = _get_exec_path(VIRTUALENV_NAMES)116 if not virtualenv:117 sys.exit("Python virtualenv is not installed. Please install it prior to running mach.")118 process = Popen(119 [virtualenv, "-p", python, "--system-site-packages", virtualenv_path],120 stdout=PIPE,121 stderr=PIPE122 )123 process.wait()124 if process.returncode:125 out, err = process.communicate()126 print('Python virtualenv failed to execute properly:')127 sys.exit('Output: %s\nError: %s' % (out, err))128 # We want to upgrade pip when virtualenv created for the first time129 need_pip_upgrade = True130 execfile(activate_path, dict(__file__=activate_path))131 python = _get_exec_path(PYTHON_NAMES, is_valid_path=check_exec_path)132 if not python:133 sys.exit("Python executable in virtualenv failed to activate.")134 # TODO: Right now, we iteratively install all the requirements by invoking135 # `pip install` each time. If it were the case that there were conflicting136 # requirements, we wouldn't know about them. Once137 # https://github.com/pypa/pip/issues/988 is addressed, then we can just138 # chain each of the requirements files into the same `pip install` call139 # and it will check for conflicts.140 requirements_paths = [141 os.path.join("python", "requirements.txt"),142 wpt_harness_path(is_firefox, topdir, "requirements.txt",),143 wpt_harness_path(is_firefox, topdir, "requirements_firefox.txt"),144 wpt_harness_path(is_firefox, topdir, "requirements_servo.txt"),145 ]146 if need_pip_upgrade:147 # Upgrade pip when virtualenv is created to fix the issue148 # https://github.com/servo/servo/issues/11074149 pip = _get_exec_path(PIP_NAMES, is_valid_path=check_exec_path)150 if not pip:151 sys.exit("Python pip is either not installed or not found in virtualenv.")152 process = Popen([pip, "install", "-q", "-I", "-U", "pip"], stdout=PIPE, stderr=PIPE)153 process.wait()154 if process.returncode:155 out, err = process.communicate()156 print('Pip failed to upgrade itself properly:')157 sys.exit('Output: %s\nError: %s' % (out, err))158 for req_rel_path in requirements_paths:159 req_path = os.path.join(topdir, req_rel_path)160 marker_file = req_rel_path.replace(os.path.sep, '-')161 marker_path = os.path.join(virtualenv_path, marker_file)162 try:163 if os.path.getmtime(req_path) + 10 < os.path.getmtime(marker_path):164 continue165 except OSError:166 pass167 pip = _get_exec_path(PIP_NAMES, is_valid_path=check_exec_path)168 if not pip:169 sys.exit("Python pip is either not installed or not found in virtualenv.")170 process = Popen([pip, "install", "-q", "-I", "-r", req_path], stdout=PIPE, stderr=PIPE)171 process.wait()172 if process.returncode:173 out, err = process.communicate()174 print('Pip failed to execute properly:')175 sys.exit('Output: %s\nError: %s' % (out, err))176 open(marker_path, 'w').close()177def _ensure_case_insensitive_if_windows():178 # The folder is called 'python'. By deliberately checking for it with the wrong case, we determine if the file179 # system is case sensitive or not.180 if _is_windows() and not os.path.exists('Python'):181 print('Cannot run mach in a path on a case-sensitive file system on Windows.')182 print('For more details, see https://github.com/pypa/virtualenv/issues/935')183 sys.exit(1)184def _is_windows():185 return sys.platform == 'win32'186def bootstrap(topdir):187 _ensure_case_insensitive_if_windows()188 topdir = os.path.abspath(topdir)189 # We don't support paths with Unicode characters for now190 # https://github.com/servo/servo/issues/10002191 try:192 topdir.decode('ascii')193 except UnicodeDecodeError:194 print('Cannot run mach in a path with Unicode characters.')195 print('Current path:', topdir)196 sys.exit(1)197 # We don't support paths with spaces for now198 # https://github.com/servo/servo/issues/9442199 if ' ' in topdir:200 print('Cannot run mach in a path with spaces.')201 print('Current path:', topdir)202 sys.exit(1)203 # Ensure we are running Python 2.7+. We put this check here so we generate a204 # user-friendly error message rather than a cryptic stack trace on module import.205 if not (3, 0) > sys.version_info >= (2, 7):206 print('Python 2.7 or above (but not Python 3) is required to run mach.')207 print('You are running Python', platform.python_version())208 sys.exit(1)209 # See if we're inside a Firefox checkout.210 parentdir = os.path.normpath(os.path.join(topdir, '..'))211 is_firefox = os.path.isfile(os.path.join(parentdir,212 'build/mach_bootstrap.py'))213 _activate_virtualenv(topdir, is_firefox)214 def populate_context(context, key=None):215 if key is None:216 return217 if key == 'topdir':218 return topdir219 raise AttributeError(key)220 sys.path[0:0] = [os.path.join(topdir, path) for path in SEARCH_PATHS]221 sys.path[0:0] = [wpt_path(is_firefox, topdir),222 wpt_harness_path(is_firefox, topdir)]223 import mach.main224 mach = mach.main.Mach(os.getcwd())225 mach.populate_context_handler = populate_context226 for category, meta in CATEGORIES.items():227 mach.define_category(category, meta['short'], meta['long'], meta['priority'])228 for path in MACH_MODULES:229 mach.load_commands_from_file(os.path.join(topdir, path))...
views.py
Source:views.py
1from django.shortcuts import render2from django.http import HttpResponse3import json4from .models import Link, Resource, Person5import datetime6from collections import OrderedDict7import base648import hashlib9# Create your views here.10def serveScript(request):11 links = Link.objects.all()12 retVal = {}13 for l in links:14 if l.inUse:15 retVal[l.website] = l.url16 print(retVal)17 return render(request, 'app/sniffScript.js', {'links':retVal}, content_type="application/x-javascript")18def serveCf(request):19 res = Resource.objects.all()20 retVal = {}21 for l in res:22 if l.inUse:23 retVal[l.website] = l.url24 print(retVal)25 return render(request, 'app/cf.js', {'res':retVal}, content_type="application/x-javascript")26def index(request):27 is_firefox = False28 print(request.META['HTTP_USER_AGENT'])29 if 'Firefox' in request.META['HTTP_USER_AGENT'] or 'firefox' in request.META['HTTP_USER_AGENT']:30 is_firefox = True31 return render(request,'app/index.html',{'is_firefox':is_firefox})32def getDates(request):33 retVal = {}34 headers_list = json.loads(request.GET["headers"])35 links = Link.objects.all()36 secrets = {}37 ranks = {}38 vw = {}39 for l in links:40 if l.inUse:41 secrets[l.website] = l.secret42 ranks[l.website] = l.rank43 vw[l.website] = l.vw44 45 # print('---------')46 # print(secrets)47 for key,val in headers_list.items():48 retVal[key] = {}49 if key in secrets:50 split_headers = headers_list[key].split('\n')51 split_headers = [i.strip() for i in split_headers]52 if secrets[key] == 'expires':53 expires = [h for h in split_headers if 'expires' in h ][0].split('expires:')[1].strip()54 max_age = [h for h in split_headers if 'max-age' in h ][0].split('=')[1]55 # print(expires)56 # print(max_age)57 val_date = datetime.datetime.strptime(expires, '%a, %d %b %Y %H:%M:%S GMT') - datetime.timedelta(seconds=int(max_age))58 retVal[key]['date'] =val_date.strftime('%a, %d %b %Y %H:%M:%S GMT')59 retVal[key]['rank'] = ranks[key]60 if vw[key] == 'max_age':61 retVal[key]['vw'] = normalize_seconds(int(max_age))62 # ordered_keys = sorted(retVal, key=lambda k: int(retVal[k]['rank']))63 # ret = {}64 # for k in ordered_keys:65 # ret[k] = retVal[k]66 ret = OrderedDict(sorted(retVal.items(), key=lambda x: int(x[1]['rank'])))67 return HttpResponse(json.dumps(ret), content_type="application/json")68def getID(request):69 print('-------------------------')70 # print(request)71 headers_list = json.loads(request.GET["headers"])72 print(headers_list)73 for key,val in headers_list.items():74 split_headers = headers_list[key].split('\n')75 split_headers = [i.strip() for i in split_headers]76 77 expires = [h for h in split_headers if 'expires' in h ][0].split('expires:')[1].strip()78 max_age = [h for h in split_headers if 'max-age' in h ][0].split('=')[1]79 to_encode = expires + max_age80 print('to_encode: %s' %to_encode) 81 82 hash = hashlib.sha1(to_encode.encode("UTF-8")).hexdigest()83 # print(hash)84 p,created = Person.objects.get_or_create(hash=hash)85 print('ID: %s' %p.id)86 print('------------------------')87 return HttpResponse(json.dumps(p.id), content_type="application/json")88def normalize_seconds(seconds: int) -> tuple:89 (days, remainder) = divmod(seconds, 86400)90 (hours, remainder) = divmod(remainder, 3600)91 (minutes, seconds) = divmod(remainder, 60)92 # print(days, hours, minutes, seconds)93 out = ''94 if days:95 out += str(days) + ' days, '96 if hours:97 out += str(hours) + ' hours, '98 if minutes:99 out += str(minutes) + ' minutes, '100 if seconds:101 out += str(seconds) + ' seconds'102 return out.rstrip().rstrip(',')103def track(request):104 is_firefox = False105 print(request.META['HTTP_USER_AGENT'])106 if 'Firefox' in request.META['HTTP_USER_AGENT'] or 'firefox' in request.META['HTTP_USER_AGENT']:107 is_firefox = True108 return render(request,'app/track.html',{'is_firefox':is_firefox})109def sniff(request):110 is_firefox = False111 print(request.META['HTTP_USER_AGENT'])112 if 'Firefox' in request.META['HTTP_USER_AGENT'] or 'firefox' in request.META['HTTP_USER_AGENT']:113 is_firefox = True...
verify_env.py
Source:verify_env.py
1import sys2import os3import subprocess4from pathlib import Path5from pip._internal.utils.misc import get_installed_distributions6SETUP_DIRECTORY = Path(__file__).resolve().parent7IS_CHROME = False8IS_FIREFOX = False9SMOKE_TEST_SUITE = os.path.join(SETUP_DIRECTORY, "verify_setup.robot")10def get_pip_packages():11 pip_packages = []12 packages = get_installed_distributions()13 for package in packages:14 pip_packages.append(package.project_name)15 return pip_packages16def check_robot_framework_package():17 pip_packages = get_pip_packages()18 if not "robotframework" in pip_packages:19 print("Install Robot Framework: pip install robotframework")20 sys.exit(1)21def check_selenium_library_package():22 pip_packages = get_pip_packages()23 if not "robotframework-seleniumlibrary" in pip_packages:24 print("Install SeleniumLibrary: pip install robotframework-seleniumlibrary")25 sys.exit(1)26def check_rflint_package():27 pip_packages = get_pip_packages()28 if not "robotframework-lint" in pip_packages:29 print("Install Robot Framework linter: pip install robotframework-lint")30 print("Linter tool is required for exercise verification")31 sys.exit(1)32def check_smoke_suite_location():33 if not os.path.isfile(SMOKE_TEST_SUITE):34 print("File not located, please run from root folder of the exercises")35 print(SMOKE_TEST_SUITE)36 sys.exit(1)37def evaluate_environment():38 try:39 subprocess.run(["robot", "-v", "BROWSER:ff", "-d", str(SETUP_DIRECTORY), SMOKE_TEST_SUITE], check=True)40 IS_FIREFOX = True41 except subprocess.CalledProcessError:42 IS_FIREFOX = False43 try:44 subprocess.run(["robot", "-v", "BROWSER:gc", "-d", str(SETUP_DIRECTORY), SMOKE_TEST_SUITE], check=True)45 IS_CHROME = True46 except subprocess.CalledProcessError:47 IS_CHROME = False48 if not IS_CHROME and not IS_FIREFOX:49 print("Setup webdriver based on the instructions for Firefox OR Chrome")50 sys.exit(1)51def main():52 check_robot_framework_package()53 check_selenium_library_package()54 check_rflint_package()55 check_smoke_suite_location()56 evaluate_environment()57 print("Setup in perfect condition!")58if __name__ == "__main__":...
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!!