How to use is_firefox method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

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

mach_bootstrap.py

Source: mach_bootstrap.py Github

copy
1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this
3# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5from __future__ import print_function, unicode_literals
6
7import os
8import platform
9import sys
10from distutils.spawn import find_executable
11from subprocess import PIPE, Popen
12
13SEARCH_PATHS = [
14    os.path.join("python", "tidy"),
15]
16
17# Individual files providing mach commands.
18MACH_MODULES = [
19    os.path.join('python', 'servo', 'bootstrap_commands.py'),
20    os.path.join('python', 'servo', 'build_commands.py'),
21    os.path.join('python', 'servo', 'testing_commands.py'),
22    os.path.join('python', 'servo', 'post_build_commands.py'),
23    os.path.join('python', 'servo', 'package_commands.py'),
24    os.path.join('python', 'servo', 'devenv_commands.py'),
25]
26
27CATEGORIES = {
28    'bootstrap': {
29        'short': 'Bootstrap Commands',
30        'long': 'Bootstrap the build system',
31        'priority': 90,
32    },
33    'build': {
34        'short': 'Build Commands',
35        'long': 'Interact with the build system',
36        'priority': 80,
37    },
38    'post-build': {
39        'short': 'Post-build Commands',
40        'long': 'Common actions performed after completing a build.',
41        'priority': 70,
42    },
43    'testing': {
44        'short': 'Testing',
45        'long': 'Run tests.',
46        'priority': 60,
47    },
48    'devenv': {
49        'short': 'Development Environment',
50        'long': 'Set up and configure your development environment.',
51        'priority': 50,
52    },
53    'build-dev': {
54        'short': 'Low-level Build System Interaction',
55        'long': 'Interact with specific parts of the build system.',
56        'priority': 20,
57    },
58    'package': {
59        'short': 'Package',
60        'long': 'Create objects to distribute',
61        'priority': 15,
62    },
63    'misc': {
64        'short': 'Potpourri',
65        'long': 'Potent potables and assorted snacks.',
66        'priority': 10,
67    },
68    'disabled': {
69        'short': 'Disabled',
70        'long': 'The disabled commands are hidden by default. Use -v to display them. These commands are unavailable '
71                'for your current context, run "mach <command>" to see why.',
72        'priority': 0,
73    }
74}
75
76# Possible names of executables
77# NOTE: Windows Python doesn't provide versioned executables, so we must use
78# the plain names. On MSYS, we still use Windows Python.
79if sys.platform in ['msys', 'win32']:
80    PYTHON_NAMES = ["python"]
81    VIRTUALENV_NAMES = ["virtualenv"]
82    PIP_NAMES = ["pip"]
83else:
84    PYTHON_NAMES = ["python-2.7", "python2.7", "python2", "python"]
85    VIRTUALENV_NAMES = ["virtualenv-2.7", "virtualenv2.7", "virtualenv2", "virtualenv"]
86    PIP_NAMES = ["pip-2.7", "pip2.7", "pip2", "pip"]
87
88
89def _get_exec_path(names, is_valid_path=lambda _path: True):
90    for name in names:
91        path = find_executable(name)
92        if path and is_valid_path(path):
93            return path
94    return None
95
96
97def _get_virtualenv_script_dir():
98    # Virtualenv calls its scripts folder "bin" on linux/OSX/MSYS64 but "Scripts" on Windows
99    if os.name == "nt" and os.sep != "/":
100        return "Scripts"
101    return "bin"
102
103
104def wpt_path(is_firefox, topdir, *paths):
105    if is_firefox:
106        rel = os.path.join("..", "testing", "web-platform")
107    else:
108        rel = os.path.join("tests", "wpt")
109
110    return os.path.join(topdir, rel, *paths)
111
112
113def wpt_harness_path(is_firefox, topdir, *paths):
114    wpt_root = wpt_path(is_firefox, topdir)
115    if is_firefox:
116        rel = os.path.join(wpt_root, "tests", "tools", "wptrunner")
117    else:
118        rel = os.path.join(wpt_root, "harness")
119
120    return os.path.join(topdir, rel, *paths)
121
122
123def _activate_virtualenv(topdir, is_firefox):
124    virtualenv_path = os.path.join(topdir, "python", "_virtualenv")
125    check_exec_path = lambda path: path.startswith(virtualenv_path)
126    python = _get_exec_path(PYTHON_NAMES)   # If there was no python, mach wouldn't have run at all!
127    if not python:
128        sys.exit('Failed to find python executable for starting virtualenv.')
129
130    script_dir = _get_virtualenv_script_dir()
131    activate_path = os.path.join(virtualenv_path, script_dir, "activate_this.py")
132    need_pip_upgrade = False
133    if not (os.path.exists(virtualenv_path) and os.path.exists(activate_path)):
134        virtualenv = _get_exec_path(VIRTUALENV_NAMES)
135        if not virtualenv:
136            sys.exit("Python virtualenv is not installed. Please install it prior to running mach.")
137
138        process = Popen(
139            [virtualenv, "-p", python, "--system-site-packages", virtualenv_path],
140            stdout=PIPE,
141            stderr=PIPE
142        )
143        process.wait()
144        if process.returncode:
145            out, err = process.communicate()
146            print('Python virtualenv failed to execute properly:')
147            sys.exit('Output: %s\nError: %s' % (out, err))
148        # We want to upgrade pip when virtualenv created for the first time
149        need_pip_upgrade = True
150
151    execfile(activate_path, dict(__file__=activate_path))
152
153    python = _get_exec_path(PYTHON_NAMES, is_valid_path=check_exec_path)
154    if not python:
155        sys.exit("Python executable in virtualenv failed to activate.")
156
157    # TODO: Right now, we iteratively install all the requirements by invoking
158    # `pip install` each time. If it were the case that there were conflicting
159    # requirements, we wouldn't know about them. Once
160    # https://github.com/pypa/pip/issues/988 is addressed, then we can just
161    # chain each of the requirements files into the same `pip install` call
162    # and it will check for conflicts.
163    requirements_paths = [
164        os.path.join("python", "requirements.txt"),
165        wpt_harness_path(is_firefox, topdir, "requirements.txt",),
166        wpt_harness_path(is_firefox, topdir, "requirements_firefox.txt"),
167        wpt_harness_path(is_firefox, topdir, "requirements_servo.txt"),
168    ]
169
170    if need_pip_upgrade:
171        # Upgrade pip when virtualenv is created to fix the issue
172        # https://github.com/servo/servo/issues/11074
173        pip = _get_exec_path(PIP_NAMES, is_valid_path=check_exec_path)
174        if not pip:
175            sys.exit("Python pip is either not installed or not found in virtualenv.")
176
177        process = Popen([pip, "install", "-q", "-I", "-U", "pip"], stdout=PIPE, stderr=PIPE)
178        process.wait()
179        if process.returncode:
180            out, err = process.communicate()
181            print('Pip failed to upgrade itself properly:')
182            sys.exit('Output: %s\nError: %s' % (out, err))
183
184    for req_rel_path in requirements_paths:
185        req_path = os.path.join(topdir, req_rel_path)
186        marker_file = req_rel_path.replace(os.path.sep, '-')
187        marker_path = os.path.join(virtualenv_path, marker_file)
188
189        try:
190            if os.path.getmtime(req_path) + 10 < os.path.getmtime(marker_path):
191                continue
192        except OSError:
193            pass
194
195        pip = _get_exec_path(PIP_NAMES, is_valid_path=check_exec_path)
196        if not pip:
197            sys.exit("Python pip is either not installed or not found in virtualenv.")
198
199        process = Popen([pip, "install", "-q", "-I", "-r", req_path], stdout=PIPE, stderr=PIPE)
200        process.wait()
201        if process.returncode:
202            out, err = process.communicate()
203            print('Pip failed to execute properly:')
204            sys.exit('Output: %s\nError: %s' % (out, err))
205
206        open(marker_path, 'w').close()
207
208
209def _ensure_case_insensitive_if_windows():
210    # The folder is called 'python'. By deliberately checking for it with the wrong case, we determine if the file
211    # system is case sensitive or not.
212    if _is_windows() and not os.path.exists('Python'):
213        print('Cannot run mach in a path on a case-sensitive file system on Windows.')
214        print('For more details, see https://github.com/pypa/virtualenv/issues/935')
215        sys.exit(1)
216
217
218def _is_windows():
219    return sys.platform == 'win32'
220
221
222def bootstrap(topdir):
223    _ensure_case_insensitive_if_windows()
224
225    topdir = os.path.abspath(topdir)
226
227    # We don't support paths with Unicode characters for now
228    # https://github.com/servo/servo/issues/10002
229    try:
230        topdir.decode('ascii')
231    except UnicodeDecodeError:
232        print('Cannot run mach in a path with Unicode characters.')
233        print('Current path:', topdir)
234        sys.exit(1)
235
236    # We don't support paths with spaces for now
237    # https://github.com/servo/servo/issues/9442
238    if ' ' in topdir:
239        print('Cannot run mach in a path with spaces.')
240        print('Current path:', topdir)
241        sys.exit(1)
242
243    # Ensure we are running Python 2.7+. We put this check here so we generate a
244    # user-friendly error message rather than a cryptic stack trace on module import.
245    if not (3, 0) > sys.version_info >= (2, 7):
246        print('Python 2.7 or above (but not Python 3) is required to run mach.')
247        print('You are running Python', platform.python_version())
248        sys.exit(1)
249
250    # See if we're inside a Firefox checkout.
251    parentdir = os.path.normpath(os.path.join(topdir, '..'))
252    is_firefox = os.path.isfile(os.path.join(parentdir,
253                                             'build/mach_bootstrap.py'))
254
255    _activate_virtualenv(topdir, is_firefox)
256
257    def populate_context(context, key=None):
258        if key is None:
259            return
260        if key == 'topdir':
261            return topdir
262        raise AttributeError(key)
263
264    sys.path[0:0] = [os.path.join(topdir, path) for path in SEARCH_PATHS]
265
266    sys.path[0:0] = [wpt_path(is_firefox, topdir),
267                     wpt_harness_path(is_firefox, topdir)]
268
269    import mach.main
270    mach = mach.main.Mach(os.getcwd())
271    mach.populate_context_handler = populate_context
272
273    for category, meta in CATEGORIES.items():
274        mach.define_category(category, meta['short'], meta['long'], meta['priority'])
275
276    for path in MACH_MODULES:
277        mach.load_commands_from_file(os.path.join(topdir, path))
278
279    return mach
280
Full Screen

views.py

Source: views.py Github

copy
1from django.shortcuts import render
2from django.http import HttpResponse
3import json
4from .models import Link, Resource, Person
5import datetime
6from collections import OrderedDict
7import base64
8import hashlib
9
10# Create your views here.
11def serveScript(request):
12	links = Link.objects.all()
13	retVal = {}
14	for l in links:
15		if l.inUse:
16			retVal[l.website] = l.url
17	print(retVal)
18
19
20	return render(request, 'app/sniffScript.js', {'links':retVal}, content_type="application/x-javascript")
21
22def serveCf(request):
23	res = Resource.objects.all()
24	retVal = {}
25	for l in res:
26		if l.inUse:
27			retVal[l.website] = l.url
28	print(retVal)
29
30
31	return render(request, 'app/cf.js', {'res':retVal}, content_type="application/x-javascript")
32
33
34def index(request):
35	is_firefox = False
36	print(request.META['HTTP_USER_AGENT'])
37	if 'Firefox' in request.META['HTTP_USER_AGENT'] or 'firefox' in request.META['HTTP_USER_AGENT']:
38		is_firefox = True
39	return render(request,'app/index.html',{'is_firefox':is_firefox})
40
41def getDates(request):
42	retVal = {}
43	headers_list = json.loads(request.GET["headers"])
44
45	links = Link.objects.all()
46
47
48	secrets = {}
49	ranks = {}
50	vw = {}
51	for l in links:
52		if l.inUse:
53			secrets[l.website] = l.secret
54			ranks[l.website] = l.rank
55			vw[l.website] = l.vw
56	
57	# print('---------')
58	# print(secrets)
59
60
61	for key,val in headers_list.items():
62		retVal[key] = {}
63		if key in secrets:
64			split_headers = headers_list[key].split('\n')
65			split_headers = [i.strip() for i in split_headers]
66			if secrets[key] == 'expires':
67
68				expires = [h for h in split_headers if 'expires' in h ][0].split('expires:')[1].strip()
69				max_age = [h for h in split_headers if 'max-age' in h ][0].split('=')[1]
70				# print(expires)
71				# print(max_age)
72
73				val_date = datetime.datetime.strptime(expires, '%a, %d %b %Y %H:%M:%S GMT') - datetime.timedelta(seconds=int(max_age))
74				retVal[key]['date'] =val_date.strftime('%a, %d %b %Y %H:%M:%S GMT')
75				retVal[key]['rank'] = ranks[key]
76
77				if vw[key] == 'max_age':
78					retVal[key]['vw'] = normalize_seconds(int(max_age))
79
80
81
82
83
84	# ordered_keys = sorted(retVal, key=lambda k: int(retVal[k]['rank']))
85	# ret = {}
86	# for k in ordered_keys:
87	# 	ret[k] = retVal[k]
88
89
90	ret = OrderedDict(sorted(retVal.items(), key=lambda x: int(x[1]['rank'])))
91
92	return HttpResponse(json.dumps(ret), content_type="application/json")
93
94
95def getID(request):
96	print('-------------------------')
97	# print(request)
98	headers_list = json.loads(request.GET["headers"])
99	print(headers_list)
100
101	for key,val in headers_list.items():
102
103		split_headers = headers_list[key].split('\n')
104		split_headers = [i.strip() for i in split_headers]
105	
106
107		expires = [h for h in split_headers if 'expires' in h ][0].split('expires:')[1].strip()
108		max_age = [h for h in split_headers if 'max-age' in h ][0].split('=')[1]
109
110		to_encode = expires + max_age
111		print('to_encode: %s' %to_encode)			
112
113	
114	hash = hashlib.sha1(to_encode.encode("UTF-8")).hexdigest()
115	# print(hash)
116
117	p,created = Person.objects.get_or_create(hash=hash)
118	print('ID: %s' %p.id)
119	print('------------------------')
120
121
122
123	return HttpResponse(json.dumps(p.id), content_type="application/json")
124
125
126
127def normalize_seconds(seconds: int) -> tuple:
128    (days, remainder) = divmod(seconds, 86400)
129    (hours, remainder) = divmod(remainder, 3600)
130    (minutes, seconds) = divmod(remainder, 60)
131    # print(days, hours, minutes, seconds)
132    out = ''
133    if days:
134    	out += str(days) + ' days, '
135    if hours:
136    	out += str(hours) + ' hours, '
137    if minutes:
138    	out += str(minutes) + ' minutes, '
139    if seconds:
140    	out += str(seconds) + ' seconds'
141
142    return out.rstrip().rstrip(',')
143
144def track(request):
145	is_firefox = False
146	print(request.META['HTTP_USER_AGENT'])
147	if 'Firefox' in request.META['HTTP_USER_AGENT'] or 'firefox' in request.META['HTTP_USER_AGENT']:
148		is_firefox = True
149	return render(request,'app/track.html',{'is_firefox':is_firefox})
150
151def sniff(request):
152	is_firefox = False
153	print(request.META['HTTP_USER_AGENT'])
154	if 'Firefox' in request.META['HTTP_USER_AGENT'] or 'firefox' in request.META['HTTP_USER_AGENT']:
155		is_firefox = True
156	return render(request, 'app/sniff.html',{'is_firefox':is_firefox})
157
158
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)