repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
CloakBrowser
tests/test_proxy.py
.py
"""Tests for proxy URL parsing and credential extraction.""" from unittest.mock import patch from cloakbrowser.browser import ( _is_socks_proxy, _parse_proxy_url, _resolve_proxy_config, maybe_resolve_geoip, ) class TestParseProxyUrl: def test_no_credentials(self): assert _parse_proxy_url...
520
25,057
CloakBrowser
tests/test_update.py
.py
"""Tests for auto-update and version management.""" from __future__ import annotations import base64 import hashlib import os from unittest.mock import MagicMock, patch import pytest from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cloakbrowser.config import ( _version_newer,...
1,513
62,675
CloakBrowser
tests/test_persistent_context.py
.py
"""Unit tests for launch_persistent_context() and launch_persistent_context_async(). All tests mock playwright to avoid needing a binary. """ from unittest.mock import AsyncMock, MagicMock, patch import pytest from cloakbrowser.config import DEFAULT_VIEWPORT def _make_mock_pw_and_context(): """Create mock syn...
306
14,012
CloakBrowser
tests/test_cloakserve.py
.py
"""Unit tests for cloakserve β€” parse_connection_params, parse_cli_args, URL rewriting, connection tracking.""" import asyncio import importlib.machinery import importlib.util import json import sys from pathlib import Path from types import SimpleNamespace from unittest.mock import patch import pytest aiohttp = pyte...
679
25,110
CloakBrowser
tests/test_config.py
.py
"""Unit tests for config.py β€” platform detection, paths, stealth args.""" import os from unittest.mock import patch import pytest from cloakbrowser.config import ( binary_supports_headless_no_viewport, binary_supports_maximized_window, get_archive_ext, get_archive_name, get_binary_path, get_c...
241
9,844
CloakBrowser
tests/test_stealth_unit.py
.py
""" Unit tests for stealth / anti-detection fixes (issue #110). Covers: - _SyncIsolatedWorld / _AsyncIsolatedWorld β€” CDP isolated-world lifecycle - _is_input_element / _is_selector_focused β€” stealth DOM queries with fallback - _type_shift_symbol / _type_shift_symbol (async) β€” CDP Input.dispatchKeyEvent path - ...
1,486
54,352
CloakBrowser
tests/test_widevine.py
.py
"""Unit tests for Widevine CDM hint-file seeding (cloakbrowser/widevine.py).""" import json import pytest from cloakbrowser import widevine from cloakbrowser.widevine import resolve_widevine_cdm_dir, seed_widevine_hint _HINT = "WidevineCdm/latest-component-updated-widevine-cdm" @pytest.fixture(autouse=True) def _...
199
8,091
CloakBrowser
tests/test_launch_context.py
.py
"""Unit tests for launch_context() β€” context kwargs, viewport defaults, close cleanup.""" from unittest.mock import AsyncMock, MagicMock, patch import pytest from cloakbrowser.config import DEFAULT_VIEWPORT # All tests mock launch() to avoid needing a binary. # launch_context() calls launch() internally, then brow...
460
17,458
CloakBrowser
tests/test_stealth_reproduction_110.py
.py
# tests/test_stealth_reproduction_110.py """ Exact reproduction of issue #110 detection vectors. Proves all three leaks (isInputElement, isSelectorFocused, typeShiftSymbol) are fixed with CDP isolated worlds. """ import asyncio import pytest @pytest.mark.slow class TestIssue110Reproduction: @pytest.mark.asyncio ...
169
6,044
CloakBrowser
tests/test_welcome_banner.py
.py
"""Tier-aware launch banner: keyless (v146) / free key / paid, + cadence.""" import time from pathlib import Path import pytest from cloakbrowser import download @pytest.fixture def cache(tmp_path, monkeypatch): monkeypatch.setenv("CLOAKBROWSER_CACHE_DIR", str(tmp_path)) return tmp_path def _banner(capsys...
70
2,619
CloakBrowser
tests/test_humanize_unit.py
.py
""" Unit + integration tests for the humanize layer. Fast unit tests (config, BΓ©zier math, mocks) are proper test_ functions that pytest discovers automatically. Browser-dependent tests are marked @pytest.mark.slow and skipped in CI unless explicitly requested (pytest -m slow). Can also run directly: python tests/te...
2,711
108,648
CloakBrowser
tests/test_extension_loading.py
.py
import os from unittest.mock import MagicMock, patch from cloakbrowser import launch @patch("cloakbrowser.browser.ensure_binary") @patch("playwright.sync_api.sync_playwright") def test_extension_loading(mock_sync_playwright, mock_ensure_binary): mock_ensure_binary.return_value = "/fake/chrome" mock_browser ...
31
819
CloakBrowser
tests/test_login.py
.py
"""Tests for `cloakbrowser login` / `logout` (key activation, no network/binary).""" import argparse from unittest import mock import pytest import cloakbrowser.__main__ as m from cloakbrowser.license import LicenseInfo @pytest.fixture def cache_dir(tmp_path, monkeypatch): monkeypatch.setenv("CLOAKBROWSER_CACHE...
78
2,803
CloakBrowser
tests/test_geoip.py
.py
"""Unit tests for GeoIP-based timezone/locale detection.""" from unittest.mock import MagicMock, patch import threading import time import pytest from cloakbrowser.browser import maybe_resolve_geoip from cloakbrowser.geoip import ( COUNTRY_LOCALE_MAP, _is_private_ip, _resolve_exit_ip, _resolve_proxy_...
362
13,620
CloakBrowser
tests/test_build_args.py
.py
"""Unit tests for build_args timezone/locale injection and timezone alias.""" from cloakbrowser.browser import build_args, _resolve_timezone def test_timezone_injected(): """--fingerprint-timezone flag should appear when timezone is set.""" args = build_args(stealth_args=True, extra_args=None, timezone="Amer...
233
8,751
CloakBrowser
tests/test_launch.py
.py
"""Basic launch tests for cloakbrowser.""" import pytest from cloakbrowser import ( launch, launch_async, launch_context, launch_persistent_context, binary_info, ) from cloakbrowser.config import get_chromium_version @pytest.mark.parametrize("env", [None, "patchright"]) def test_removed_backend_k...
112
3,695
CloakBrowser
tests/test_font_warning.py
.py
"""Unit tests for the Linux Windows-font mismatch warning (browser.py). The warning fires once per environment when spoofing Windows on a font-less Linux host. These tests mock platform, fc-list, and the cache dir so they are host-independent and need no binary. The warning is written straight to stderr (like the welc...
141
5,524
CloakBrowser
tests/test_cli.py
.py
"""Unit tests for the cloakbrowser CLI diagnostics (`info` / `doctor`).""" import json import os import sys from argparse import Namespace from unittest.mock import patch import pytest import cloakbrowser.__main__ from cloakbrowser.__main__ import _binary_version, cmd_info from cloakbrowser.license import LicenseInf...
355
14,087
CloakBrowser
tests/test_license_error.py
.py
"""Tests for license exit-code -> message surfacing (license_error_message).""" import json import pytest from cloakbrowser import CloakBrowserLicenseError from cloakbrowser.license import ( license_error_for_code, license_error_message, mint_denial_file, read_denial_file, ) def _launch_text(code: ...
369
12,944
CloakBrowser
tests/test_license.py
.py
"""Tests for the CloakBrowser Pro license module.""" import hashlib import json import os import time from pathlib import Path from unittest.mock import MagicMock, patch import pytest from cloakbrowser.download import BinaryVerificationError, ensure_binary from cloakbrowser.license import ( LicenseInfo, buil...
853
38,493
CloakBrowser
tests/test_human_visual.py
.py
""" Visual + functional test for humanize. Red dot = cursor, yellow = mouse held. """ import pytest pytestmark = pytest.mark.slow if __name__ == "__main__": from cloakbrowser import launch import time CURSOR_JS = """ () => { if (document.getElementById('__hc')) return; const el = docum...
364
14,376
CloakBrowser
tests/test_stealth_resolver_js.py
.py
"""Resolver-JS selector-semantics tests. ``cloakbrowser/human/stealth_dom.py`` embeds a JavaScript selector resolver that runs in the browser's isolated world. Its selector *semantics* (``:has-text``, ``text=``, ``xpath=``, trailing ``>> nth=N``, and the unsupported-grammar fallback) can't be exercised from pure Pytho...
103
4,638
CloakBrowser
tests/test_fetch_widevine.py
.py
"""Unit tests for bin/fetch-widevine.py β€” CRX3/protobuf parsing, app-id pinning, signature verification, the integrity-install policy, and zip extraction. All offline: the network (`_resolve_crx`/`_download`) is mocked, and a minimal CRX3 is synthesized in-process with a throwaway RSA key (with ``APP_ID`` monkeypatche...
310
12,557
CloakBrowser
tests/test_lambda_security.py
.py
"""Security tests for the AWS Lambda handler URL validation.""" from __future__ import annotations import sys from pathlib import Path from unittest.mock import patch import pytest sys.path.insert( 0, str(Path(__file__).resolve().parent.parent / "examples" / "integrations" / "aws_lambda") ) from lambda_handler...
172
7,267
CloakBrowser
tests/conftest.py
.py
"""Shared pytest fixtures.""" import pytest @pytest.fixture(autouse=True) def isolated_cache_dir(tmp_path_factory, monkeypatch): """Keep the suite away from the developer's real ``~/.cloakbrowser``. A ``license.key`` (or a cached Pro version marker) in the real cache dir resolves the machine as Pro, whi...
20
724
CloakBrowser
examples/fingerprint_scan_test.py
.py
"""Test against fingerprint-scan.com and CreepJS. Tests the specific headless detection signals flagged by the community: - noTaskbar, noContentIndex, noContactsManager, noDownlinkMax - Bot risk score (fingerprint-scan.com) - Headless/stealth percentages (CreepJS) - Full CreepJS signal breakdown (likeHeadless, headles...
230
8,346
CloakBrowser
examples/recaptcha_score.py
.py
"""Check reCAPTCHA v3 score with stealth browser. Visits Google's reCAPTCHA demo page and extracts the score. Expected: 0.9 (human-level) with cloakbrowser. Default Playwright typically scores 0.1-0.3. """ import re from cloakbrowser import launch print("Launching stealth browser...", flush=True) browser = launch(h...
37
1,210
CloakBrowser
examples/stealth_test.py
.py
"""Run stealth tests against major bot detection services. Tests cloakbrowser against multiple detection sites, extracts pass/fail verdicts via JS evaluation, and reports results with screenshots. Usage: python examples/stealth_test.py python examples/stealth_test.py --headed # watch in real-time pyth...
330
12,730
CloakBrowser
examples/persistent_context.py
.py
"""Persistent context example: cookies and localStorage survive across sessions.""" from cloakbrowser import launch_persistent_context PROFILE_DIR = "./my-profile" # Session 1 β€” set some state print("=== Session 1: Setting state ===") print("Launching stealth browser...", flush=True) ctx = launch_persistent_context(...
32
1,116
CloakBrowser
examples/basic.py
.py
"""Basic example: launch stealth browser and load a page.""" from cloakbrowser import launch print("Launching stealth browser...", flush=True) browser = launch(headless=False) page = browser.new_page() page.goto("https://example.com") print(f"Title: {page.title()}") print(f"URL: {page.url}") browser.close() print("...
15
328
CloakBrowser
examples/integrations/undetected_chromedriver.py
.py
"""undetected-chromedriver + CloakBrowser: double stealth layer. undetected-chromedriver patches ChromeDriver detection signals, CloakBrowser patches the browser fingerprints at the C++ level. Requires: pip install undetected-chromedriver cloakbrowser """ import undetected_chromedriver as uc from cloakbrowser.confi...
41
1,188
CloakBrowser
examples/integrations/langchain_loader.py
.py
"""LangChain + CloakBrowser: load web pages behind bot detection into LangChain Documents. LangChain's PlaywrightURLLoader hardcodes chromium.launch() with no way to pass a custom binary. This example uses CloakBrowser directly as a stealth document loader that produces LangChain Document objects. Requires: pip insta...
52
1,441
CloakBrowser
examples/integrations/crawlee_example.py
.py
"""Crawlee + CloakBrowser: stealth web crawling with PlaywrightCrawler. Uses a custom BrowserPlugin to swap Crawlee's default Chromium for CloakBrowser's patched binary with source-level fingerprint patches. Requires: pip install cloakbrowser "crawlee[playwright]" """ import asyncio from cloakbrowser.config import ...
73
2,508
CloakBrowser
examples/integrations/scrapling_example.py
.py
"""Scrapling + CloakBrowser: adaptive web scraping with stealth fingerprints. Scrapling handles parsing and element tracking, CloakBrowser handles bot detection. Requires: pip install scrapling[all] cloakbrowser """ import asyncio import json from urllib.request import urlopen from scrapling.fetchers import Stealth...
43
1,133
CloakBrowser
examples/integrations/browser_use_example.py
.py
"""browser-use + CloakBrowser: AI agent with stealth fingerprints. browser-use handles AI agent logic, CloakBrowser handles bot detection. Your agent can now browse sites behind Cloudflare, reCAPTCHA, DataDome. Requires: pip install browser-use cloakbrowser Set OPENAI_API_KEY (or swap for another LLM provider). """ ...
42
1,199
CloakBrowser
examples/integrations/crawl4ai_example.py
.py
"""Crawl4AI + CloakBrowser: LLM-ready web crawling with stealth fingerprints. Crawl4AI handles extraction and markdown conversion, CloakBrowser handles bot detection. Requires: pip install crawl4ai cloakbrowser """ import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig from cloakbrows...
40
1,128
CloakBrowser
examples/integrations/selenium_example.py
.py
"""Selenium + CloakBrowser: use stealth Chromium with Selenium WebDriver. CloakBrowser provides the binary and stealth args. Selenium drives it via ChromeDriver. Requires: pip install selenium cloakbrowser Note: ChromeDriver version must match Chromium 145. pip install chromedriver-autoinstaller or download man...
42
1,122
CloakBrowser
examples/integrations/aws_lambda/lambda_handler.py
.py
"""AWS Lambda handler for one-off stealth-browser invocations. Always runs **headed** via the Xvfb display started by `lambda-entrypoint.sh`. Event schema (all fields except `url` are optional): Launch options (passed to cloakbrowser.launch_context_async): url str required, t...
356
15,086
CloakBrowser
cloakbrowser/download.py
.py
"""Binary download and cache management for cloakbrowser. Downloads the patched Chromium binary on first use, caches it locally. Similar to how Playwright downloads its own bundled Chromium. """ from __future__ import annotations import hashlib import logging import os import shutil import platform import stat impor...
1,269
48,664
CloakBrowser
cloakbrowser/__main__.py
.py
"""CLI for cloakbrowser β€” download and manage the stealth Chromium binary. Usage: python -m cloakbrowser install # Download binary (with progress) python -m cloakbrowser info # Environment + binary diagnostics python -m cloakbrowser doctor # Alias for `info` python -m cloakbrowser up...
698
25,839
CloakBrowser
cloakbrowser/__init__.py
.py
"""cloakbrowser β€” Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. Usage: from cloakbrowser import launch browser = launch() page = browser.new_page() page.goto("https://protected-site.com") browser.close() """ from .bro...
56
1,740
CloakBrowser
cloakbrowser/widevine.py
.py
"""Widevine CDM hint-file seeding for persistent contexts. CloakBrowser's binary is built with Widevine support but ships no CDM (the CDM is a proprietary Google binary we can't redistribute). Users sideload it by copying a ``WidevineCdm/`` directory from a real Chrome install next to the binary (see issue #96). Chro...
129
5,881
CloakBrowser
cloakbrowser/geoip.py
.py
"""GeoIP-based timezone and locale detection from proxy IP. Optional feature β€” requires ``geoip2`` package:: pip install cloakbrowser[geoip] Downloads GeoLite2-City.mmdb (~70 MB) on first use, caches in ``~/.cloakbrowser/geoip/``. Background re-download after 30 days. """ from __future__ import annotations im...
375
13,833
CloakBrowser
cloakbrowser/license.py
.py
"""License validation and caching for CloakBrowser Pro. Handles license key resolution, server validation with local caching, and Pro version checks. """ from __future__ import annotations import hashlib import json import logging import os import re import time import uuid from collections.abc import Mapping from d...
571
21,494
CloakBrowser
cloakbrowser/config.py
.py
"""Stealth configuration and platform detection for cloakbrowser.""" from __future__ import annotations import os import platform import random import re from pathlib import Path # --------------------------------------------------------------------------- # Chromium version shipped with this release. # Different p...
453
18,601
CloakBrowser
cloakbrowser/browser.py
.py
"""Core browser launch functions for cloakbrowser. Provides launch() and launch_async() β€” thin wrappers around Playwright that use our patched stealth Chromium binary instead of stock Chromium. Usage: from cloakbrowser import launch browser = launch() page = browser.new_page() page.goto("https://prot...
1,753
72,593
CloakBrowser
cloakbrowser/human/scroll.py
.py
"""cloakbrowser-human β€” Human-like scrolling via mouse wheel events.""" from __future__ import annotations import math import random import time from typing import Any, Callable, Optional, Tuple from .config import HumanConfig, rand, rand_range, rand_int_range, sleep_ms from .mouse import RawMouse, human_move from ....
206
7,629
CloakBrowser
cloakbrowser/human/mouse.py
.py
"""cloakbrowser-human β€” Human-like mouse movement and clicking.""" from __future__ import annotations import math import random from typing import Any, Protocol, Tuple from .config import HumanConfig, rand, rand_range, rand_int_range, sleep_ms class RawMouse(Protocol): def move(self, x: float, y: float) -> Non...
133
4,226
CloakBrowser
cloakbrowser/human/keyboard.py
.py
"""cloakbrowser-human β€” Human-like keyboard input. Stealth-aware: when a CDP session is provided, shift symbols are typed via CDP Input.dispatchKeyEvent (isTrusted=true, no evaluate stack trace). Falls back to page.evaluate when no CDP session is available. """ from __future__ import annotations import random from t...
190
6,474
CloakBrowser
cloakbrowser/human/__init__.py
.py
"""Human-like behavioral layer for cloakbrowser. Activated via humanize=True in launch() / launch_async(). Patches page methods to use Bezier mouse curves, realistic typing, and smooth scrolling. Stealth-aware (fixes #110): - isInputElement / isSelectorFocused use CDP Isolated Worlds instead of page.evaluate - Sh...
3,128
127,941
CloakBrowser
cloakbrowser/human/actionability.py
.py
"""Playwright-style actionability checks for the humanize layer (sync). Checks: attached, visible, stable, enabled, editable, receives pointer events. Retry loop with backoff matching Playwright internals: [100, 250, 500, 1000]ms. """ from __future__ import annotations import json import logging import time from typ...
434
15,867
CloakBrowser
cloakbrowser/human/stealth_dom.py
.py
"""Isolated-world DOM reads for the humanize layer. The pre-click helpers (``ensure_actionable``, ``scroll_to_element`` geometry, ``check_pointer_events``) read element state and geometry. This module performs those reads inside the CDP isolated execution context (``page._stealth_world``, created via ``Page.createIsol...
220
9,449
CloakBrowser
cloakbrowser/human/actionability_async.py
.py
"""Playwright-style actionability checks for the humanize layer (async). Async mirror of actionability.py β€” same logic, uses asyncio.sleep and await. """ from __future__ import annotations import asyncio import logging import time from typing import Any, FrozenSet, Optional logger = logging.getLogger(__name__) fro...
317
10,681
CloakBrowser
cloakbrowser/human/scroll_async.py
.py
"""cloakbrowser-human β€” Async human-like scrolling via mouse wheel events. Mirrors scroll.py but uses ``await`` for all Playwright calls and ``async_sleep_ms`` instead of ``sleep_ms``. """ from __future__ import annotations import asyncio import math import random import time from typing import Any, Awaitable, Calla...
203
7,726
CloakBrowser
cloakbrowser/human/config.py
.py
"""cloakbrowser-human β€” Configuration and presets. All numeric parameters for human-like behavior are centralized here. Two built-in presets: 'default' (normal human speed) and 'careful' (slower, more cautious). """ from __future__ import annotations import math import random import time from dataclasses import data...
258
8,049
CloakBrowser
cloakbrowser/human/mouse_async.py
.py
"""cloakbrowser-human β€” Async human-like mouse movement and clicking. Mirrors mouse.py but uses ``await`` for all Playwright calls and ``async_sleep_ms`` instead of ``sleep_ms``. """ from __future__ import annotations import math import random from typing import Any, Protocol from .config import HumanConfig, rand, ...
88
3,238
CloakBrowser
cloakbrowser/human/keyboard_async.py
.py
"""cloakbrowser-human β€” Async human-like keyboard input. Mirrors keyboard.py but uses ``await`` for all Playwright calls and ``async_sleep_ms`` instead of ``sleep_ms``. Stealth-aware: when a CDP session is provided, shift symbols are typed via CDP Input.dispatchKeyEvent (isTrusted=true, no evaluate stack trace). """ ...
151
5,441
django-rest-framework
runtests.py
.py
#! /usr/bin/env python3 import os import sys import pytest def split_class_and_function(string): class_string, function_string = string.split('.', 1) return "%s and %s" % (class_string, function_string) def is_function(string): # `True` if it looks like a test function is included in the string. re...
65
1,973
django-rest-framework
tests/test_settings.py
.py
from django.test import TestCase, override_settings from rest_framework.settings import APISettings, api_settings class TestSettings(TestCase): def test_import_error_message_maintained(self): """ Make sure import errors are captured and raised sensibly. """ settings = APISettings(...
83
3,074
django-rest-framework
tests/test_one_to_one_with_inheritance.py
.py
from django.db import models from django.test import TestCase from rest_framework import serializers from tests.models import RESTFrameworkModel # Models from tests.test_multitable_inheritance import ChildModel # Regression test for #4290 class ChildAssociatedModel(RESTFrameworkModel): child_model = models.OneTo...
42
1,255
django-rest-framework
tests/test_views.py
.py
import copy from django.test import TestCase from django.views.decorators.vary import vary_on_headers from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.settings import APISettings, api_settings from rest_framework.test imp...
185
5,799
django-rest-framework
tests/test_status.py
.py
from django.test import TestCase from rest_framework.status import ( is_client_error, is_informational, is_redirect, is_server_error, is_success ) class TestStatus(TestCase): def test_status_categories(self): assert not is_informational(99) assert is_informational(100) assert is_infor...
34
951
django-rest-framework
tests/test_response.py
.py
from django.test import TestCase, override_settings from django.urls import include, path, re_path from rest_framework import generics, routers, serializers, status, viewsets from rest_framework.parsers import JSONParser from rest_framework.renderers import ( BaseRenderer, BrowsableAPIRenderer, JSONRenderer ) from...
291
10,915
django-rest-framework
tests/test_exceptions.py
.py
from django.test import RequestFactory, TestCase from django.utils import translation from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import ( APIException, ErrorDetail, Throttled, _get_error_details, bad_request, server_error ) class ExceptionTestCase(TestCase): de...
108
3,537
django-rest-framework
tests/test_prefetch_related.py
.py
import pytest from django.contrib.auth.models import Group, User from django.test import TestCase from rest_framework import generics, serializers from rest_framework.test import APIRequestFactory factory = APIRequestFactory() class UserSerializer(serializers.ModelSerializer): class Meta: model = User ...
75
2,665
django-rest-framework
tests/test_multitable_inheritance.py
.py
from django.db import models from django.test import TestCase from rest_framework import serializers from tests.models import RESTFrameworkModel # Models class ParentModel(RESTFrameworkModel): name1 = models.CharField(max_length=100) class ChildModel(ParentModel): name2 = models.CharField(max_length=100) ...
68
2,054
django-rest-framework
tests/test_urlpatterns.py
.py
from collections import namedtuple from django.test import TestCase from django.urls import Resolver404, URLResolver, include, path, re_path from django.urls.resolvers import RegexPattern from rest_framework.test import APIRequestFactory from rest_framework.urlpatterns import format_suffix_patterns # A container cla...
197
8,061
django-rest-framework
tests/utils.py
.py
from operator import attrgetter from django.core.exceptions import ObjectDoesNotExist from django.urls import NoReverseMatch class MockObject: def __init__(self, **kwargs): self._kwargs = kwargs for key, val in kwargs.items(): setattr(self, key, val) def __str__(self): kw...
60
1,662
django-rest-framework
tests/test_templates.py
.py
import re from django.shortcuts import render def test_base_template_with_context(): context = {'request': True, 'csrf_token': 'TOKEN'} result = render({}, 'rest_framework/base.html', context=context) assert re.search(r'"csrfToken": "TOKEN"', result.content.decode()) def test_base_template_with_no_cont...
18
601
django-rest-framework
tests/test_generics.py
.py
import pytest from django.db import models from django.http import Http404 from django.shortcuts import get_object_or_404 from django.test import TestCase from rest_framework import generics, renderers, serializers, status from rest_framework.exceptions import ErrorDetail from rest_framework.response import Response f...
716
25,797
django-rest-framework
tests/test_testing.py
.py
import itertools from io import BytesIO from unittest.mock import patch from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.test import TestCase, override_settings from django.urls import path from rest_framework import fields, par...
401
14,459
django-rest-framework
tests/test_routers.py
.py
from collections import namedtuple import pytest from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import TestCase, override_settings from django.urls import include, path, resolve, reverse from rest_framework import permissions, serializers, viewsets from rest_fram...
712
26,834
django-rest-framework
tests/test_parsers.py
.py
import io import math import pytest from django import forms from django.core.files.uploadhandler import ( MemoryFileUploadHandler, TemporaryFileUploadHandler ) from django.http.request import RawPostDataException from django.test import TestCase from rest_framework.exceptions import ParseError from rest_framewor...
179
6,745
django-rest-framework
tests/test_versioning.py
.py
import pytest from django.test import override_settings from django.urls import ResolverMatch, include, path, re_path from rest_framework import serializers, status, versioning from rest_framework.decorators import APIView from rest_framework.relations import PKOnlyObject from rest_framework.response import Response f...
400
15,008
django-rest-framework
tests/test_negotiation.py
.py
import pytest from django.http import Http404 from django.test import TestCase from rest_framework.negotiation import ( BaseContentNegotiation, DefaultContentNegotiation ) from rest_framework.renderers import BaseRenderer from rest_framework.request import Request from rest_framework.test import APIRequestFactory ...
100
3,680
django-rest-framework
tests/models.py
.py
import uuid from django.contrib.auth.models import User from django.db import models from django.db.models import QuerySet from django.db.models.manager import BaseManager from django.utils.translation import gettext_lazy as _ class RESTFrameworkModel(models.Model): """ Base for test models that sets app_lab...
153
5,132
django-rest-framework
tests/test_relations_hyperlink.py
.py
import pytest from django.test import TestCase, override_settings from django.urls import path from rest_framework import serializers from rest_framework.test import APIRequestFactory from tests.models import ( ForeignKeySource, ForeignKeyTarget, ManyToManySource, ManyToManyTarget, NullableForeignKeySource, Nu...
462
26,755
django-rest-framework
tests/test_reverse.py
.py
from django.test import TestCase, override_settings from django.urls import NoReverseMatch, path from rest_framework.reverse import reverse from rest_framework.test import APIRequestFactory from rest_framework.versioning import BaseVersioning factory = APIRequestFactory() def null_view(request): pass urlpatte...
55
1,538
django-rest-framework
tests/test_bound_fields.py
.py
from django.http import QueryDict from rest_framework import serializers from rest_framework.exceptions import ValidationError class TestSimpleBoundField: def test_empty_bound_field(self): class ExampleSerializer(serializers.Serializer): text = serializers.CharField(max_length=100) ...
248
9,796
django-rest-framework
tests/test_middleware.py
.py
from django.contrib.auth.models import User from django.http import HttpRequest from django.test import override_settings from django.urls import include, path from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.authtoken.models import Token from rest_fra...
145
4,685
django-rest-framework
tests/test_metadata.py
.py
import pytest from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.test import TestCase from rest_framework import ( exceptions, metadata, serializers, status, versioning, views ) from rest_framework.renderers import BrowsableAPIRenderer from rest_framewo...
414
14,951
django-rest-framework
tests/test_validation_error.py
.py
from django.test import TestCase from rest_framework import serializers, status from rest_framework.decorators import api_view from rest_framework.exceptions import ValidationError from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.test import APIRequestFa...
112
3,698
django-rest-framework
tests/test_serializer_lists.py
.py
import pytest from django.http import QueryDict from django.utils.datastructures import MultiValueDict from rest_framework import serializers from rest_framework.exceptions import ErrorDetail from tests.models import ( CustomManagerModel, NullableOneToOneSource, OneToOneTarget ) class BasicObject: """ A ...
963
34,523
django-rest-framework
tests/test_requests_client.py
.py
import unittest from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.shortcuts import redirect from django.test import override_settings from django.urls import path from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf...
255
8,756
django-rest-framework
tests/test_relations_pk.py
.py
import pytest from django.test import TestCase from rest_framework import serializers from tests.models import ( ForeignKeySource, ForeignKeySourceWithLimitedChoices, ForeignKeySourceWithQLimitedChoices, ForeignKeyTarget, ManyToManySource, ManyToManyTarget, NullableForeignKeySource, NullableOneToOneSource,...
632
25,530
django-rest-framework
tests/test_description.py
.py
import pytest from django.test import TestCase from rest_framework.compat import apply_markdown from rest_framework.utils.formatting import dedent from rest_framework.views import APIView # We check that docstrings get nicely un-indented. DESCRIPTION = """an example docstring ==================== * list * list anot...
156
4,726
django-rest-framework
tests/test_authtoken.py
.py
import importlib from io import StringIO from unittest.mock import patch import pytest from django.contrib.admin import site from django.contrib.auth.models import User from django.core.management import CommandError, call_command from django.db import IntegrityError from django.test import TestCase, modify_settings ...
160
6,709
django-rest-framework
tests/test_pagination.py
.py
import pytest from django.core.paginator import Paginator as DjangoPaginator from django.db import models from django.test import TestCase from rest_framework import ( exceptions, filters, generics, pagination, serializers, status ) from rest_framework.pagination import PAGE_BREAK, PageLink from rest_framework.req...
1,156
43,492
django-rest-framework
tests/test_write_only_fields.py
.py
from django.test import TestCase from rest_framework import serializers class WriteOnlyFieldTests(TestCase): def setUp(self): class ExampleSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField(write_only=True) self.Serialize...
30
909
django-rest-framework
tests/test_renderers.py
.py
import re from collections.abc import MutableMapping from datetime import datetime from zoneinfo import ZoneInfo import pytest from django.core.cache import cache from django.db import models from django.http.request import HttpRequest from django.test import TestCase, override_settings from django.urls import include...
1,120
40,737
django-rest-framework
tests/test_relations_slug.py
.py
import pytest from django.test import TestCase from rest_framework import serializers from tests.models import ( ForeignKeySource, ForeignKeyTarget, NullableForeignKeySource ) class ForeignKeyTargetSerializer(serializers.ModelSerializer): sources = serializers.SlugRelatedField( slug_field='name', ...
291
12,045
django-rest-framework
tests/test_throttling.py
.py
""" Tests for the throttling implementations in the permissions module. """ import pytest from django.contrib.auth.models import User from django.core.cache import cache from django.core.exceptions import ImproperlyConfigured from django.http import HttpRequest from django.test import TestCase from rest_framework.req...
523
17,078
django-rest-framework
tests/test_lazy_hyperlinks.py
.py
from django.db import models from django.test import TestCase, override_settings from django.urls import path from rest_framework import serializers from rest_framework.renderers import JSONRenderer from rest_framework.templatetags.rest_framework import format_value str_called = False class Example(models.Model): ...
50
1,345
django-rest-framework
tests/test_permissions.py
.py
import base64 import unittest from unittest import mock import pytest from django.conf import settings from django.contrib.auth.models import AnonymousUser, Group, Permission, User from django.db import models from django.test import TestCase from django.urls import ResolverMatch from rest_framework import ( HTTP...
779
32,600
django-rest-framework
tests/test_serializer_nested.py
.py
import pytest from django.db import models from django.http import QueryDict from django.test import TestCase from rest_framework import serializers from rest_framework.compat import postgres_fields from rest_framework.serializers import raise_errors_on_nested_writes class TestNestedSerializer: def setup_method(...
357
12,826
django-rest-framework
tests/test_serializer.py
.py
import inspect import pickle import re from collections import ChainMap from collections.abc import Mapping import pytest from django.db import models from django.test import TestCase from rest_framework import exceptions, fields, relations, serializers from rest_framework.fields import Field from .models import ( ...
832
31,014
django-rest-framework
tests/test_validators.py
.py
import datetime import re from unittest.mock import MagicMock, patch import pytest from django import VERSION as django_version from django.db import DataError, connection, models from django.test import TestCase from rest_framework import serializers from rest_framework.exceptions import ValidationError from rest_fr...
1,242
46,663
django-rest-framework
tests/test_request.py
.py
""" Tests for content parsing, and form-overloaded content parsing. """ import copy import os.path import tempfile import pytest from django.contrib.auth import authenticate, login, logout from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.auth.models import User from django.contri...
442
15,708
django-rest-framework
tests/test_validation.py
.py
import re from django.core.validators import MaxValueValidator, RegexValidator from django.db import models from django.test import TestCase from rest_framework import generics, serializers, status from rest_framework.test import APIRequestFactory factory = APIRequestFactory() # Regression for #666 class Validati...
255
8,215
django-rest-framework
tests/test_templatetags.py
.py
from django.template import Context, Template from django.test import TestCase, override_settings from django.utils.html import urlize from rest_framework.relations import Hyperlink from rest_framework.templatetags import rest_framework from rest_framework.templatetags.rest_framework import ( add_nested_class, add...
317
10,424