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
bottle
test/test_html_helper.py
.py
import unittest from bottle import _parse_http_header class TestHttpUtils(unittest.TestCase): # TODO: Move more of the low level http stuff here. def test_accept_header(self): self.assertEqual(_parse_http_header( 'text/xml, text/whitespace ,' 'application/params;para...
24
707
bottle
test/test_environ.py
.py
# -*- coding: utf-8 -*- ''' Tests for the BaseRequest and BaseResponse objects and their subclasses. ''' import unittest import sys import itertools import bottle from bottle import request, tob, touni, json_dumps, HTTPError, parse_date, CookieError from . import tools import wsgiref.util import base64 from bottle ...
908
38,675
bottle
test/test_exc.py
.py
import bottle from .tools import ServerTestBase class SomeError(Exception): pass class TestAppException(ServerTestBase): def test_no_exc(self): @bottle.route('/') def test(): return 'test' self.assertBody('test', '/') def test_memory_error(self): @bottle.route('/') ...
42
1,135
bottle
test/test_stpl.py
.py
# -*- coding: utf-8 -*- from __future__ import with_statement import unittest from bottle import SimpleTemplate, TemplateError, view, template, touni, tob, html_quote import re, os import traceback from .tools import chdir class TestSimpleTemplate(unittest.TestCase): def assertRenders(self, tpl, to, *args, **vars...
369
13,686
bottle
test/test_jinja2.py
.py
# -*- coding: utf-8 -*- import unittest from bottle import Jinja2Template, jinja2_template, jinja2_view, touni from .tools import warn, chdir class TestJinja2Template(unittest.TestCase): def test_string(self): """ Templates: Jinja2 string""" t = Jinja2Template('start {{var}} end').render(var='va...
74
2,745
bottle
test/test_mako.py
.py
from __future__ import with_statement import unittest from .tools import warn, chdir from bottle import MakoTemplate, mako_template, mako_view, touni class TestMakoTemplate(unittest.TestCase): def test_string(self): """ Templates: Mako string""" t = MakoTemplate('start ${var} end').render(var='var'...
58
2,185
bottle
test/test_fileupload.py
.py
# -*- coding: utf-8 -*- ''' Tests for the FileUpload wrapper. ''' import unittest import sys, os.path import bottle from bottle import FileUpload, BytesIO, tob import tempfile class TestFileUpload(unittest.TestCase): def test_name(self): self.assertEqual(FileUpload(None, 'abc', None).name, 'abc') def...
69
2,478
bottle
test/test_plugins.py
.py
# -*- coding: utf-8 -*- import unittest from . import tools from bottle import HTTPResponse, HTTPError, json_dumps class MyPlugin(object): def __init__(self): self.app = None self.add_args = {} self.add_content = '' def setup(self, app): self.app = app def apply(self, fu...
222
7,526
bottle
test/tools.py
.py
# -*- coding: utf-8 -*- from __future__ import with_statement import os import bottle import sys import unittest import wsgiref import wsgiref.util import wsgiref.validate import warnings import mimetypes import uuid from bottle import tob, BytesIO def warn(msg): sys.stderr.write('WARNING: %s\n' % msg.strip())...
178
6,256
bottle
test/test_importhook.py
.py
# -*- coding: utf-8 -*- import unittest import sys, os import bottle class TestImportHooks(unittest.TestCase): def make_module(self, name, **args): mod = sys.modules.setdefault(name, bottle.new_module(name)) mod.__file__ = '<virtual %s>' % name mod.__dict__.update(**args) return mo...
41
1,290
bottle
test/test_wsgi.py
.py
# -*- coding: utf-8 -*- from __future__ import with_statement import bottle from .tools import ServerTestBase, chdir from bottle import tob, touni, HTTPResponse class TestWsgi(ServerTestBase): ''' Tests for WSGI functionality, routing and output casting (decorators) ''' def test_get(self): """ WSGI: G...
545
18,480
bottle
test/test_outputfilter.py
.py
# -*- coding: utf-8 -*- '''Everything returned by Bottle()._cast() MUST be WSGI compatiple.''' import unittest import bottle from bottle import tob, touni from .tools import ServerTestBase, tobs, warn USING_UJSON = True try: import ujson except ImportError: USING_UJSON = False class TestOutputFilter(ServerT...
198
6,298
falcon
setup.py
.py
import glob import os from os import path import platform from setuptools import setup try: from Cython.Build import build_ext as _cy_build_ext from Cython.Distutils.extension import Extension as _cy_Extension HAS_CYTHON = True except ImportError: _cy_build_ext = _cy_Extension = None HAS_CYTHON =...
100
3,103
falcon
tools/towncrier_draft.py
.py
#!/usr/bin/env python import argparse import atexit import pathlib import subprocess import toml HERE = pathlib.Path(__file__).resolve().parent ROOT = HERE.parent def _write_changelog(target, data): with open(ROOT / target, 'wb') as rst: rst.write(data) def get_target_filename(): with open(ROOT /...
75
1,758
falcon
tools/test_dist.py
.py
#!/usr/bin/env python import argparse import logging import pathlib import subprocess import sys import tempfile logging.basicConfig( format='[test_dist.py] %(asctime)s [%(levelname)s] %(message)s', level=logging.INFO ) FALCON_ROOT = pathlib.Path(__file__).resolve().parent.parent REQUIREMENTS = FALCON_ROOT / 're...
72
2,462
falcon
tools/clean.py
.py
#!/usr/bin/env python import argparse import pathlib CLEAN_EXTENSIONS = frozenset({'.c', '.pyc', '.so'}) def clean(root): for path in root.iterdir(): if path.is_file() and path.suffix in CLEAN_EXTENSIONS: path.unlink() elif path.is_dir(): clean(path) if __name__ == '__m...
25
598
falcon
tools/sed_coverage_rc.py
.py
#!/usr/bin/env python """Patch .coveragerc to drop some 3.10-specific pragmas.""" import pathlib import sys HERE = pathlib.Path(__file__).resolve().parent ROOT = HERE.parent DIRECTIVES = ( ' pragma: no py39,py310 cover\n', ' pragma: no py311 cover\n', ) def sed_coverage_rc(): version_short = 'py{...
38
824
falcon
tools/add_contributors.py
.py
#!/usr/bin/env python import argparse import pathlib import re import requests import toml HERE = pathlib.Path(__file__).resolve().parent ROOT = HERE.parent FALCON_CREATOR = 'kgriffs' FALCON_REPOSITORY_API = 'https://api.github.com/repos/falconry/falcon' STABLE_RELEASE_TAG = r'^\d+\.\d+\.\d+(\.post\d+)?$' AUTHORS...
178
5,487
falcon
tools/tox_sdist.py
.py
#!/usr/bin/env python import argparse import atexit import logging import pathlib import shutil import subprocess import sys import tarfile import tempfile logging.basicConfig( format='[tox_sdist.py] %(asctime)s [%(levelname)s] %(message)s', level=logging.INFO ) HERE = pathlib.Path(__file__).resolve().parent DIST...
73
1,935
falcon
tools/check_dist.py
.py
#!/usr/bin/env python import argparse import pathlib import re import sys HERE = pathlib.Path(__file__).resolve().parent FALCON_ROOT = HERE.parent DIST = FALCON_ROOT / 'dist' CHANGELOGS = FALCON_ROOT / 'docs' / 'changes' RELEASE_STABLE_VERSION_PATTERN = re.compile(r'^(\d+)\.(\d+).(\d+)$') RELEASE_META_PATTERN = re.c...
114
3,376
falcon
docs/conf.py
.py
# Copyright 2014-2026 by Falcon Contributors. # # 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...
252
8,441
falcon
docs/ext/private_args.py
.py
# Copyright 2021 by Kurt Griffiths # # 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 writ...
41
1,288
falcon
docs/ext/rfc.py
.py
# Copyright 2016 by Rackspace Hosting, Inc. # # 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 t...
65
1,834
falcon
docs/ext/cibuildwheel.py
.py
# Copyright 2024-2026 by Vytautas Liuolia. # # 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...
157
5,461
falcon
docs/ext/doorway.py
.py
# Copyright 2016 by Rackspace Hosting, Inc. # # 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 t...
37
1,318
falcon
docs/ext/falcon_releases.py
.py
# Copyright 2025-2026 by Vytautas Liuolia. # # 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...
235
7,324
falcon
docs/ext/newsfragments.py
.py
# Copyright 2026 by Vytautas Liuolia. # # 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 w...
94
3,265
falcon
docs/ext/autodoc_customizations.py
.py
"""Customizations to the autodoc functionalities""" import sphinx.ext.autodoc as ad def setup(app): # avoid adding "alias of xyz" ad.GenericAliasMixin.update_content = ad.DataDocumenterMixinBase.update_content return {'parallel_read_safe': True}
11
262
falcon
docs/ext/workarounds.py
.py
# Copyright 2025-2026 by Vytautas Liuolia. # # 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...
58
1,701
falcon
tests/test_query_params.py
.py
from datetime import date from datetime import datetime from datetime import timezone import json from uuid import UUID import pytest import falcon from falcon.errors import HTTPInvalidParam from falcon.errors import HTTPMissingParam from falcon.errors import MediaMalformedError import falcon.testing as testing from ...
1,282
50,279
falcon
tests/test_wsgiref_inputwrapper_with_size.py
.py
import json import falcon from falcon import testing class TypeResource(testing.SimpleTestResource): """A simple resource to return the posted request body.""" @falcon.before(testing.capture_responder_args) def on_post(self, req, resp, **kwargs): resp.status = falcon.HTTP_200 # NOTE(mast...
34
1,186
falcon
tests/test_response.py
.py
from io import BytesIO from unittest.mock import MagicMock import pytest from falcon import MEDIA_TEXT from falcon import ResponseOptions from falcon.util.deprecation import AttributeRemovedError @pytest.fixture() def resp(asgi, util): return util.create_resp(asgi) def test_response_set_content_type_set(resp)...
107
3,218
falcon
tests/test_sink_and_static.py
.py
import pytest import falcon from falcon import testing def sink(req, resp, **kw): resp.text = 'sink' async def sink_async(req, resp, **kw): resp.text = 'sink' @pytest.fixture def client(asgi, util, tmp_path): file = tmp_path / 'file.txt' file.write_text('foo bar') def make(sink_before_static...
48
1,187
falcon
tests/test_uri_templates.py
.py
"""Application tests for URI templates using simulate_get(). These tests differ from those in test_default_router in that they are a collection of sanity-checks that exercise the full framework code path via simulate_get(), vs. probing the router directly. """ from datetime import datetime from datetime import timezo...
605
17,196
falcon
tests/test_default_router.py
.py
import textwrap from types import MethodType import pytest from falcon import testing from falcon.routing import DefaultRouter def client(asgi, util): return testing.TestClient(util.create_app(asgi)) @pytest.fixture def router(): router = DefaultRouter() router.add_route('/repos', ResourceWithId(1)) ...
938
29,213
falcon
tests/test_request_attrs.py
.py
import datetime import itertools import pytest import falcon from falcon.request import Request from falcon.request import RequestOptions from falcon.request_helpers import _parse_etags import falcon.testing as testing import falcon.uri from falcon.util import DeprecatedWarning from falcon.util.structures import ETag...
1,098
37,133
falcon
tests/test_request_access_route.py
.py
import pytest from falcon.request import Request import falcon.testing as testing def test_remote_addr_default(asgi, util): req = util.create_req(asgi) assert req.remote_addr == '127.0.0.1' def test_remote_addr_non_default(asgi, util): client_ip = '10.132.0.5' req = util.create_req(asgi, remote_add...
139
3,530
falcon
tests/test_testing.py
.py
import io import pytest import falcon from falcon import App from falcon import status_codes from falcon import testing from falcon.util.sync import async_to_sync try: import msgpack except ImportError: msgpack = None class CustomCookies: def items(self): return [('foo', 'bar'), ('baz', 'foo')]...
356
9,797
falcon
tests/test_custom_router.py
.py
import pytest import falcon from falcon import testing def test_custom_router_add_route_should_be_used(asgi, util): check = [] class CustomRouter: def add_route(self, uri_template, *args, **kwargs): check.append(uri_template) def find(self, uri): pass app = util...
145
4,301
falcon
tests/test_wsgi_errors.py
.py
import io import pytest import falcon from falcon import testing unicode_message = 'Unicode: \x80' @pytest.fixture def client(): app = falcon.App() tehlogger = LoggerResource() app.add_route('/logger', tehlogger) return testing.TestClient(app) class LoggerResource: def on_get(self, req, resp...
46
1,061
falcon
tests/test_cmd_inspect_app.py
.py
from argparse import Namespace import contextlib import io import sys import pytest from falcon import App from falcon import inspect import falcon.asgi from falcon.cmd import inspect_app _WIN32 = sys.platform.startswith('win') # NOTE(vytas): This is not the cleanest way to import as we lack __init__.py, # but it...
207
6,179
falcon
tests/test_wsgi_interface.py
.py
import re import sys import falcon import falcon.testing as testing class TestWSGIInterface: def test_srmock(self): mock = testing.StartResponseMock() mock(falcon.HTTP_200, ()) assert mock.status == falcon.HTTP_200 assert mock.exc_info is None mock = testing.StartRespons...
55
1,480
falcon
tests/test_python_version_requirements.py
.py
import falcon def test_asgi(): # TODO(vytas): consider removing this file completely. # Its only purpose left is verifying that ASGI_SUPPORTED is still # available for compatibility. assert falcon.ASGI_SUPPORTED
9
234
falcon
tests/test_middleware.py
.py
import json import pytest import falcon import falcon.errors import falcon.testing as testing from falcon.util.deprecation import DeprecatedWarning from falcon.util.misc import _utcnow _EXPECTED_BODY = {'status': 'ok'} context = {'executed_methods': []} # type: ignore TEST_ROUTE = '/test_path' class CaptureRespo...
1,038
37,215
falcon
tests/test_response_media.py
.py
import json import pytest import falcon from falcon import errors from falcon import media from falcon import testing @pytest.fixture(scope='session') def msgpack(): return pytest.importorskip('msgpack') @pytest.fixture def client(): return create_client() def create_client(handlers=None): res = tes...
220
5,377
falcon
tests/test_request_media.py
.py
import json import pytest import falcon from falcon import errors from falcon import media from falcon import testing from falcon import util import falcon.asgi @pytest.fixture(scope='session') def msgpack(): return pytest.importorskip('msgpack') def create_client(asgi, handlers=None, resource=None): if n...
396
11,620
falcon
tests/test_sinks.py
.py
import re import pytest import falcon import falcon.testing as testing class Proxy: def forward(self, req): return falcon.HTTP_503 class Sink: def __init__(self): self._proxy = Proxy() def __call__(self, req, resp, **kwargs): resp.status = self._proxy.forward(req) self...
176
5,497
falcon
tests/test_error.py
.py
import pytest import falcon import falcon.errors as errors import falcon.status_codes as status @pytest.mark.parametrize( 'err, title', [ (falcon.HTTPBadRequest, status.HTTP_400), (falcon.HTTPUnauthorized, status.HTTP_401), (falcon.HTTPForbidden, status.HTTP_403), (falcon.HTTP...
359
10,887
falcon
tests/test_headers.py
.py
from collections import defaultdict from datetime import datetime import pytest import falcon from falcon import testing from falcon.util.deprecation import DeprecatedWarning from falcon.util.misc import _utcnow SAMPLE_BODY = testing.rand_string(0, 128 * 1024) @pytest.fixture def client(asgi, util): app = util...
1,061
37,459
falcon
tests/test_hello.py
.py
import io import pytest import falcon from falcon import testing @pytest.fixture def client(): return testing.TestClient(falcon.App()) # NOTE(kgriffs): Concept from Gunicorn's source (wsgi.py) class FileWrapper: def __init__(self, file_like, block_size=8192): self.file_like = file_like sel...
250
8,043
falcon
tests/test_uri_converters.py
.py
from datetime import datetime from datetime import timezone import math import string import uuid import pytest from falcon.routing import converters _TEST_UUID = uuid.uuid4() _TEST_UUID_STR = str(_TEST_UUID) _TEST_UUID_STR_SANS_HYPHENS = _TEST_UUID_STR.replace('-', '') def _as_params(*values, prefix=''): # NO...
183
5,422
falcon
tests/test_boundedstream.py
.py
import io import pytest from falcon.stream import BoundedStream from falcon.util.deprecation import DeprecatedWarning @pytest.fixture def bounded_stream(): return BoundedStream(io.BytesIO(), 1024) def test_not_writable(bounded_stream): assert not bounded_stream.writable() with pytest.raises(OSError):...
30
725
falcon
tests/test_inspect.py
.py
from functools import partial import os import pathlib import sys import _inspect_fixture as i_f import pytest import falcon from falcon import inspect from falcon import routing import falcon.asgi HERE = pathlib.Path(__file__).resolve().parent def get_app(asgi, cors=True, **kw): if asgi: return falcon...
702
25,557
falcon
tests/test_response_context.py
.py
import pytest import falcon import falcon.asgi @pytest.fixture(params=[True, False], ids=['asgi.Response', 'Response']) def resp_type(request): if request.param: return falcon.asgi.Response return falcon.Response class TestResponseContext: def test_default_response_context(self, resp_type): ...
55
1,556
falcon
tests/test_status_codes.py
.py
import http import sys import pytest from falcon import status_codes class TestStatusCodes: @pytest.mark.skipif( sys.version_info < (3, 13), reason='Outdated http statuses definitions' ) @pytest.mark.parametrize('status', status_codes.__all__) def test_statuses_are_in_compliance_with_http_fr...
28
925
falcon
tests/test_typing.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import Any from uuid import UUID import falcon import falcon.asgi import falcon.testing @dataclass class RichContext: userid: UUID | None = None role: str = 'anonymous' comment: str = 'no comment' class FancyRequest(falco...
223
6,517
falcon
tests/test_mediatypes.py
.py
import itertools import pytest from falcon import errors from falcon.util import mediatypes @pytest.mark.parametrize( 'value,expected', [ ('', ('', {})), ('strange', ('strange', {})), ('text/plain', ('text/plain', {})), ('text/plain ', ('text/plain', {})), (' text/pla...
284
8,885
falcon
tests/test_cookies.py
.py
from datetime import datetime from datetime import timedelta from datetime import timezone from http import cookies as http_cookies import re import warnings import pytest import falcon import falcon.testing as testing from falcon.util import http_date_to_dt from falcon.util.deprecation import DeprecatedWarning from ...
571
17,856
falcon
tests/test_cors_middleware.py
.py
from pathlib import Path import pytest import falcon from falcon import testing @pytest.fixture def client(asgi, util): app = util.create_app(asgi) return testing.TestClient(app) @pytest.fixture(scope='function') def cors_client(asgi, util): # NOTE(kgriffs): Disable wrapping to test that built-in midd...
338
13,755
falcon
tests/dump_asgi.py
.py
import asyncio import time async def _say_hi(): print(f'[{time.time()}] Hi!') async def app(scope, receive, send): await send( { 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'application/json'], ], ...
27
513
falcon
tests/test_examples.py
.py
import pytest import falcon.testing as testing @pytest.fixture(scope='session') def httpx(): return pytest.importorskip('httpx') @pytest.fixture(scope='session') def requests(): return pytest.importorskip('requests') def test_quote(util): quote = util.load_module('examples/quote.py') resp = test...
81
2,212
falcon
tests/test_validators.py
.py
import typing # NOQA: F401 import pytest import falcon from falcon import testing from falcon.media import validators @pytest.fixture(scope='session') def jsonschema(): return pytest.importorskip('jsonschema') _VALID_MEDIA = {'message': 'something'} _INVALID_MEDIA = {} # type: typing.Dict[str, str] _TEST_...
181
5,269
falcon
tests/test_app_initializers.py
.py
import pytest import falcon from falcon import media from falcon import testing class MediaResource: def on_get(self, req, resp): resp.media = {'foo': 'bar'} def on_post(self, req, resp): resp.media = req.media class PlainTextHandler(media.BaseHandler): def serialize(self, media, conte...
55
1,432
falcon
tests/test_request_context.py
.py
import pytest from falcon.request import Request import falcon.testing as testing class TestRequestContext: def test_default_request_context( self, ): req = testing.create_req() req.context.hello = 'World' assert req.context.hello == 'World' assert req.context['hello'...
55
1,680
falcon
tests/_inspect_fixture.py
.py
from falcon.routing import CompiledRouter class MyRouter(CompiledRouter): pass class MyResponder: def on_get(self, req, res): pass def on_post(self, req, res): pass def on_delete(self, req, res): pass def on_get_id(self, req, res, id): pass def on_put_id(s...
111
1,798
falcon
tests/test_after_hooks.py
.py
import functools import json import typing import pytest import falcon from falcon import testing from falcon._typing import Resource import falcon.hooks from falcon.request import Request from falcon.response import Response # -------------------------------------------------------------------- # Fixtures # -------...
529
14,624
falcon
tests/test_slots.py
.py
import pytest import falcon import falcon.asgi import falcon.testing as testing class TestSlots: def test_slots_request(self, asgi): req = testing.create_asgi_req() if asgi else testing.create_req() try: req.doesnt = 'exist' except AttributeError: pytest.fail('Una...
27
671
falcon
tests/test_alias.py
.py
# NOTE(myusko): A file contains temporary tests for API alias # and it will be deleted once the API alias will be removed import pytest import falcon import falcon.testing as testing from falcon.util.deprecation import DeprecatedWarning class CookieResource: def on_get(self, req, resp): resp.set_cookie(...
48
1,314
falcon
tests/test_request_body.py
.py
import io from wsgiref.validate import InputWrapper import pytest import falcon import falcon.request from falcon.stream import BoundedStream import falcon.testing as testing SIZE_1_KB = 1024 @pytest.fixture def resource(): return testing.SimpleTestResource() @pytest.fixture def client(): app = falcon.Ap...
169
5,822
falcon
tests/test_request_forwarded.py
.py
import pytest def test_no_forwarded_headers(asgi, util): req = util.create_req( asgi, host='example.com', path='/languages', root_path='backoffice' ) assert req.forwarded is None assert req.forwarded_uri == req.uri assert req.forwarded_uri == 'http://example.com/backoffice/languages' ...
202
6,537
falcon
tests/test_media_urlencoded.py
.py
import io import pytest import falcon from falcon import media from falcon import testing def test_deserialize_empty_form(): handler = media.URLEncodedFormHandler() stream = io.BytesIO(b'') assert handler.deserialize(stream, falcon.MEDIA_URLENCODED, 0) == {} def test_deserialize_invalid_unicode(): ...
84
2,310
falcon
tests/test_media_handlers.py
.py
from functools import partial import io import json import platform import pytest import falcon from falcon import media from falcon import testing import falcon.asgi from falcon.asgi.stream import BoundedStream from falcon.constants import MEDIA_JSON from falcon.constants import MEDIA_YAML msgspec = None mujson = N...
521
15,923
falcon
tests/test_recipes.py
.py
import types import unittest.mock import pytest import falcon import falcon.testing class TestMultipartMixed: """Test parsing example from the now-obsolete RFC 1867: --AaB03x Content-Disposition: form-data; name="field1" Joe Blow --AaB03x Content-Disposition: form-data; name="docs" Con...
320
10,939
falcon
tests/test_error_handlers.py
.py
import pytest import falcon from falcon import constants from falcon import testing import falcon.asgi from falcon.util.deprecation import DeprecatedWarning def capture_error(req, resp, ex, params): resp.status = falcon.HTTP_723 resp.text = f'error: {str(ex)}' async def capture_error_async(*args): capt...
350
11,224
falcon
tests/test_before_hooks.py
.py
import functools import io import json import pytest import falcon import falcon.hooks import falcon.testing as testing def validate(req, resp, resource, params): assert resource raise falcon.HTTPBadRequest( title='Invalid thing', description='Your thing was not formatted correctly.' ) def val...
642
18,363
falcon
tests/test_compiled_router.py
.py
from threading import Barrier from threading import Thread from time import sleep from unittest.mock import MagicMock import pytest from falcon.routing import compiled from falcon.routing import CompiledRouter from falcon.routing import CompiledRouterOptions def test_find_src(monkeypatch): called = False fi...
148
3,548
falcon
tests/test_buffered_reader.py
.py
import io import pytest from falcon.errors import DelimiterError from falcon.util import BufferedReader class WouldHang(RuntimeError): pass class GlitchyStream(io.BytesIO): def read(self, size=None): if size is None or size == -1: raise WouldHang('unbounded read()') result = s...
362
9,318
falcon
tests/test_request_query_string_media.py
.py
from urllib.parse import quote import pytest import falcon from falcon import errors from falcon import testing class CaptureQueryStringMedia: """Resource that captures the deserialized query string media.""" def on_get(self, req, resp): self.captured_media = req.get_query_string_as_media() de...
325
11,327
falcon
tests/dump_wsgi.py
.py
def application(environ, start_response): # wsgi_errors = environ['wsgi.errors'] start_response('200 OK', [('Content-Type', 'text/plain')]) body = '\n{\n' for key, value in environ.items(): # if isinstance(value, str): body += f' "{key}": "{value}",\n' body += '}\n\n' if n...
30
633
falcon
tests/test_http_method_routing.py
.py
from contextlib import nullcontext from functools import wraps from wsgiref.validate import WSGIWarning import pytest import falcon import falcon.constants import falcon.testing as testing # RFC 7231, 5789 methods HTTP_METHODS = [ 'CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'P...
344
10,050
falcon
tests/test_http_custom_method_routing.py
.py
import importlib import os import wsgiref.validate import pytest import falcon from falcon import testing import falcon.constants from falcon.routing import util FALCON_CUSTOM_HTTP_METHODS = ['FOO', 'BAR'] @pytest.fixture def resource_things(): return ThingsResource() @pytest.fixture def cleanup_constants():...
129
3,514
falcon
tests/test_httperror.py
.py
import datetime import http import json import wsgiref.validate import xml.etree.ElementTree as et import pytest import falcon from falcon.constants import MEDIA_JSON from falcon.constants import MEDIA_XML from falcon.constants import MEDIA_YAML from falcon.media import BaseHandler import falcon.testing as testing fr...
1,137
40,573
falcon
tests/test_cython.py
.py
import io import pytest import falcon.uri import falcon.util class TestCythonized: def test_imported_from_c_modules(self, util): if not util.HAS_CYTHON: pytest.skip(reason='Cython not installed') assert 'cyfunction' in str(falcon.uri.parse_query_string) def test_stream_has_priv...
23
570
falcon
tests/test_wsgi.py
.py
import multiprocessing import os import os.path import platform import time import wsgiref.simple_server import pytest import falcon import falcon.testing as testing _HERE = os.path.abspath(os.path.dirname(__file__)) _SERVER_HOST = 'localhost' _SIZE_1_KB = 1024 _STARTUP_TIMEOUT = 10 _START_ATTEMPTS = 3 @pytest.mar...
171
5,761
falcon
tests/test_httpstatus.py
.py
import http import pytest import falcon from falcon.http_status import HTTPStatus import falcon.testing as testing @pytest.fixture() def client(asgi, util): app = util.create_app(asgi) app.add_route('/status', TestStatusResource()) return testing.TestClient(app) @pytest.fixture() def hook_test_client(...
279
9,171
falcon
tests/test_wsgi_servers.py
.py
import hashlib import os import random import subprocess import sys import time import pytest from falcon import testing @pytest.fixture(scope='session') def requests(): return pytest.importorskip('requests') _HERE = os.path.abspath(os.path.dirname(__file__)) _SERVER_HOST = '127.0.0.1' _SIZE_1_KB = 1024 _SIZE...
313
8,839
falcon
tests/test_options.py
.py
import pytest from falcon.request import RequestOptions from falcon.util import deprecation class TestRequestOptions: def test_option_defaults(self): options = RequestOptions() assert options.keep_blank_qs_values assert not options.auto_parse_form_urlencoded assert not options.au...
46
1,323
falcon
tests/test_media_multipart.py
.py
import io import itertools import os import random import pytest import falcon from falcon import media from falcon import testing from falcon.media.multipart import MultipartParseOptions from falcon.util import BufferedReader @pytest.fixture(scope='session') def msgpack(): return pytest.importorskip('msgpack')...
933
29,884
falcon
tests/test_static.py
.py
import errno import io import os import pathlib import posixpath from unittest import mock import pytest import falcon from falcon.routing import StaticRoute from falcon.routing import StaticRouteAsync from falcon.routing.static import _BoundedFile import falcon.testing as testing def normalize_path(path): # NO...
760
23,748
falcon
tests/test_utils.py
.py
from datetime import datetime from datetime import timedelta from datetime import timezone import functools import http import inspect import itertools import json import random import sys from urllib.parse import quote from urllib.parse import unquote_plus import pytest import falcon from falcon import media from fa...
1,642
55,270
falcon
tests/_wsgi_test_app.py
.py
import hashlib import io import os.path import falcon HERE = os.path.abspath(os.path.dirname(__file__)) class Forms: def on_post(self, req, resp): parts = {} for part in req.media: # NOTE(vytas): SHA1 is no longer recommended for cryptographic # purposes, but here we a...
54
1,379
falcon
tests/test_response_body.py
.py
import pytest import falcon from falcon import testing @pytest.fixture def resp(asgi, util): return util.create_resp(asgi) def test_append_body(resp): text = 'Hello beautiful world! ' resp.text = '' for token in text.split(): resp.text += token resp.text += ' ' assert resp.tex...
123
3,463
falcon
tests/test_redirects.py
.py
import pytest import falcon import falcon.testing as testing @pytest.fixture def client(asgi, util): app = util.create_app(asgi) resource = RedirectingResource() app.add_route('/', resource) return testing.TestClient(app) @pytest.fixture def client_exercising_headers(asgi, util): app = util.c...
106
3,324
falcon
tests/conftest.py
.py
import contextlib import functools import http.client import importlib.util import inspect import json import os import pathlib import sys import urllib.parse import pytest import falcon import falcon.asgi import falcon.testing import falcon.util try: import cython # noqa has_cython = True except ImportErr...
216
5,966
falcon
tests/asgi/_asgi_test_app.py
.py
import asyncio from collections import Counter import hashlib import platform import sys import time import falcon import falcon.asgi import falcon.errors import falcon.util SSE_TEST_MAX_DELAY_SEC = 1 _WIN32 = sys.platform.startswith('win') _X86_64 = platform.machine() == 'x86_64' class Things: def __init__(sel...
324
10,562
falcon
tests/asgi/test_misc.py
.py
# misc test for 100% coverage from unittest.mock import MagicMock import pytest from falcon.asgi import App from falcon.http_error import HTTPError from falcon.http_status import HTTPStatus async def test_http_status_not_impl(): app = App() with pytest.raises(NotImplementedError): await app._http_s...
30
779
falcon
tests/asgi/test_asgi_servers.py
.py
import asyncio from contextlib import contextmanager import hashlib import os import platform import random import signal import subprocess import sys import time import pytest from falcon import testing from . import _asgi_test_app @pytest.fixture(scope='session') def httpx(): return pytest.importorskip('http...
666
22,121
falcon
tests/asgi/test_asgi_conductor.py
.py
import pytest import falcon from falcon import testing from falcon.asgi import App async def test_default_headers(): class Resource: async def on_get(self, req, resp): resp.set_header('the-answer', req.get_header('the-answer')) app = App() app.add_route('/', Resource()) client = ...
85
2,541
falcon
tests/asgi/test_ws.py
.py
import asyncio from collections import deque from contextlib import nullcontext import functools import os import pytest import falcon from falcon import media from falcon import testing from falcon.asgi import App from falcon.asgi.ws import _WebSocketState as ServerWebSocketState from falcon.asgi.ws import WebSocket...
1,530
48,641
falcon
tests/asgi/test_sync.py
.py
import asyncio import time import pytest from falcon import testing from falcon.asgi import App import falcon.util @pytest.mark.slow def test_sync_helpers(): safely_values = [] unsafely_values = [] shirley_values = [] class SomeResource: async def on_get(self, req, resp): safely...
130
4,382