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
httpie
httpie/manager/core.py
.py
import argparse from typing import Optional from httpie.context import Environment from httpie.status import ExitStatus from httpie.manager.cli import missing_subcommand, parser from httpie.manager.tasks import CLI_TASKS MSG_COMMAND_CONFUSION = '''\ This command is only for managing HTTPie plugins. To send a request,...
43
1,142
httpie
httpie/manager/tasks/__init__.py
.py
from httpie.manager.tasks.sessions import cli_sessions from httpie.manager.tasks.export_args import cli_export_args from httpie.manager.tasks.plugins import cli_plugins from httpie.manager.tasks.check_updates import cli_check_updates CLI_TASKS = { 'sessions': cli_sessions, 'export-args': cli_export_args, '...
12
384
httpie
httpie/manager/tasks/check_updates.py
.py
import argparse from httpie.context import Environment from httpie.status import ExitStatus from httpie.internal.update_warnings import fetch_updates, get_update_status def cli_check_updates(env: Environment, args: argparse.Namespace) -> ExitStatus: fetch_updates(env, lazy=False) env.stdout.write(get_update_s...
11
362
httpie
httpie/manager/tasks/sessions.py
.py
import argparse from httpie.sessions import SESSIONS_DIR_NAME, get_httpie_session from httpie.status import ExitStatus from httpie.context import Environment from httpie.legacy import v3_1_0_session_cookie_format, v3_2_0_session_header_format from httpie.manager.cli import missing_subcommand, parser from httpie.utils ...
87
2,686
httpie
httpie/manager/tasks/plugins.py
.py
import argparse import os import textwrap import re import shutil from collections import defaultdict from contextlib import suppress from pathlib import Path from typing import List, Optional, Tuple from httpie.manager.compat import PipError, run_pip from httpie.manager.cli import parser, missing_subcommand from http...
249
8,526
httpie
httpie/manager/tasks/export_args.py
.py
import argparse import json from httpie.cli.definition import options from httpie.cli.options import to_data from httpie.output.writer import write_raw_data from httpie.status import ExitStatus from httpie.context import Environment FORMAT_TO_CONTENT_TYPE = { 'json': 'application/json' } def cli_export_args(en...
28
701
httpie
httpie/cli/options.py
.py
import argparse import textwrap import typing from dataclasses import dataclass, field from enum import Enum, auto from typing import Any, Optional, Dict, List, Tuple, Type, TypeVar from httpie.cli.argparser import HTTPieArgumentParser from httpie.cli.utils import Manual, LazyChoices class Qualifiers(Enum): OPTI...
250
7,732
httpie
httpie/cli/utils.py
.py
import argparse from typing import Any, Callable, Generic, Iterator, Iterable, Optional, TypeVar T = TypeVar('T') class Manual(argparse.Action): def __init__( self, option_strings, dest=argparse.SUPPRESS, default=argparse.SUPPRESS, help=None ): super().__init__...
80
2,151
httpie
httpie/cli/argparser.py
.py
import argparse import errno import os import re import sys from argparse import RawDescriptionHelpFormatter from textwrap import dedent from urllib.parse import urlsplit from requests.utils import get_netrc_auth from .argtypes import ( AuthCredentials, SSLCredentials, KeyValueArgType, PARSED_DEFAULT_FORMAT_O...
614
23,136
httpie
httpie/cli/exceptions.py
.py
class ParseError(Exception): pass
3
38
httpie
httpie/cli/argtypes.py
.py
import argparse import getpass import os import sys from copy import deepcopy from typing import List, Optional, Union from .constants import DEFAULT_FORMAT_OPTIONS, SEPARATOR_CREDENTIALS from ..sessions import VALID_SESSION_NAME_PATTERN class KeyValueArg: """Base key-value pair parsed from CLI.""" def __in...
276
7,991
httpie
httpie/cli/dicts.py
.py
from collections import OrderedDict from multidict import MultiDict, CIMultiDict class BaseMultiDict(MultiDict): """ Base class for all MultiDicts. """ class HTTPHeadersDict(CIMultiDict, BaseMultiDict): """ Headers are case-insensitive and multiple values are supported through the `add()` A...
95
2,317
httpie
httpie/cli/constants.py
.py
"""Parsing and processing of CLI input (args, auth credentials, files, stdin). """ import enum import re URL_SCHEME_RE = re.compile(r'^[a-z][a-z0-9.+-]*://', re.IGNORECASE) HTTP_POST = 'POST' HTTP_GET = 'GET' HTTP_OPTIONS = 'OPTIONS' # Various separators used in args SEPARATOR_HEADER = ':' SEPARATOR_HEADER_EMPTY =...
135
3,246
httpie
httpie/cli/definition.py
.py
from __future__ import annotations import os import textwrap from argparse import FileType from httpie import __doc__, __version__ from httpie.cli.argtypes import (KeyValueArgType, SessionNameValidator, SSLCredentials, readable_file_arg, response_chars...
957
29,143
httpie
httpie/cli/requestitems.py
.py
import os import functools from typing import Callable, Dict, IO, List, Optional, Tuple, Union from .argtypes import KeyValueArg from .constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_GROUP_NESTED_JSON_ITEMS, SEPARATOR_DATA_RAW...
231
7,546
httpie
httpie/cli/nested_json/parse.py
.py
from typing import Iterator from .errors import NestedJSONSyntaxError from .tokens import ( EMPTY_STRING, BACKSLASH, TokenKind, OPERATORS, SPECIAL_CHARS, LITERAL_TOKENS, Token, PathAction, Path, ) __all__ = [ 'parse', 'assert_cant_happen', ] def parse(source: str) -> Ite...
194
5,431
httpie
httpie/cli/nested_json/errors.py
.py
from typing import Optional from .tokens import Token, HIGHLIGHTER class NestedJSONSyntaxError(ValueError): def __init__( self, source: str, token: Optional[Token], message: str, message_kind: str = 'Syntax', ) -> None: self.source = source self.token =...
28
745
httpie
httpie/cli/nested_json/__init__.py
.py
""" A library for parsing the HTTPie nested JSON key syntax and constructing the resulting objects. <https://httpie.io/docs/cli/nested-json> It has no dependencies. """ from .interpret import interpret_nested_json, unwrap_top_level_list_if_needed from .errors import NestedJSONSyntaxError from .tokens import EMPTY_ST...
21
497
httpie
httpie/cli/nested_json/interpret.py
.py
from typing import Type, Union, Any, Iterable, Tuple from .parse import parse, assert_cant_happen from .errors import NestedJSONSyntaxError from .tokens import EMPTY_STRING, TokenKind, Token, PathAction, Path, NestedJSONArray __all__ = [ 'interpret_nested_json', 'unwrap_top_level_list_if_needed', ] JSONType...
130
4,341
httpie
httpie/cli/nested_json/tokens.py
.py
from enum import Enum, auto from typing import NamedTuple, Union, Optional, List EMPTY_STRING = '' HIGHLIGHTER = '^' OPEN_BRACKET = '[' CLOSE_BRACKET = ']' BACKSLASH = '\\' class TokenKind(Enum): TEXT = auto() NUMBER = auto() LEFT_BRACKET = auto() RIGHT_BRACKET = auto() PSEUDO = auto() # Not a r...
81
1,912
httpie
httpie/legacy/v3_2_0_session_header_format.py
.py
from typing import Any, Type, List, Dict, TYPE_CHECKING if TYPE_CHECKING: from httpie.sessions import Session OLD_HEADER_STORE_WARNING = '''\ Outdated layout detected for the current session. Please consider updating it, in order to use the latest features regarding the header layout. For fixing the current ses...
74
2,078
httpie
httpie/legacy/v3_1_0_session_cookie_format.py
.py
import argparse from typing import Any, Type, List, Dict, TYPE_CHECKING if TYPE_CHECKING: from httpie.sessions import Session INSECURE_COOKIE_JAR_WARNING = '''\ Outdated layout detected for the current session. Please consider updating it, in order to not get affected by potential security problems. For fixing ...
101
2,905
httpie
httpie/plugins/manager.py
.py
import sys import os import warnings from itertools import groupby from operator import attrgetter from typing import Dict, List, Type, Iterator, Iterable, Optional, ContextManager from pathlib import Path from contextlib import contextmanager, nullcontext from ..compat import importlib_metadata, find_entry_points, g...
122
4,049
httpie
httpie/plugins/__init__.py
.py
""" WARNING: The plugin API is still work in progress and will probably be completely reworked in the future. """ from .base import ( AuthPlugin, FormatterPlugin, ConverterPlugin, TransportPlugin ) __all__ = ('AuthPlugin', 'ConverterPlugin', 'FormatterPlugin', 'TransportPlugin')
12
299
httpie
httpie/plugins/registry.py
.py
from .manager import PluginManager from .builtin import BasicAuthPlugin, DigestAuthPlugin, BearerAuthPlugin from ..output.formatters.headers import HeadersFormatter from ..output.formatters.json import JSONFormatter from ..output.formatters.xml import XMLFormatter from ..output.formatters.colors import ColorFormatter ...
22
560
httpie
httpie/plugins/builtin.py
.py
from base64 import b64encode import requests.auth from .base import AuthPlugin # noinspection PyAbstractClass class BuiltinAuthPlugin(AuthPlugin): package_name = '(builtin)' class HTTPBasicAuth(requests.auth.HTTPBasicAuth): def __call__( self, request: requests.PreparedRequest ) -> re...
80
2,120
httpie
httpie/plugins/base.py
.py
from typing import Tuple class BasePlugin: # The name of the plugin, eg. "My auth". name = None # Optional short description. It will be shown in the help # under --auth-type. description = None # This be set automatically once the plugin has been loaded. package_name = None class Auth...
166
4,529
marshmallow
performance/benchmark.py
.py
"""Simple benchmark for marshmallow serialization of a moderately complex object. Uses the `timeit` module to benchmark serializing an object through marshmallow. """ # ruff: noqa: A002, T201 import argparse import cProfile import datetime import gc import timeit from marshmallow import Schema, ValidationError, fiel...
153
3,859
marshmallow
docs/conf.py
.py
import importlib.metadata extensions = [ "autodocsumm", "sphinx.ext.autodoc", "sphinx.ext.autodoc.typehints", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx_copybutton", "sphinx_issues", "sphinxext.opengraph", ] primary_domain = "py" default_role = "py:obj" intersphinx_mappi...
70
2,216
marshmallow
tests/test_error_store.py
.py
from typing import NamedTuple from marshmallow import missing from marshmallow.error_store import ErrorStore, merge_errors def test_missing_is_falsy(): assert bool(missing) is False class CustomError(NamedTuple): code: int message: str class TestMergeErrors: def test_merging_none_and_string(self)...
168
5,749
marshmallow
tests/test_exceptions.py
.py
import pytest from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError("foo") assert err.messages == ["foo"] def test_can_pass_list_of_messages(self): err = ValidationError(["foo", "bar"]) asser...
43
1,416
marshmallow
tests/test_registry.py
.py
import pytest from marshmallow import Schema, class_registry, fields from marshmallow.exceptions import RegistryError def test_serializer_has_class_registry(): class MySchema(Schema): pass class MySubSchema(Schema): pass assert "MySchema" in class_registry._registry assert "MySubSch...
232
7,328
marshmallow
tests/test_validate.py
.py
"""Tests for marshmallow.validate""" import re import pytest from marshmallow import ValidationError, validate @pytest.mark.parametrize( "valid_url", [ "http://example.org", "https://example.org", "ftp://example.org", "ftps://example.org", "http://example.co.jp", ...
1,102
36,011
marshmallow
tests/test_decorators.py
.py
import pytest from marshmallow import ( EXCLUDE, INCLUDE, RAISE, Schema, ValidationError, fields, post_dump, post_load, pre_dump, pre_load, validate, validates, validates_schema, ) from tests.base import predicate @pytest.mark.parametrize("partial_val", (True, Fals...
988
34,392
marshmallow
tests/foo_serializer.py
.py
from marshmallow import Schema, fields class FooSerializer(Schema): _id = fields.Integer()
6
97
marshmallow
tests/test_fields.py
.py
import pytest from marshmallow import ( EXCLUDE, INCLUDE, RAISE, Schema, ValidationError, fields, missing, ) from marshmallow.exceptions import StringNotCollectionError from marshmallow.orderedset import OrderedSet from tests.base import ALL_FIELDS @pytest.mark.parametrize( ("alias", ...
756
27,882
marshmallow
tests/base.py
.py
"""Test utilities and fixtures.""" import datetime as dt import functools import typing import uuid from enum import Enum, IntEnum from zoneinfo import ZoneInfo import simplejson from marshmallow import Schema, fields, missing, post_load, validate from marshmallow.exceptions import ValidationError central = ZoneInf...
291
7,343
marshmallow
tests/test_context.py
.py
import typing import pytest from marshmallow import ( Schema, fields, post_dump, post_load, pre_dump, pre_load, validates, validates_schema, ) from marshmallow.exceptions import ValidationError from marshmallow.experimental.context import Context from tests.base import Blog, User cla...
252
8,390
marshmallow
tests/test_options.py
.py
import datetime as dt from marshmallow import EXCLUDE, Schema, fields class UserSchema(Schema): name = fields.String(allow_none=True) email = fields.Email(allow_none=True) age = fields.Integer() created = fields.DateTime() id = fields.Integer(allow_none=True) homepage = fields.Url() birth...
166
4,752
marshmallow
tests/test_serialization.py
.py
"""Tests for field serialization.""" import datetime as dt import decimal import ipaddress import itertools import math import uuid from collections import OrderedDict from typing import NamedTuple import pytest from marshmallow import Schema, fields from marshmallow import missing as missing_ from tests.base import...
1,003
37,608
marshmallow
tests/test_utils.py
.py
from __future__ import annotations import datetime as dt from copy import copy, deepcopy from typing import NamedTuple import pytest from marshmallow import Schema, fields, utils def test_missing_singleton_copy(): assert copy(utils.missing) is utils.missing assert deepcopy(utils.missing) is utils.missing ...
161
4,316
marshmallow
tests/test_schema.py
.py
import datetime as dt import math import random from collections import OrderedDict from typing import NamedTuple, cast import pytest import simplejson as json from marshmallow import ( EXCLUDE, INCLUDE, RAISE, Schema, class_registry, fields, validate, validates, validates_schema, ...
2,552
78,701
marshmallow
tests/test_deserialization.py
.py
# mypy: disable-error-code="arg-type" import datetime as dt import decimal import ipaddress import math import typing import uuid from unittest.mock import patch import pytest from marshmallow import ( EXCLUDE, INCLUDE, RAISE, Schema, fields, missing, validate, ) from marshmallow.exception...
2,398
91,519
marshmallow
tests/conftest.py
.py
"""Pytest fixtures that are available in all test modules.""" import pytest from tests.base import Blog, User, UserSchema @pytest.fixture def user(): return User(name="Monty", age=42.3, homepage="http://monty.python.org/") @pytest.fixture def blog(user): col1 = User(name="Mick", age=123) col2 = User(n...
28
566
marshmallow
tests/mypy_test_cases/test_validation_error.py
.py
from __future__ import annotations import marshmallow as ma # OK types for 'message' ma.ValidationError("foo") ma.ValidationError(["foo"]) ma.ValidationError({"foo": "bar"}) # non-OK types for 'message' ma.ValidationError(0) # type: ignore[arg-type] # 'messages' is a dict|list err = ma.ValidationError("foo") a: di...
21
579
marshmallow
tests/mypy_test_cases/test_class_registry.py
.py
from marshmallow import class_registry # Works without passing `all` class_registry.get_class("MySchema")
5
107
marshmallow
tests/mypy_test_cases/test_schema.py
.py
import json from marshmallow import EXCLUDE, Schema from marshmallow.fields import Integer, String # Test that valid `Meta` class attributes pass type checking class MySchema(Schema): foo = String() bar = Integer() class Meta(Schema.Meta): fields = ("foo", "bar") additional = ("baz", "qu...
30
748
marshmallow
examples/inflection_example.py
.py
# /// script # requires-python = ">=3.9" # dependencies = [ # "marshmallow", # ] # /// from marshmallow import Schema, fields def camelcase(s): parts = iter(s.split("_")) return next(parts) + "".join(i.title() for i in parts) class CamelCaseSchema(Schema): """Schema that uses camel-case for its exte...
39
921
marshmallow
examples/package_json_example.py
.py
# /// script # requires-python = ">=3.10" # dependencies = [ # "marshmallow", # "packaging>=17.0", # ] # /// import json import sys from pprint import pprint from packaging import version from marshmallow import INCLUDE, Schema, ValidationError, fields class Version(fields.Field[version.Version]): """Ve...
59
1,598
marshmallow
examples/flask_example.py
.py
# /// script # requires-python = ">=3.10" # dependencies = [ # "flask", # "flask-sqlalchemy>=3.1.1", # "marshmallow", # "sqlalchemy>2.0", # ] # /// from __future__ import annotations import datetime from flask import Flask, request from flask_sqlalchemy import SQLAlchemy from sqlalchemy.exc import NoR...
163
4,551
marshmallow
src/marshmallow/types.py
.py
"""Type aliases. .. warning:: This module is provisional. Types may be modified, added, and removed between minor releases. """ from __future__ import annotations import typing T = typing.TypeVar("T") #: A type that can be either a sequence of strings or a set of strings StrSequenceOrSet: typing.TypeAlias = t...
55
1,634
marshmallow
src/marshmallow/utils.py
.py
"""Utility methods for marshmallow.""" from __future__ import annotations import datetime as dt import inspect import typing from collections.abc import Mapping, Sequence from marshmallow.constants import missing def is_generator(obj) -> typing.TypeGuard[typing.Generator]: """Return True if ``obj`` is a genera...
167
5,430
marshmallow
src/marshmallow/fields.py
.py
# ruff: noqa: SLF001 from __future__ import annotations import abc import collections import copy import datetime as dt import decimal import email.utils import ipaddress import math import numbers import typing import uuid from collections.abc import Mapping as _Mapping from enum import Enum as EnumType try: fro...
2,152
75,337
marshmallow
src/marshmallow/exceptions.py
.py
"""Exception classes for marshmallow-related errors.""" from __future__ import annotations import typing # Key used for schema-level validation errors SCHEMA = "_schema" class MarshmallowError(Exception): """Base class for all marshmallow-related errors.""" class ValidationError(MarshmallowError): """Rai...
71
2,273
marshmallow
src/marshmallow/error_store.py
.py
"""Utilities for storing collections of error messages. .. warning:: This module is treated as private API. Users should not need to use this module directly. """ from marshmallow.exceptions import SCHEMA class ErrorStore: def __init__(self): #: Dictionary of errors stored during serialization ...
72
2,444
marshmallow
src/marshmallow/class_registry.py
.py
"""A registry of :class:`Schema <marshmallow.Schema>` classes. This allows for string lookup of schemas, which may be used with class:`fields.Nested <marshmallow.fields.Nested>`. .. warning:: This module is treated as private API. Users should not need to use this module directly. """ # ruff: noqa: ERA001 fr...
104
3,029
marshmallow
src/marshmallow/__init__.py
.py
from marshmallow.constants import EXCLUDE, INCLUDE, RAISE, missing from marshmallow.decorators import ( post_dump, post_load, pre_dump, pre_load, validates, validates_schema, ) from marshmallow.exceptions import ValidationError from marshmallow.schema import Schema, SchemaOpts from . import fie...
31
573
marshmallow
src/marshmallow/constants.py
.py
import typing EXCLUDE: typing.Final = "exclude" INCLUDE: typing.Final = "include" RAISE: typing.Final = "raise" class _Missing: def __bool__(self): return False def __copy__(self): return self def __deepcopy__(self, _): return self def __repr__(self): return "<marsh...
26
415
marshmallow
src/marshmallow/schema.py
.py
"""The `Schema <marshmallow.Schema>` class, including its metaclass and options (`class Meta <marshmallow.Schema.Meta>`).""" # ruff: noqa: SLF001 from __future__ import annotations import copy import datetime as dt import decimal import functools import inspect import ipaddress import json import operator import typi...
1,254
50,119
marshmallow
src/marshmallow/validate.py
.py
"""Validation classes for various types of data.""" from __future__ import annotations import re import typing from abc import ABC, abstractmethod from operator import attrgetter from marshmallow.exceptions import ValidationError if typing.TYPE_CHECKING: from marshmallow import types _T = typing.TypeVar("_T") ...
709
24,880
marshmallow
src/marshmallow/orderedset.py
.py
# OrderedSet # Copyright (c) 2009 Raymond Hettinger # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merg...
90
2,953
marshmallow
src/marshmallow/decorators.py
.py
"""Decorators for registering schema pre-processing and post-processing methods. These should be imported from the top-level `marshmallow` module. Methods decorated with `pre_load <marshmallow.decorators.pre_load>`, `post_load <marshmallow.decorators.post_load>`, `pre_dump <marshmallow.decorators.pre_dump>`, `post_dum...
255
10,165
marshmallow
src/marshmallow/experimental/__init__.py
.py
"""Experimental features. The features in this subpackage are experimental. Breaking changes may be introduced in minor marshmallow versions. """
6
147
marshmallow
src/marshmallow/experimental/context.py
.py
"""Helper API for setting serialization/deserialization context. Example usage: .. code-block:: python import typing from marshmallow import Schema, fields from marshmallow.experimental.context import Context class UserContext(typing.TypedDict): suffix: str UserSchemaContext = Contex...
74
2,040
loguru
docs/conf.py
.py
"""Configuration file for the Sphinx documentation builder. This file does only contain a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/master/config -- Path setup -------------------------------------------------------------- If extensions (or modules to d...
184
5,655
loguru
tests/test_colorama.py
.py
import builtins import os import sys from unittest.mock import MagicMock import pytest from loguru import logger from loguru._colorama import should_colorize, should_wrap from .conftest import ( StreamFilenoException, StreamIsattyException, StreamIsattyFalse, StreamIsattyTrue, ) @pytest.fixture(aut...
375
13,727
loguru
tests/test_template_strings.py
.py
import sys from unittest.mock import MagicMock import pytest from loguru import logger from .conftest import parse if sys.version_info >= (3, 14): from string.templatelib import Interpolation, Template @pytest.mark.skipif(sys.version_info < (3, 14), reason="Template Strings not supported") def test_template_s...
208
6,849
loguru
tests/test_add_option_enqueue.py
.py
import pickle import re import sys import time import pytest from loguru import logger from .conftest import default_threading_excepthook class NotPicklable: def __getstate__(self): raise pickle.PicklingError("You shall not serialize me!") def __setstate__(self, state): pass class NotPic...
295
8,480
loguru
tests/test_pickling.py
.py
import asyncio import contextlib import datetime import logging import pickle import pytest from loguru import logger from .conftest import parse def print_(message): print(message, end="") async def async_print(msg): print_(msg) @contextlib.contextmanager def copied_logger_though_pickle(logger): p...
351
10,656
loguru
tests/test_coroutine_sink.py
.py
import asyncio import logging import multiprocessing import re import sys import threading import pytest from loguru import logger from .conftest import new_event_loop_context, set_event_loop_context async def async_writer(msg): await asyncio.sleep(0.01) print(msg, end="") class AsyncWriter: async de...
678
16,966
loguru
tests/test_standard_handler.py
.py
import sys from logging import FileHandler, Filter, Formatter, Handler, NullHandler, StreamHandler import pytest from loguru import logger class RejectAllFilter(Filter): def filter(self, record): return False def test_stream_handler(capsys): logger.add(StreamHandler(sys.stderr), format="{level} {m...
251
6,884
loguru
tests/test_filesink_compression.py
.py
import os import sys import threading import time from unittest.mock import Mock import pytest from loguru import logger from .conftest import check_dir @pytest.mark.parametrize( "compression", ["gz", "bz2", "zip", "xz", "lzma", "tar", "tar.gz", "tar.bz2", "tar.xz"] ) def test_compression_ext(tmp_path, compres...
318
9,666
loguru
tests/test_type_hinting.py
.py
import sys import pytest try: mypy_api = None # type: Optional[ModuleType] import mypy.api as mypy_api # noqa: F811 except ImportError: pass @pytest.mark.skipif(mypy_api is None, reason="Requires mypy to be installed.") def test_mypy_import(): # Check stub file is valid and can be imported by Mypy...
19
568
loguru
tests/test_repr.py
.py
import logging import pathlib import re import sys from loguru import logger def test_no_handler(): assert repr(logger) == "<loguru.logger handlers=[]>" def test_stderr(): logger.add(sys.__stderr__) assert repr(logger) == "<loguru.logger handlers=[(id=0, level=10, sink=<stderr>)]>" def test_stdout():...
192
4,984
loguru
tests/test_remove.py
.py
import sys import time import pytest from loguru import logger class StopSinkError: def write(self, message): print(message, end="") def stop(self): raise OSError("Stop error") def test_remove_all(tmp_path, writer, capsys): file = tmp_path / "test.log" logger.debug("This shouldn'...
113
2,670
loguru
tests/test_threading.py
.py
import itertools import time from threading import Barrier, Thread from loguru import logger class NonSafeSink: def __init__(self, sleep_time, stop_time=0): self.sleep_time = sleep_time self.stop_time = stop_time self.written = "" self.stopped = False def write(self, message)...
226
4,996
loguru
tests/test_datetime.py
.py
import datetime import os import sys from time import strftime from unittest.mock import Mock import freezegun import pytest import loguru from loguru import logger if sys.version_info < (3, 6): UTC_NAME = "UTC+00:00" else: UTC_NAME = "UTC" def _expected_fallback_time_zone(): # For some reason, Python ...
263
9,480
loguru
tests/test_bind.py
.py
import pytest from loguru import logger def test_bind_after_add(writer): logger.add(writer, format="{extra[a]} {message}") logger_bound = logger.bind(a=0) logger_bound.debug("A") assert writer.read() == "0 A\n" def test_bind_before_add(writer): logger_bound = logger.bind(a=0) logger.add(wr...
87
2,046
loguru
tests/test_patch.py
.py
from loguru import logger def test_patch_after_add(writer): logger.add(writer, format="{extra[a]} {message}") logger_patched = logger.patch(lambda r: r["extra"].update(a=0)) logger_patched.debug("A") assert writer.read() == "0 A\n" def test_patch_before_add(writer): logger_patched = logger.patc...
96
2,702
loguru
tests/test_levels.py
.py
import functools import pytest from loguru import logger from .conftest import parse def test_log_int_level(writer): logger.add(writer, format="{level.name} -> {level.no} -> {message}", colorize=False) logger.log(10, "test") assert writer.read() == "Level 10 -> 10 -> test\n" def test_log_str_level(w...
299
9,005
loguru
tests/test_multiprocessing.py
.py
import copy import multiprocessing import os import platform import sys import threading import time import pytest from loguru import logger from .conftest import new_event_loop_context @pytest.fixture def fork_context(): return multiprocessing.get_context("fork") @pytest.fixture def spawn_context(): ret...
633
16,900
loguru
tests/test_get_frame.py
.py
import sys import loguru from loguru._get_frame import load_get_frame_function def test_with_sys_getframe(monkeypatch): def patched(): return with monkeypatch.context() as context: context.setattr(sys, "_getframe", patched()) assert load_get_frame_function() == patched() def test_w...
38
912
loguru
tests/test_exceptions_formatting.py
.py
import os import platform import re import subprocess import sys import traceback from unittest.mock import MagicMock import pytest from loguru import logger def normalize(exception): """Normalize exception output for reproducible test cases.""" if os.name == "nt": exception = re.sub( r'...
326
10,591
loguru
tests/test_add_option_diagnose.py
.py
from loguru import logger # See "test_catch_exceptions.py" for extended testing def test_diagnose(writer): logger.add(writer, format="{message}", diagnose=True) try: 1 / 0 # noqa: B018 except Exception: logger.exception("") result_with = writer.read().strip() logger.remove() ...
25
604
loguru
tests/test_add_option_backtrace.py
.py
from loguru import logger # See "test_catch_exceptions.py" for extended testing def test_backtrace(writer): logger.add(writer, format="{message}", backtrace=True) try: 1 / 0 # noqa: B018 except Exception: logger.exception("") result_with = writer.read().strip() logger.remove() ...
25
607
loguru
tests/test_parse.py
.py
import io import pathlib import re from datetime import datetime import pytest from loguru import logger TEXT = "This\nIs\nRandom\nText\n123456789\nABC!DEF\nThis Is The End\n" @pytest.fixture def fileobj(): with io.StringIO(TEXT) as file: yield file def test_parse_file(tmp_path): file = tmp_path ...
147
4,452
loguru
tests/test_filesink_delay.py
.py
import datetime import time from loguru import logger from .conftest import check_dir def test_file_not_delayed(tmp_path): file = tmp_path / "test.log" logger.add(file, format="{message}", delay=False) assert file.read_text() == "" logger.debug("Not delayed") assert file.read_text() == "Not dela...
118
3,435
loguru
tests/test_defaults.py
.py
import pytest from loguru._defaults import env @pytest.mark.parametrize("value", ["test", ""]) def test_string(value, monkeypatch): with monkeypatch.context() as context: key = "VALID_STRING" context.setenv(key, value) assert env(key, str) == value @pytest.mark.parametrize("value", ["y"...
67
1,984
loguru
tests/test_filesink_rotation.py
.py
import datetime import os import pathlib import tempfile import time from unittest.mock import Mock import pytest import loguru from loguru import logger from loguru._ctime_functions import load_ctime_functions from .conftest import check_dir @pytest.fixture def tmp_path_local(reset_logger): # Pytest 'tmp_path...
1,151
37,430
loguru
tests/test_reinstall.py
.py
import multiprocessing import os import pytest from loguru import logger @pytest.fixture def fork_context(): return multiprocessing.get_context("fork") @pytest.fixture def spawn_context(): return multiprocessing.get_context("spawn") class Writer: def __init__(self): self._output = "" de...
107
2,332
loguru
tests/test_deepcopy.py
.py
import copy from loguru import logger def print_(message): print(message, end="") def test_add_sink_after_deepcopy(capsys): logger_ = copy.deepcopy(logger) logger_.add(print_, format="{message}", catch=False) logger_.info("A") logger.info("B") out, err = capsys.readouterr() assert ou...
62
1,173
loguru
tests/test_add_option_level.py
.py
import pytest from loguru import logger @pytest.mark.parametrize("level", [0, "TRACE", "INFO", 20]) def test_level_low_enough(writer, level): logger.add(writer, level=level, format="{message}") logger.info("Test level") assert writer.read() == "Test level\n" @pytest.mark.parametrize("level", ["WARNING"...
36
1,006
loguru
tests/test_add_option_context.py
.py
import multiprocessing import os from unittest.mock import patch import pytest from loguru import logger def test_using_multiprocessing_directly_if_context_is_none(): logger.add(lambda _: None, enqueue=True, context=None) assert multiprocessing.get_start_method(allow_none=True) is not None @pytest.mark.sk...
68
2,563
loguru
tests/test_filesink_watch.py
.py
import os from unittest.mock import Mock import pytest from loguru import logger from .conftest import check_dir @pytest.mark.skipif(os.name == "nt", reason="Windows can't delete file in use") def test_file_deleted_before_write_without_delay(tmp_path): file = tmp_path / "test.log" logger.add(file, format="...
149
4,502
loguru
tests/test_interception.py
.py
import inspect import logging from loguru import logger from .conftest import make_logging_logger class InterceptHandler(logging.Handler): def emit(self, record): # Get corresponding Loguru level if it exists. try: level = logger.level(record.levelname).name except ValueError...
167
5,443
loguru
tests/test_recattr.py
.py
import re import loguru._recattrs as recattrs from loguru import logger def test_patch_record_file(writer): def patch(record): record["file"].name = "456" record["file"].path = "123/456" logger.add(writer, format="{file} {file.name} {file.path}") logger.patch(patch).info("Test") ass...
78
2,164
loguru
tests/test_opt.py
.py
import sys from unittest.mock import MagicMock import pytest from loguru import logger from .conftest import parse def test_record(writer): logger.add(writer, format="{message}") logger.opt(record=True).debug("1") logger.opt(record=True).debug("2 {record[level]}") logger.opt(record=True).log(11, "...
639
22,076
loguru
tests/test_ansimarkup_extended.py
.py
import pytest from colorama import Back, Fore, Style from .conftest import parse @pytest.mark.parametrize( ("text", "expected"), [ ("<bg red>1</bg red>", Back.RED + "1" + Style.RESET_ALL), ("<bg BLACK>1</bg BLACK>", Back.BLACK + "1" + Style.RESET_ALL), ("<bg light-green>1</bg light-gr...
253
8,013
loguru
tests/test_ansimarkup_basic.py
.py
import pytest from colorama import Back, Fore, Style from .conftest import parse @pytest.mark.parametrize( ("text", "expected"), [ ("<bold>1</bold>", Style.BRIGHT + "1" + Style.RESET_ALL), ("<dim>1</dim>", Style.DIM + "1" + Style.RESET_ALL), ("<normal>1</normal>", Style.NORMAL + "1" +...
240
6,924
loguru
tests/test_formatting.py
.py
import os import re import pytest from loguru import logger @pytest.mark.parametrize( ("format", "validator"), [ ("{name}", lambda r: r == "tests.test_formatting"), ("{time}", lambda r: re.fullmatch(r"\d+-\d+-\d+T\d+:\d+:\d+[.,]\d+[+-]\d{4}", r)), ("{elapsed}", lambda r: re.fullmatch...
269
9,089