How to use _build_wheels 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.

build.py

Source: build.py Github

copy
1import shutil
2import os
3
4from pjmlib.pathutils import Path
5from pjmlib.dept.opd.buildutils import increment_version, push_to_nexus
6
7app_name = 'pjmlib'
8
9class PjmlibBuilder(AbstractBuilder):
10    def __init__(self):
11        super.__init__()
12
13
14class AbstractBuilder(object):
15    def __init__(self):
16        self.topdir = Path(__file__).parent.absolute()
17        self.version = '0.0.1'
18
19    def run_full_build_cycle(self, run_test=True):
20        self._increment_version()
21        self._cleanup_last_build()
22        self._create_build_copies()
23        self._transpile_py2()
24        if run_test:
25            self._run_unit_tests_py2(True)
26        self._build_wheels()
27        self._upload_to_nexus()
28
29    def run_py2_tests(self, run_slow_tests=False):
30        self._cleanup_last_build()
31        self._create_build_copies()
32        self._transpile_py2()
33        self._run_unit_tests_py2(run_slow_tests)
34
35
36    def _increment_version(self):
37        # Increment the version number
38        self.version = increment_version(r"{}\__init__.py".format(app_name), app_name, format='increment')
39
40    def _cleanup_last_build(self):
41        # Cleanup last build
42        if (self.topdir / 'dist').is_dir():
43            shutil.rmtree(self.topdir / 'dist')
44        if(self.topdir / 'build').is_dir():
45            shutil.rmtree(self.topdir / 'build')
46
47    def _create_build_copies(self):
48        # Copy existing code into python 3 and 2 folders
49        (self.topdir / 'build').mkdir()
50        (self.topdir / 'build' / 'py3').mkdir()
51        (self.topdir / 'build' / 'py2').mkdir()
52        self._copy_to_build(self.topdir / 'build' / 'py2', py2=True)
53        self._copy_to_build(self.topdir / 'build' / 'py3', py2=False)
54
55    def _copy_to_build(self, output_dir: Path, py2=False):
56        for root, dirs, files in os.walk(self.topdir.str):
57            if 'build' in root:
58                continue
59            if '.git' in root:
60                continue
61            if '.idea' in root:
62                continue
63            if '__pycache__' in root:
64                continue
65            ext_dir = output_dir / Path(root).relative_to(self.topdir)
66            if not ext_dir.is_dir():
67                ext_dir.mkdir()
68            for fn in files:
69                if not (fn.endswith(".py") or fn.endswith(".txt")):
70                    continue
71                fp = Path(root) / fn
72                ext = fp.relative_to(self.topdir)
73
74                if fn.endswith(".py2.py"):
75                    # Overwite the py3 version with py2
76                    py3fn = output_dir / ext.str.replace(".py2.py", ".py")
77                    assert py3fn.is_file(), f"Missing: {py3fn}"
78
79                    if py2:
80                        shutil.copy(fp, os.path.join(output_dir, ext.str.replace(".py2.py", ".py")))
81                    else:
82                        pass # noop: skip file
83                else:
84                    shutil.copy(fp, os.path.join(output_dir, ext.str))
85
86
87    def _transpile_py2(self):
88        # Run 3to6 on py2 folder
89        from lib3to6.common import  BuildContext, BuildConfig, CheckError
90        from lib3to6.transpile import transpile_module_data
91
92        cfg = BuildConfig(target_version='2.7',
93                          cache_enabled=False,
94                          default_mode='enabled',
95                          fixers=['AnnotationsFutureFixer', 'GeneratorStopFutureFixer',
96                                    'UnicodeLiteralsFutureFixer', 'RemoveUnsupportedFuturesFixer',
97                                    'PrintFunctionFutureFixer', 'WithStatementFutureFixer',
98                                    'AbsoluteImportFutureFixer', 'DivisionFutureFixer',
99                                    'GeneratorsFutureFixer', 'NestedScopesFutureFixer',
100                                    'XrangeToRangeFixer',
101                                    'UnicodeToStrFixer', 'UnichrToChrFixer', 'RawInputToInputFixer',
102                                    'RemoveFunctionDefAnnotationsFixer', 'ForwardReferenceAnnotationsFixer',
103                                    'RemoveAnnAssignFixer', 'ShortToLongFormSuperFixer',
104                                    'InlineKWOnlyArgsFixer', 'NewStyleClassesFixer',
105                                    'UnpackingGeneralizationsFixer',
106                                    'NamedTupleClassToAssignFixer', 'FStringToStrFormatFixer',
107                                    'UnpackingGeneralizationsFixer'],
108                          checkers=['NoAsyncAwait', 'NoComplexNamedTuple',
109                                    'NoYieldFromChecker', 'NoMatMultOpChecker'],
110                          install_requires=None)
111        for filepath in (self.topdir / 'build' / 'py2' / 'pjmlib').walk_files():
112            if filepath.suffix != '.py':
113                continue
114            with open(filepath, mode='rb') as fobj:
115                module_source_data = fobj.read()
116
117            ctx = BuildContext(cfg, str(filepath))
118            try:
119                fixed_module_source_data = transpile_module_data(ctx,
120                                                                 module_source_data)
121            except CheckError as err:
122                loc = str(filepath)
123                if err.lineno >= 0:
124                    loc += '@' + str(err.lineno)
125                err.args = (loc + ' - ' + err.args[0],) + err.args[1:]
126                raise
127            with open(filepath, mode='wb') as fobj:
128                fobj.write(fixed_module_source_data)
129
130    def _run_unit_tests_py2(self, run_slow_tests):
131        (self.topdir / 'build' / 'py2').chdir()
132        os.environ['SLOW_TESTS'] = 'yes' if run_slow_tests else 'no'
133        # os.system(r"C:\Personal\projects\venvs\venv_pjmlib_py27\Scripts\python.exe -m pjmlib.test_pjmlib")
134        os.system(r"C:\Python27\python.exe -m unittest discover "
135                  rf"-s {self.topdir / 'pjmlib' / 'tests'}"
136                  rf"-t {self.topdir / 'pjmlib' / 'tests'}")
137
138        print('-' * 80)
139        print("Did the tests pass?")
140        input(">>>")
141
142    def _build_wheels(self):
143        if self.version is None:
144            from pjmlib import __version__
145            self.version = __version__
146
147        (self.topdir / 'dist').mkdir()
148
149        (self.topdir / 'build' / 'py3').chdir()
150        print("building py3 wheel...")
151        os.system('python.exe setup.py sdist bdist_wheel')
152        shutil.copy(self.topdir / 'build' / 'py3' / 'dist' / f"{app_name}-{self.version}-py3-none-any.whl",
153                    self.topdir / 'dist')
154
155        (self.topdir / 'build' / 'py2').chdir()
156        print("building py2 wheel...")
157        os.system('C:\Python27\python.exe setup.py sdist bdist_wheel')
158        shutil.copy(self.topdir / 'build' / 'py2' / 'dist' / f"{app_name}-{self.version}-py2-none-any.whl",
159                    self.topdir / 'dist')
160
161
162    def _upload_to_nexus(self):
163        (self.topdir / 'dist').chdir()
164        push_to_nexus(r"{}-{}-py2-none-any.whl".format(app_name, self.version))
165        push_to_nexus(r"{}-{}-py3-none-any.whl".format(app_name, self.version))
166
167        (self.topdir / 'build').rmdir()
168
169        print('')
170        print('*'*80)
171        print('* {} version {} has been built and uploaded to nexus.'.format(app_name, self.version))
172        print('*'*80)
173
174        print('')
175        print('Next steps:')
176        print(' 1. Update CHANGELOG.md')
177        print(' 2. Commit to git and push.')
178
179if __name__ == '__main__':
180    builder = PjmlibBuilder()
181    #builder.run_py2_tests(run_slow_tests=True)
182    builder.run_full_build_cycle(run_test=True)
Full Screen

setup.py

Source: setup.py Github

copy
1# Copyright (c) Microsoft Corporation.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import glob
16import os
17import platform
18import shutil
19import subprocess
20import sys
21import zipfile
22from pathlib import Path
23from typing import Dict, List
24
25from setuptools import find_packages, setup
26
27try:
28    from auditwheel.wheeltools import InWheel
29except ImportError:
30    InWheel = None
31from wheel.bdist_wheel import bdist_wheel as BDistWheelCommand
32
33driver_version = "1.21.0"
34
35
36def extractall(zip: zipfile.ZipFile, path: str) -> None:
37    for name in zip.namelist():
38        member = zip.getinfo(name)
39        extracted_path = zip.extract(member, path)
40        attr = member.external_attr >> 16
41        if attr != 0:
42            os.chmod(extracted_path, attr)
43
44
45def download_driver(zip_name: str) -> None:
46    zip_file = f"playwright-{driver_version}-{zip_name}.zip"
47    if os.path.exists("driver/" + zip_file):
48        return
49    url = "https://playwright.azureedge.net/builds/driver/"
50    if (
51        "-alpha" in driver_version
52        or "-beta" in driver_version
53        or "-next" in driver_version
54    ):
55        url = url + "next/"
56    url = url + zip_file
57    print(f"Fetching {url}")
58    # Don't replace this with urllib - Python won't have certificates to do SSL on all platforms.
59    subprocess.check_call(["curl", url, "-o", "driver/" + zip_file])
60
61
62class PlaywrightBDistWheelCommand(BDistWheelCommand):
63    user_options = BDistWheelCommand.user_options + [
64        ("all", "a", "create wheels for all platforms")
65    ]
66    boolean_options = BDistWheelCommand.boolean_options + ["all"]
67
68    def initialize_options(self) -> None:
69        super().initialize_options()
70        self.all = False
71
72    def run(self) -> None:
73        shutil.rmtree("build", ignore_errors=True)
74        shutil.rmtree("dist", ignore_errors=True)
75        shutil.rmtree("playwright.egg-info", ignore_errors=True)
76        super().run()
77        os.makedirs("driver", exist_ok=True)
78        os.makedirs("playwright/driver", exist_ok=True)
79        base_wheel_bundles: List[Dict[str, str]] = [
80            {
81                "wheel": "macosx_10_13_x86_64.whl",
82                "machine": "x86_64",
83                "platform": "darwin",
84                "zip_name": "mac",
85            },
86            {
87                "wheel": "macosx_11_0_universal2.whl",
88                "machine": "x86_64",
89                "platform": "darwin",
90                "zip_name": "mac",
91            },
92            {
93                "wheel": "macosx_11_0_arm64.whl",
94                "machine": "arm64",
95                "platform": "darwin",
96                "zip_name": "mac-arm64",
97            },
98            {
99                "wheel": "manylinux1_x86_64.whl",
100                "machine": "x86_64",
101                "platform": "linux",
102                "zip_name": "linux",
103            },
104            {
105                "wheel": "manylinux_2_17_aarch64.manylinux2014_aarch64.whl",
106                "machine": "aarch64",
107                "platform": "linux",
108                "zip_name": "linux-arm64",
109            },
110            {
111                "wheel": "win32.whl",
112                "machine": "i386",
113                "platform": "win32",
114                "zip_name": "win32_x64",
115            },
116            {
117                "wheel": "win_amd64.whl",
118                "machine": "amd64",
119                "platform": "win32",
120                "zip_name": "win32_x64",
121            },
122        ]
123        self._download_and_extract_local_driver(base_wheel_bundles)
124
125        wheels = base_wheel_bundles
126        if not self.all:
127            # Limit to 1, since for MacOS e.g. we have multiple wheels for the same platform and architecture and Conda expects 1.
128            wheels = list(
129                filter(
130                    lambda wheel: wheel["platform"] == sys.platform
131                    and wheel["machine"] == platform.machine().lower(),
132                    base_wheel_bundles,
133                )
134            )[:1]
135        self._build_wheels(wheels)
136
137    def _build_wheels(
138        self,
139        wheels: List[Dict[str, str]],
140    ) -> None:
141        base_wheel_location: str = glob.glob(os.path.join(self.dist_dir, "*.whl"))[0]
142        without_platform = base_wheel_location[:-7]
143        for wheel_bundle in wheels:
144            download_driver(wheel_bundle["zip_name"])
145            zip_file = (
146                f"driver/playwright-{driver_version}-{wheel_bundle['zip_name']}.zip"
147            )
148            with zipfile.ZipFile(zip_file, "r") as zip:
149                extractall(zip, f"driver/{wheel_bundle['zip_name']}")
150            wheel_location = without_platform + wheel_bundle["wheel"]
151            shutil.copy(base_wheel_location, wheel_location)
152            with zipfile.ZipFile(wheel_location, "a") as zip:
153                driver_root = os.path.abspath(f"driver/{wheel_bundle['zip_name']}")
154                for dir_path, _, files in os.walk(driver_root):
155                    for file in files:
156                        from_path = os.path.join(dir_path, file)
157                        to_path = os.path.relpath(from_path, driver_root)
158                        zip.write(from_path, f"playwright/driver/{to_path}")
159                zip.writestr(
160                    "playwright/driver/README.md",
161                    f"{wheel_bundle['wheel']} driver package",
162                )
163        os.remove(base_wheel_location)
164        if InWheel:
165            for whlfile in glob.glob(os.path.join(self.dist_dir, "*.whl")):
166                os.makedirs("wheelhouse", exist_ok=True)
167                with InWheel(
168                    in_wheel=whlfile,
169                    out_wheel=os.path.join("wheelhouse", os.path.basename(whlfile)),
170                ):
171                    print(f"Updating RECORD file of {whlfile}")
172            shutil.rmtree(self.dist_dir)
173            print("Copying new wheels")
174            shutil.move("wheelhouse", self.dist_dir)
175        else:
176            print("auditwheel not installed, not updating RECORD file")
177
178    def _download_and_extract_local_driver(
179        self,
180        wheels: List[Dict[str, str]],
181    ) -> None:
182        zip_names_for_current_system = set(
183            map(
184                lambda wheel: wheel["zip_name"],
185                filter(
186                    lambda wheel: wheel["machine"] == platform.machine().lower()
187                    and wheel["platform"] == sys.platform,
188                    wheels,
189                ),
190            )
191        )
192        assert len(zip_names_for_current_system) == 1
193        zip_name = zip_names_for_current_system.pop()
194        download_driver(zip_name)
195        zip_file = f"driver/playwright-{driver_version}-{zip_name}.zip"
196        with zipfile.ZipFile(zip_file, "r") as zip:
197            extractall(zip, "playwright/driver")
198
199
200setup(
201    name="playwright",
202    author="Microsoft Corporation",
203    author_email="",
204    description="A high-level API to automate web browsers",
205    long_description=Path("README.md").read_text(encoding="utf-8"),
206    long_description_content_type="text/markdown",
207    url="https://github.com/Microsoft/playwright-python",
208    packages=find_packages(exclude=["tests*"]),
209    include_package_data=True,
210    install_requires=[
211        "websockets==10.1",
212        "greenlet==1.1.2",
213        "pyee==8.1.0",
214        "typing-extensions;python_version<='3.8'",
215    ],
216    classifiers=[
217        "Topic :: Software Development :: Testing",
218        "Topic :: Internet :: WWW/HTTP :: Browsers",
219        "Intended Audience :: Developers",
220        "Programming Language :: Python :: 3",
221        "Programming Language :: Python :: 3.7",
222        "Programming Language :: Python :: 3.8",
223        "Programming Language :: Python :: 3.9",
224        "Programming Language :: Python :: 3.10",
225        "License :: OSI Approved :: Apache Software License",
226        "Operating System :: OS Independent",
227    ],
228    python_requires=">=3.7",
229    cmdclass={"bdist_wheel": PlaywrightBDistWheelCommand},
230    use_scm_version={
231        "version_scheme": "post-release",
232        "write_to": "playwright/_repo_version.py",
233        "write_to_template": 'version = "{version}"\n',
234    },
235    setup_requires=["setuptools-scm==6.3.2", "wheel==0.37.0"],
236    entry_points={
237        "console_scripts": [
238            "playwright=playwright.__main__:main",
239        ],
240        "pyinstaller40": ["hook-dirs=playwright._impl.__pyinstaller:get_hook_dirs"],
241    },
242)
243
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)