Skip to content

Commit

Permalink
ft: black GH runner, remove dead code
Browse files Browse the repository at this point in the history
  • Loading branch information
Mattwmaster58 committed Oct 25, 2024
1 parent 13eee2b commit 218512e
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 108 deletions.
13 changes: 12 additions & 1 deletion .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
python-version: [ "3.8", "3.9", "3.10", "3.11", "3.12", "3.13" ]

steps:
- uses: actions/checkout@v4
Expand All @@ -26,8 +26,19 @@ jobs:
run: |
python -m pip install -U pip
pip install pytest playwright
playwright install-deps
playwright install chromium firefox
pip install -e ".[test]"
- name: Test with pytest
run: |
pytest
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.13'
- uses: psf/black@stable
with:
use_pyproject: true
13 changes: 9 additions & 4 deletions playwright_stealth/context_managers.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from playwright import async_api, sync_api


class AsyncWrappingContextManager:
def __init__(self, stealth: 'Stealth', manager: async_api.PlaywrightContextManager):
def __init__(self, stealth: "Stealth", manager: async_api.PlaywrightContextManager):
if isinstance(manager, sync_api.PlaywrightContextManager):
raise TypeError("You need to call 'use_sync' instead of 'use_async' for a sync Playwright context")
self.stealth = stealth
self.manager = manager

async def __aenter__(self, ) -> async_api.Playwright:
async def __aenter__(
self,
) -> async_api.Playwright:
context = await self.manager.__aenter__()
self.stealth.hook_playwright_context(context)
return context
Expand All @@ -17,13 +20,15 @@ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:


class SyncWrappingContextManager:
def __init__(self, stealth: 'Stealth', manager: sync_api.PlaywrightContextManager):
def __init__(self, stealth: "Stealth", manager: sync_api.PlaywrightContextManager):
if isinstance(manager, async_api.PlaywrightContextManager):
raise TypeError("You need to call 'use_async' instead of 'use_sync' for an async Playwright context")
self.stealth = stealth
self.manager = manager

def __enter__(self, ) -> sync_api.Playwright:
def __enter__(
self,
) -> sync_api.Playwright:
context = self.manager.__enter__()
self.stealth.hook_playwright_context(context)
return context
Expand Down
8 changes: 2 additions & 6 deletions playwright_stealth/js/generate.magic.arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ generateFunctionMocks = (proto, itemMainProp, dataArray) => ({
apply(target, ctx, args) {
if (!args.length) {
throw new TypeError(
`Failed to execute 'item' on '${
proto[Symbol.toStringTag]
}': 1 argument required, but only 0 present.`
`Failed to execute 'item' on '${proto[Symbol.toStringTag]}': 1 argument required, but only 0 present.`
);
}
// Special behavior alert:
Expand All @@ -21,9 +19,7 @@ generateFunctionMocks = (proto, itemMainProp, dataArray) => ({
apply(target, ctx, args) {
if (!args.length) {
throw new TypeError(
`Failed to execute 'namedItem' on '${
proto[Symbol.toStringTag]
}': 1 argument required, but only 0 present.`
`Failed to execute 'namedItem' on '${proto[Symbol.toStringTag]}': 1 argument required, but only 0 present.`
);
}
return dataArray.find((mt) => mt[itemMainProp] === args[0]) || null; // Not `undefined`!
Expand Down
87 changes: 51 additions & 36 deletions playwright_stealth/stealth.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@

from playwright import async_api, sync_api

from playwright_stealth.context_managers import AsyncWrappingContextManager, SyncWrappingContextManager
from playwright_stealth.context_managers import (
AsyncWrappingContextManager,
SyncWrappingContextManager,
)


def from_file(name) -> str:
Expand Down Expand Up @@ -60,32 +63,32 @@ def enabled_scripts():
"""

def __init__(
self,
navigator_webdriver: bool = True,
webgl_vendor: bool = True,
chrome_app: bool = True,
chrome_csi: bool = True,
chrome_load_times: bool = True,
chrome_runtime: bool = False,
iframe_content_window: bool = True,
media_codecs: bool = True,
navigator_hardware_concurrency: bool = True,
navigator_languages: bool = True,
navigator_permissions: bool = True,
navigator_platform: bool = True,
navigator_plugins: bool = True,
navigator_user_agent: bool = True,
navigator_vendor: bool = True,
hairline: bool = True,
webgl_vendor_override: str = "Intel Inc.",
webgl_renderer_override: str = "Intel Iris OpenGL Engine",
navigator_vendor_override: str = "Google Inc.",
navigator_user_agent_override: Optional[str] = None,
navigator_platform_override: Optional[str] = None,
navigator_languages_override: Tuple[str, str] = ("en-US", "en"),
chrome_runtime_run_on_insecure_origins: bool = False,
init_scripts_only: bool = False,
script_logging: bool = False,
self,
navigator_webdriver: bool = True,
webgl_vendor: bool = True,
chrome_app: bool = True,
chrome_csi: bool = True,
chrome_load_times: bool = True,
chrome_runtime: bool = False,
iframe_content_window: bool = True,
media_codecs: bool = True,
navigator_hardware_concurrency: bool = True,
navigator_languages: bool = True,
navigator_permissions: bool = True,
navigator_platform: bool = True,
navigator_plugins: bool = True,
navigator_user_agent: bool = True,
navigator_vendor: bool = True,
hairline: bool = True,
webgl_vendor_override: str = "Intel Inc.",
webgl_renderer_override: str = "Intel Iris OpenGL Engine",
navigator_vendor_override: str = "Google Inc.",
navigator_user_agent_override: Optional[str] = None,
navigator_platform_override: Optional[str] = None,
navigator_languages_override: Tuple[str, str] = ("en-US", "en"),
chrome_runtime_run_on_insecure_origins: bool = False,
init_scripts_only: bool = False,
script_logging: bool = False,
):
# scripts to load
self.navigator_webdriver: bool = navigator_webdriver
Expand Down Expand Up @@ -216,8 +219,9 @@ def apply_stealth_sync(self, page_or_context: Union[sync_api.Page, sync_api.Brow
if len(self.script_payload) > 0:
page_or_context.add_init_script(self.script_payload)

def _kwargs_with_patched_cli_arg(self, method: Callable, packed_kwargs: Dict[str, Any], chromium_mode: bool) -> \
Dict[str, Any]:
def _kwargs_with_patched_cli_arg(
self, method: Callable, packed_kwargs: Dict[str, Any], chromium_mode: bool
) -> Dict[str, Any]:
signature = inspect.signature(method).parameters
args_parameter = signature.get("args")

Expand All @@ -241,14 +245,20 @@ def hook_playwright_context(self, ctx: Union[async_api.Playwright, sync_api.Play
"""
for browser_type in (ctx.chromium, ctx.firefox, ctx.webkit):
for name, method in inspect.getmembers(browser_type, predicate=inspect.ismethod):
if method.__annotations__.get('return') in ("Browser", "BrowserContext"):
if method.__annotations__.get("return") in (
"Browser",
"BrowserContext",
):
chromium_mode = browser_type.name == "chromium"
method = self._generate_hooked_method_that_returns_browser(method, chromium_mode)
setattr(browser_type, name, method)

def _generate_hooked_method_that_returns_browser(self, method: Callable, chromium_mode: bool):
async def async_hooked_method(*args, **kwargs) -> Union[async_api.Browser, async_api.BrowserContext]:
browser_or_context = await method(*args, **self._kwargs_with_patched_cli_arg(method, kwargs, chromium_mode))
browser_or_context = await method(
*args,
**self._kwargs_with_patched_cli_arg(method, kwargs, chromium_mode),
)
if isinstance(browser_or_context, async_api.BrowserContext):
context: async_api.BrowserContext = browser_or_context
context.new_page = self._generate_hooked_new_page(context.new_page)
Expand All @@ -262,7 +272,10 @@ async def async_hooked_method(*args, **kwargs) -> Union[async_api.Browser, async
return browser_or_context

def sync_hooked_method(*args, **kwargs) -> Union[sync_api.Browser, sync_api.BrowserContext]:
browser_or_context = method(*args, **self._kwargs_with_patched_cli_arg(method, kwargs, chromium_mode))
browser_or_context = method(
*args,
**self._kwargs_with_patched_cli_arg(method, kwargs, chromium_mode),
)
if isinstance(browser_or_context, sync_api.BrowserContext):
context: sync_api.BrowserContext = browser_or_context
context.new_page = self._generate_hooked_new_page(context.new_page)
Expand Down Expand Up @@ -343,9 +356,11 @@ def _patch_cli_arg(existing_args: List[str], flag: str) -> List[str]:
for arg in existing_args:
stripped_arg = arg.strip()
if stripped_arg.startswith(switch_name):
warnings.warn("playwright-stealth is trying to modify a flag you have set yourself already."
f"Either disable the mitigation or don't specify this flag manually {flag=}"
f"to avoid this warning. playwright-stealth has overridden your flag")
warnings.warn(
"playwright-stealth is trying to modify a flag you have set yourself already."
f"Either disable the mitigation or don't specify this flag manually {flag=}"
f"to avoid this warning. playwright-stealth has overridden your flag"
)
new_args.append(flag)
break
else:
Expand Down Expand Up @@ -373,4 +388,4 @@ def _patch_cli_arg(existing_args: List[str], flag: str) -> List[str]:
"navigator_user_agent": False,
"navigator_vendor": False,
"hairline": False,
}
}
53 changes: 0 additions & 53 deletions playwright_stealth/types.py

This file was deleted.

5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ dependencies = [

[project.optional-dependencies]
test = [
"pytest", "pytest-asyncio"
"pytest", "pytest-asyncio", "black~=24.10.0"
]

[project.urls]
Expand All @@ -33,3 +33,6 @@ Homepage = "https://github.com/Mattwmaster58/playwright_stealth"
asyncio_mode="auto"
asyncio_default_fixture_loop_scope="function"
log_cli=true

[tool.black]
line-length=120
9 changes: 2 additions & 7 deletions tests/test_basics.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import asyncio
import logging

import pytest
from playwright import sync_api
from playwright.async_api import async_playwright
from playwright.sync_api import sync_playwright, Browser
from playwright.sync_api import sync_playwright

from playwright_stealth.stealth import Stealth, ALL_EVASIONS_DISABLED_KWARGS

Expand Down Expand Up @@ -43,6 +39,7 @@ def test_sync_navigator_webdriver_smoketest(hooked_sync_browser):
def test_payload_is_empty_when_no_evasions_active():
assert len(Stealth(**ALL_EVASIONS_DISABLED_KWARGS).script_payload) == 0


def test_empty_payload_not_injected():
init_script_added = False

Expand All @@ -54,5 +51,3 @@ def add_init_script(self, *args, **kwargs):
# noinspection PyTypeChecker
Stealth(**ALL_EVASIONS_DISABLED_KWARGS).apply_stealth_sync(MockBrowser())
assert not init_script_added


0 comments on commit 218512e

Please sign in to comment.