diff --git a/.github/workflows/pychecks.yaml b/.github/workflows/pychecks.yaml new file mode 100644 index 0000000..e59f6ab --- /dev/null +++ b/.github/workflows/pychecks.yaml @@ -0,0 +1,41 @@ +name: py checks + +on: + pull_request: + push: + branches: + - main + +permissions: + contents: read + +jobs: + checks: + runs-on: ubuntu-latest + steps: + - name: Checkout working copy + uses: actions/checkout@v4 + - name: ruff check + uses: chartboost/ruff-action@v1 + with: + args: check + - name: ruff format + if: always() + uses: chartboost/ruff-action@v1 + with: + args: format --diff + - name: Set up Python + id: setup_python + if: always() + uses: actions/setup-python@v5 + with: + python-version: "3.x" + - name: Install mypy + id: install_mypy + if: ${{ always() && steps.setup_python.conclusion == 'success' }} + run: | + python -mpip install --upgrade pip + python -mpip install mypy pytest types-PyYaml + - name: mypy + if: ${{ always() && steps.install_mypy.conclusion == 'success' }} + run: mypy --strict . diff --git a/.github/workflows/pyo3-wheels.yml b/.github/workflows/pyo3-wheels.yml new file mode 100644 index 0000000..6262fba --- /dev/null +++ b/.github/workflows/pyo3-wheels.yml @@ -0,0 +1,193 @@ +name: Wheels and Tests + +on: + push: + branches: [ main ] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + wheels: + strategy: + matrix: + python-version: + - "3.x" + - "pypy-3.10" + - "graalpy-24" + arch: + - x86_64 + - aarch64 + platform: + - linux + - musllinux + - windows + - macos + + exclude: + - platform: windows + arch: aarch64 + - platform: windows + python-version: graalpy-24 + + include: + - platform: linux + manylinux: auto + - platform: musllinux + manylinux: musllinux_1_2 + + - args: --release --out dist -m ua-parser-py/Cargo.toml -i python + - platform: linux + args: --release --out dist -m ua-parser-py/Cargo.toml -i python --zig + - platform: musllinux + args: --release --out dist -m ua-parser-py/Cargo.toml + + - runs: ubuntu-latest + - platform: windows + runs: windows-latest + - platform: macos + runs: macos-latest + + runs-on: ${{ matrix.runs }} + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Build wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.arch }} + args: ${{ matrix.args }} + sccache: 'true' + manylinux: ${{ matrix.manylinux }} + - name: Upload wheels + uses: actions/upload-artifact@v4 + with: + name: wheels-${{ matrix.platform }}-${{ matrix.arch }}-${{ matrix.python-version }} + path: dist/* + + sdist: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Build sdist + uses: PyO3/maturin-action@v1 + with: + command: sdist + args: --out dist -m ua-parser-py/Cargo.toml + - name: Upload sdist + uses: actions/upload-artifact@v4 + with: + name: wheels-sdist + path: dist + + # TODO: tags don't work because multiple crates in same repo, so + # needs some other method of picking versions + release: + name: Release + runs-on: ubuntu-latest + if: ${{ github.event_name == 'workflow_dispatch' }} + needs: [wheels, sdist] + permissions: + # Use to sign the release artifacts + id-token: write + # Used to upload release artifacts + contents: write + # Used to generate artifact attestation + attestations: write + steps: + - uses: actions/download-artifact@v4 + - name: Generate artifact attestation + uses: actions/attest-build-provenance@v1 + with: + subject-path: 'wheels-*/*' + - name: Publish to PyPI + uses: PyO3/maturin-action@v1 + env: + MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} + with: + command: upload + args: --non-interactive --skip-existing wheels-*/* + + tests: + needs: wheels + + strategy: + fail-fast: false + matrix: + python-version: + - "3.9" + - "3.10" + - "3.11" + - "3.12" + - "3.13" + - "pypy-3.10" + - "graalpy-24" + platform: + - linux + # probably requires a custom image of some sort + # - musllinux + - windows + - macos + + exclude: + - platform: windows + python-version: graalpy-24 + + include: + # would probably need to run qemu inside the thing to full + # test the archs... + - arch: x86_64 + - platform: macos + arch: aarch64 + + - wheel: "3.x" + - python-version: "pypy-3.10" + wheel: "pypy-3.10" + - python-version: "graalpy-24" + wheel: "graalpy-24" + + - runs: ubuntu-latest + - platform: windows + runs: windows-latest + - platform: macos + runs: macos-latest + + runs-on: ${{ matrix.runs }} + + steps: + - name: Checkout working copy + uses: actions/checkout@v4 + with: + submodules: true + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + allow-prereleases: true + - name: Retrieve wheel + uses: actions/download-artifact@v4 + with: + name: wheels-${{ matrix.platform }}-${{ matrix.arch }}-${{ matrix.wheel }} + path: dist + - name: Update pip + run: python -mpip install --upgrade pip + - name: Maybe install libyaml-dev + if: matrix.runs == 'ubuntu-latest' + run: | + # if binary wheels are not available for the current + # package install libyaml-dev so we can install pyyaml + # from source + if ! pip download --only-binary :all: pyyaml > /dev/null 2>&1; then + sudo apt install libyaml-dev + fi + - name: Install test dependencies + run: python -mpip install pytest pyyaml + - name: Install wheel + run: pip install --find-links dist ua_parser_rs + - name: Run tests + run: pytest -v -Werror -ra ua-parser-py diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index e22aeaa..25a53a3 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -1,25 +1,24 @@ name: Rust on: - push: - branches: [ "main" ] pull_request: - branches: [ "main" ] + push: + branches: + - main env: CARGO_TERM_COLOR: always jobs: checks: - runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - - name: Build - run: cargo build --verbose + - name: Check + run: cargo check - name: Format run: cargo fmt --check - name: clippy diff --git a/.gitignore b/.gitignore index 2ce191f..bffc5eb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ Cargo.lock *.dSYM/ regex-filtered/re2/flake.lock regex-filtered/re2/bench +.tox/ +__pycache__ diff --git a/Cargo.toml b/Cargo.toml index e857923..c9976a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["regex-filtered", "ua-parser"] +members = ["regex-filtered", "ua-parser", "ua-parser-py"] resolver = "2" [profile.release] diff --git a/ua-parser-py/Cargo.toml b/ua-parser-py/Cargo.toml new file mode 100644 index 0000000..bf82718 --- /dev/null +++ b/ua-parser-py/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "ua-parser-rs" +version = "0.1.0" +edition = "2021" +license = "Apache 2.0" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[lib] +name = "ua_parser_rs" +crate-type = ["cdylib"] + +[dependencies] +pyo3 = { version = "0.22", features = ["extension-module", "abi3", "abi3-py38"] } +ua-parser = { version = "0.2.0", path = "../ua-parser" } diff --git a/ua-parser-py/LICENSE b/ua-parser-py/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/ua-parser-py/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/ua-parser-py/pyproject.toml b/ua-parser-py/pyproject.toml new file mode 100644 index 0000000..b8fcddd --- /dev/null +++ b/ua-parser-py/pyproject.toml @@ -0,0 +1,18 @@ +[build-system] +requires = ["maturin>=1.5,<2.0"] +build-backend = "maturin" + +[project] +name = "ua-parser-rs" +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Rust", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + # "Programming Language :: Python :: Implementation :: GraalPy", + "License :: OSI Approved :: Apache Software License", +] +dynamic = ["version"] +[tool.maturin] +features = ["pyo3/extension-module"] diff --git a/ua-parser-py/src/lib.rs b/ua-parser-py/src/lib.rs new file mode 100644 index 0000000..0951c58 --- /dev/null +++ b/ua-parser-py/src/lib.rs @@ -0,0 +1,202 @@ +/// An uap-python Resolver is a callable which returns a PartialResult +/// (~a triplet of optional user_agent, os, and domain). A resolver +/// has lists of matchers for user agents, os, and devices taken in as +/// a Matchers (a 3-uple of lists of matchers). +/// +/// A matcher is a callable with a `pattern` and a `flags` properties. +/// But matchers also have additional properties for the replacement +/// information. +/// +/// In uap-rs, that's the ua_parser::Extractor doing that, kinda, but +/// it takes a struct from regexes.yaml and parses them in, so +/// probably better leaving that to the Python side and instead +/// exposing individual extractors with convenient interfaces. +/// +/// An Extractor is built off of a series of Parsers, which we could +/// get directly from the python side matchers *if those kept the +/// string as `regex` -> swap pattern and regex in the matcher (/ +/// rename pattern), and maybe expose regex_flag? +/// +/// May not matter as much because pyo3 natively can't piggyback +/// FromPyObject onto Deserialize, this requires the pythonize crate +/// and that seems a bit much for a measly 3 structs... Still, would +/// probably be a good idea for uap-python's matchers to retain the +/// structure of regexes.yaml parsers. Would have been nice to rename +/// them to Parsers as well but that's still very confusing given the +/// global Parser object, unless *that* gets renamed to Extractor on +/// the python side, or something. +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; +use std::borrow::Cow::{self, Owned}; + +type UAParser = ( + String, + Option, + Option, + Option, + Option, + Option, +); +#[pyclass(frozen)] +struct UserAgentExtractor(ua_parser::user_agent::Extractor<'static>); +#[pyclass(frozen)] +struct UserAgent { + #[pyo3(get)] + family: String, + #[pyo3(get)] + major: Option, + #[pyo3(get)] + minor: Option, + #[pyo3(get)] + patch: Option, + #[pyo3(get)] + patch_minor: Option, +} +#[pymethods] +impl UserAgentExtractor { + #[new] + fn new(it: &Bound) -> PyResult { + use ua_parser::user_agent::{Builder, Parser}; + it.iter()? + .try_fold(Builder::new(), |s, p| { + let p: UAParser = p?.extract()?; + s.push(Parser { + regex: Owned(p.0), + family_replacement: p.1.map(Owned), + v1_replacement: p.2.map(Owned), + v2_replacement: p.3.map(Owned), + v3_replacement: p.4.map(Owned), + v4_replacement: p.5.map(Owned), + }) + .map_err(|e| PyValueError::new_err(e.to_string())) + })? + .build() + .map_err(|e| PyValueError::new_err(e.to_string())) + .map(Self) + } + fn extract(&self, s: &str) -> PyResult> { + Ok(self.0.extract(s).map(|v| UserAgent { + family: v.family.into_owned(), + major: v.major.map(|s| s.to_string()), + minor: v.minor.map(|s| s.to_string()), + patch: v.patch.map(|s| s.to_string()), + patch_minor: v.patch_minor.map(|s| s.to_string()), + })) + } +} + +type OSParser = ( + String, + Option, + Option, + Option, + Option, + Option, +); +#[pyclass(frozen)] +struct OSExtractor(ua_parser::os::Extractor<'static>); +#[pyclass(frozen)] +struct OS { + #[pyo3(get)] + family: String, + #[pyo3(get)] + major: Option, + #[pyo3(get)] + minor: Option, + #[pyo3(get)] + patch: Option, + #[pyo3(get)] + patch_minor: Option, +} +#[pymethods] +impl OSExtractor { + #[new] + fn new(it: &Bound) -> PyResult { + use ua_parser::os::{Builder, Parser}; + it.iter()? + .try_fold(Builder::new(), |s, p| { + let p: OSParser = p?.extract()?; + s.push(Parser { + regex: Owned(p.0), + os_replacement: p.1.map(Owned), + os_v1_replacement: p.2.map(Owned), + os_v2_replacement: p.3.map(Owned), + os_v3_replacement: p.4.map(Owned), + os_v4_replacement: p.5.map(Owned), + }) + .map_err(|e| PyValueError::new_err(e.to_string())) + })? + .build() + .map_err(|e| PyValueError::new_err(e.to_string())) + .map(Self) + } + fn extract(&self, s: &str) -> PyResult> { + Ok(self.0.extract(s).map(|v| OS { + family: v.os.into_owned(), + major: v.major.map(Cow::into_owned), + minor: v.minor.map(Cow::into_owned), + patch: v.patch.map(Cow::into_owned), + patch_minor: v.patch_minor.map(Cow::into_owned), + })) + } +} + +type DeviceParser = ( + String, + Option, + Option, + Option, + Option, +); +#[pyclass(frozen)] +struct DeviceExtractor(ua_parser::device::Extractor<'static>); +#[pyclass(frozen)] +struct Device { + #[pyo3(get)] + family: String, + #[pyo3(get)] + brand: Option, + #[pyo3(get)] + model: Option, +} +#[pymethods] +impl DeviceExtractor { + #[new] + fn new(it: &Bound) -> PyResult { + use ua_parser::device::{Builder, Flag, Parser}; + it.iter()? + .try_fold(Builder::new(), |s, p| { + let p: DeviceParser = p?.extract()?; + s.push(Parser { + regex: Owned(p.0), + regex_flag: if p.1.as_deref() == Some("i") { + Some(Flag::IgnoreCase) + } else { + None + }, + device_replacement: p.2.map(Owned), + brand_replacement: p.3.map(Owned), + model_replacement: p.4.map(Owned), + }) + .map_err(|e| PyValueError::new_err(e.to_string())) + })? + .build() + .map_err(|e| PyValueError::new_err(e.to_string())) + .map(Self) + } + fn extract(&self, s: &str) -> PyResult> { + Ok(self.0.extract(s).map(|v| Device { + family: v.device.into_owned(), + brand: v.brand.map(Cow::into_owned), + model: v.model.map(Cow::into_owned), + })) + } +} + +#[pymodule] +fn ua_parser_rs(m: &Bound) -> PyResult<()> { + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + Ok(()) +} diff --git a/ua-parser-py/tests/test_device.py b/ua-parser-py/tests/test_device.py new file mode 100644 index 0000000..cc1e5aa --- /dev/null +++ b/ua-parser-py/tests/test_device.py @@ -0,0 +1,53 @@ +import pathlib +import operator + +import pytest + +try: + from yaml import CSafeLoader as SafeLoader, load +except ImportError: + from yaml import SafeLoader, load # type: ignore + +import ua_parser_rs + + +CORE_DIR = pathlib.Path(__file__).resolve().parents[2] / "ua-parser" / "uap-core" + +MISSING_UA = {"family": "Other", "brand": None, "model": None} +get_reference = operator.itemgetter(*MISSING_UA) +get_result = operator.attrgetter(*MISSING_UA) + + +@pytest.mark.parametrize( + "test_file", + [ + CORE_DIR / "tests" / "test_device.yaml", + ], + ids=operator.attrgetter("name"), +) +def test_device(test_file: pathlib.Path) -> None: + with (CORE_DIR / "regexes.yaml").open("rb") as f: + contents = load(f, Loader=SafeLoader) + + parser = ua_parser_rs.DeviceExtractor( + ( + t["regex"], + t.get("regex_flag"), + t.get("device_replacement"), + t.get("brand_replacement"), + t.get("model_replacement"), + ) + for t in contents["device_parsers"] + ) + + with test_file.open("rb") as f: + contents = load(f, Loader=SafeLoader) + + for test_case in contents["test_cases"]: + r = parser.extract(test_case["user_agent_string"]) + if r: + result = get_result(r) + else: + result = get_reference(MISSING_UA) + + assert result == get_reference(test_case) diff --git a/ua-parser-py/tests/test_os.py b/ua-parser-py/tests/test_os.py new file mode 100644 index 0000000..2c92382 --- /dev/null +++ b/ua-parser-py/tests/test_os.py @@ -0,0 +1,63 @@ +import pathlib +import operator + +import pytest + +try: + from yaml import CSafeLoader as SafeLoader, load +except ImportError: + from yaml import SafeLoader, load # type: ignore + +import ua_parser_rs + + +CORE_DIR = pathlib.Path(__file__).resolve().parents[2] / "ua-parser" / "uap-core" + + +MISSING_UA = { + "family": "Other", + "major": None, + "minor": None, + "patch": None, + "patch_minor": None, +} +get_reference = operator.itemgetter(*MISSING_UA) +get_result = operator.attrgetter(*MISSING_UA) + + +@pytest.mark.parametrize( + "test_file", + [ + CORE_DIR / "tests" / "test_os.yaml", + CORE_DIR / "test_resources" / "additional_os_tests.yaml", + ], + ids=operator.attrgetter("name"), +) +def test_os(test_file: pathlib.Path) -> None: + with (CORE_DIR / "regexes.yaml").open("rb") as f: + contents = load(f, Loader=SafeLoader) + + parser = ua_parser_rs.OSExtractor( + ( + t["regex"], + t.get("os_replacement"), + t.get("os_v1_replacement"), + t.get("os_v2_replacement"), + t.get("os_v3_replacement"), + t.get("os_v4_replacement"), + ) + for t in contents["os_parsers"] + ) + + with test_file.open("rb") as f: + contents = load(f, Loader=SafeLoader) + + for test_case in contents["test_cases"]: + r = parser.extract(test_case["user_agent_string"]) + if r: + result = get_result(r) + else: + result = get_reference(MISSING_UA) + + print(test_case) + assert result == get_reference(test_case) diff --git a/ua-parser-py/tests/test_ua.py b/ua-parser-py/tests/test_ua.py new file mode 100644 index 0000000..d0128dc --- /dev/null +++ b/ua-parser-py/tests/test_ua.py @@ -0,0 +1,64 @@ +import pathlib +import operator + +import pytest + +try: + from yaml import CSafeLoader as SafeLoader, load +except ImportError: + from yaml import SafeLoader, load # type: ignore + +import ua_parser_rs + + +CORE_DIR = pathlib.Path(__file__).resolve().parents[2] / "ua-parser" / "uap-core" + + +MISSING_UA = { + "family": "Other", + "major": None, + "minor": None, + "patch": None, +} # , "patch_minor": None} +get_reference = operator.itemgetter(*MISSING_UA) +get_result = operator.attrgetter(*MISSING_UA) + + +@pytest.mark.parametrize( + "test_file", + [ + CORE_DIR / "tests" / "test_ua.yaml", + CORE_DIR / "test_resources" / "firefox_user_agent_strings.yaml", + CORE_DIR / "test_resources" / "pgts_browser_list.yaml", + CORE_DIR / "test_resources" / "opera_mini_user_agent_strings.yaml", + CORE_DIR / "test_resources" / "podcasting_user_agent_strings.yaml", + ], + ids=operator.attrgetter("name"), +) +def test_ua(test_file: pathlib.Path) -> None: + with (CORE_DIR / "regexes.yaml").open("rb") as f: + contents = load(f, Loader=SafeLoader) + + parser = ua_parser_rs.UserAgentExtractor( + ( + t["regex"], + t.get("family_replacement"), + t.get("v1_replacement"), + t.get("v2_replacement"), + t.get("v3_replacement"), + t.get("v4_replacement"), + ) + for t in contents["user_agent_parsers"] + ) + + with test_file.open("rb") as f: + contents = load(f, Loader=SafeLoader) + + for test_case in contents["test_cases"]: + r = parser.extract(test_case["user_agent_string"]) + if r: + result = get_result(r) + else: + result = get_reference(MISSING_UA) + + assert result == get_reference(test_case) diff --git a/ua-parser-py/tox.ini b/ua-parser-py/tox.ini new file mode 100644 index 0000000..ad09f15 --- /dev/null +++ b/ua-parser-py/tox.ini @@ -0,0 +1,29 @@ +[tox] +env_list = py{39,310,311,312}, pypy3.10#, graalpy + , typecheck, format, lint +skip_missing_interpreters = true + +[testenv] +package = wheel +deps = + pytest + pyyaml +commands = pytest -Werror tests {posargs} + +[testenv:lint] +package = skip +deps = ruff +commands = ruff check {posargs} + +[testenv:format] +package = skip +deps = ruff +commands = ruff format {posargs:--diff} + +[testenv:typecheck] +package = skip +deps = + mypy + pytest + types-PyYaml +commands = mypy --strict {posargs:} . diff --git a/ua-parser-py/ua_parser_rs.pyi b/ua-parser-py/ua_parser_rs.pyi new file mode 100644 index 0000000..5b39f02 --- /dev/null +++ b/ua-parser-py/ua_parser_rs.pyi @@ -0,0 +1,59 @@ +from collections.abc import Iterable +from typing import Literal, Protocol + +UAParser = tuple[ + str, + str | None, + str | None, + str | None, + str | None, + str | None, +] + +class UserAgent(Protocol): + family: str + major: str | None + minor: str | None + patch: str | None + patch_minor: str | None + +class UserAgentExtractor: + def __init__(self, it: Iterable[UAParser], /) -> None: ... + def extract(self, s: str, /) -> UserAgent | None: ... + +OSParser = tuple[ + str, + str | None, + str | None, + str | None, + str | None, + str | None, +] + +class OS(Protocol): + family: str + major: str | None + minor: str | None + patch: str | None + patch_minor: str | None + +class OSExtractor: + def __init__(self, it: Iterable[OSParser], /) -> None: ... + def extract(self, s: str, /) -> OS | None: ... + +DeviceParser = tuple[ + str, + Literal["i"] | None, + str | None, + str | None, + str | None, +] + +class Device(Protocol): + family: str + brand: str | None + model: str | None + +class DeviceExtractor: + def __init__(self, it: Iterable[DeviceParser], /) -> None: ... + def extract(self, s: str, /) -> Device | None: ...