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 |
|---|---|---|---|---|---|
celery | celery/utils/deprecated.py | .py | """Deprecation utilities."""
import warnings
from vine.utils import wraps
from celery.exceptions import CDeprecationWarning, CPendingDeprecationWarning
__all__ = ('Callable', 'Property', 'warn')
PENDING_DEPRECATION_FMT = """
{description} is scheduled for deprecation in \
version {deprecation} and removal ... | 114 | 3,620 |
celery | celery/utils/collections.py | .py | """Custom maps, sets, sequences, and other data structures."""
import time
from collections import OrderedDict as _OrderedDict
from collections import deque
from collections.abc import Callable, Mapping, MutableMapping, MutableSet, Sequence
from heapq import heapify, heappop, heappush
from itertools import chain, count... | 864 | 25,432 |
celery | celery/utils/serialization.py | .py | """Utilities for safely pickling exceptions."""
import datetime
import numbers
import sys
from base64 import b64decode as base64decode
from base64 import b64encode as base64encode
from functools import partial
from inspect import getmro
from itertools import takewhile
from kombu.utils.encoding import bytes_to_str, saf... | 274 | 8,209 |
celery | celery/utils/quorum_queues.py | .py | from __future__ import annotations
def detect_quorum_queues(app, driver_type: str) -> tuple[bool, str]:
"""Detect if any of the queues are quorum queues.
Returns:
tuple[bool, str]: A tuple containing a boolean indicating if any of the queues are quorum queues
and the name of the first quorum ... | 21 | 705 |
celery | celery/utils/graph.py | .py | """Dependency graph implementation."""
from collections import Counter
from textwrap import dedent
from kombu.utils.encoding import bytes_to_str, safe_str
__all__ = ('DOT', 'CycleError', 'DependencyGraph', 'GraphFormatter')
class DOT:
"""Constants related to the dot format."""
HEAD = dedent("""
{IN... | 310 | 9,041 |
celery | celery/utils/saferepr.py | .py | """Streaming, truncating, non-recursive version of :func:`repr`.
Differences from regular :func:`repr`:
- Sets are represented the Python 3 way: ``{1, 2}`` vs ``set([1, 2])``.
- Unicode strings does not have the ``u'`` prefix, even on Python 2.
- Empty set formatted as ``set()`` (Python 3), not ``set([])`` (Python 2)... | 270 | 9,022 |
celery | celery/utils/dispatch/signal.py | .py | """Implementation of the Observer pattern."""
import sys
import threading
import warnings
import weakref
from weakref import WeakMethod
from kombu.utils.functional import retry_over_time
from celery.exceptions import CDeprecationWarning
from celery.local import PromiseProxy, Proxy
from celery.utils.functional import ... | 359 | 13,859 |
celery | celery/utils/dispatch/__init__.py | .py | """Observer pattern."""
from .signal import Signal
__all__ = ('Signal',)
| 5 | 74 |
celery | celery/utils/static/__init__.py | .py | """Static files."""
import os
def get_file(*args):
# type: (*str) -> str
"""Get filename for static file."""
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *args)
def logo():
# type: () -> bytes
"""Celery logo image."""
return get_file('celery_128.png')
| 15 | 299 |
celery | celery/concurrency/solo.py | .py | """Single-threaded execution pool."""
import os
from celery import signals
from .base import BasePool, apply_target
__all__ = ('TaskPool',)
class TaskPool(BasePool):
"""Solo task pool (blocking, inline, fast)."""
body_can_be_buffer = True
def __init__(self, *args, **kwargs):
super().__init__(... | 32 | 754 |
celery | celery/concurrency/asynpool.py | .py | """Version of multiprocessing.Pool using Async I/O.
.. note::
This module will be moved soon, so don't use it directly.
This is a non-blocking version of :class:`multiprocessing.Pool`.
This code deals with three major challenges:
#. Starting up child processes and keeping them running.
#. Sending jobs to the p... | 1,418 | 54,788 |
celery | celery/concurrency/__init__.py | .py | """Pool implementation abstract factory, and alias definitions."""
import os
# Import from kombu directly as it's used
# early in the import stage, where celery.utils loads
# too much (e.g., for eventlet patching)
from kombu.utils.imports import symbol_by_name
__all__ = ('get_implementation', 'get_available_pool_name... | 49 | 1,457 |
celery | celery/concurrency/thread.py | .py | """Thread execution pool."""
from __future__ import annotations
from concurrent.futures import Future, ThreadPoolExecutor, wait
from typing import TYPE_CHECKING, Any, Callable
from .base import BasePool, apply_target
__all__ = ('TaskPool',)
if TYPE_CHECKING:
from typing import TypedDict
PoolInfo = TypedDic... | 65 | 1,826 |
celery | celery/concurrency/gevent.py | .py | """Gevent execution pool."""
import functools
import types
from time import monotonic
from kombu.asynchronous import timer as _timer
from . import base
try:
from gevent import Timeout
except ImportError:
Timeout = None
__all__ = ('TaskPool',)
# pylint: disable=redefined-outer-name
# We cache globals and at... | 172 | 4,953 |
celery | celery/concurrency/eventlet.py | .py | """Eventlet execution pool."""
import sys
from time import monotonic
from greenlet import GreenletExit
from kombu.asynchronous import timer as _timer
from celery import signals
from . import base
__all__ = ('TaskPool',)
W_RACE = """\
Celery module with %s imported before eventlet patched\
"""
RACE_MODS = ('billiar... | 182 | 5,140 |
celery | celery/concurrency/prefork.py | .py | """Prefork execution pool.
Pool implementation using :mod:`multiprocessing`.
"""
import os
import threading
import time
from billiard import forking_enable
from billiard.common import REMAP_SIGTERM, TERM_SIGNAME
from billiard.pool import CLOSE, RUN
from billiard.pool import Pool as BlockingPool
from kombu.asynchronou... | 217 | 7,573 |
celery | celery/concurrency/base.py | .py | """Base Execution Pool."""
import logging
import os
import sys
import time
from typing import Any, Dict
from billiard.einfo import ExceptionInfo
from billiard.exceptions import WorkerLostError
from kombu.utils.encoding import safe_repr
from celery.exceptions import WorkerShutdown, WorkerTerminate, reraise
from celery... | 181 | 4,706 |
celery | celery/contrib/abortable.py | .py | """Abortable Tasks.
Abortable tasks overview
=========================
For long-running :class:`Task`'s, it can be desirable to support
aborting during execution. Of course, these tasks should be built to
support abortion specifically.
The :class:`AbortableTask` serves as a base class for all :class:`Task`
objects ... | 166 | 5,003 |
celery | celery/contrib/sphinx.py | .py | """Sphinx documentation plugin used to document tasks.
Introduction
============
Usage
-----
The Celery extension for Sphinx requires Sphinx 2.0 or later.
Add the extension to your :file:`docs/conf.py` configuration module:
.. code-block:: python
extensions = (...,
'celery.contrib.sphinx')
... | 140 | 4,675 |
celery | celery/contrib/rdb.py | .py | """Remote Debugger.
Introduction
============
This is a remote debugger for Celery tasks running in multiprocessing
pool workers. Inspired by a lost post on dzone.com.
Usage
-----
.. code-block:: python
from celery.contrib import rdb
from celery import task
@task()
def add(x, y):
result =... | 188 | 5,005 |
celery | celery/contrib/pytest.py | .py | """Fixtures and testing utilities for :pypi:`pytest <pytest>`."""
import os
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Mapping, Sequence, Union # noqa
import pytest
if TYPE_CHECKING:
from celery import Celery
from ..worker import WorkController
else:
Celery = WorkContro... | 217 | 6,754 |
celery | celery/contrib/migrate.py | .py | """Message migration tools (Broker <-> Broker)."""
import socket
from functools import partial
from itertools import cycle, islice
from kombu import Queue, eventloop
from kombu.common import maybe_declare
from kombu.utils.encoding import ensure_bytes
from celery.app import app_or_default
from celery.utils.nodenames i... | 417 | 14,361 |
celery | celery/contrib/testing/app.py | .py | """Create Celery app instances used for testing."""
import weakref
from contextlib import contextmanager
from copy import deepcopy
from kombu.utils.imports import symbol_by_name
from celery import Celery, _state
#: Contains the default configuration values for the test app.
DEFAULT_TEST_CONFIG = {
'worker_hijack... | 113 | 3,112 |
celery | celery/contrib/testing/manager.py | .py | """Integration testing utilities."""
import socket
import sys
from collections import defaultdict
from functools import partial
from itertools import count
from typing import Any, Callable, Dict, Sequence, TextIO, Tuple # noqa
from kombu.exceptions import ContentDisallowed
from kombu.utils.functional import retry_ove... | 240 | 8,605 |
celery | celery/contrib/testing/worker.py | .py | """Embedded workers for integration tests."""
import logging
import os
import threading
from contextlib import contextmanager
from typing import Any, Iterable, Optional, Union
import celery.worker.consumer # noqa
from celery import Celery, worker
from celery.result import _set_task_join_will_block, allow_join_result
... | 226 | 7,385 |
celery | celery/contrib/testing/mocks.py | .py | """Useful mocks for unit testing."""
import numbers
from datetime import datetime, timedelta
from typing import Any, Mapping, Sequence # noqa
from unittest.mock import Mock
from celery import Celery # noqa
from celery.canvas import Signature # noqa
def TaskMessage(
name, # type: str
id=None, # type: str... | 138 | 4,182 |
celery | celery/contrib/testing/tasks.py | .py | """Helper tasks for integration tests."""
from celery import shared_task
@shared_task(name='celery.ping')
def ping():
# type: () -> str
"""Simple task that just returns 'pong'."""
return 'pong'
| 10 | 208 |
celery | celery/contrib/django/task.py | .py | import functools
from django.db import transaction
from celery.app.task import Task
class DjangoTask(Task):
"""
Extend the base :class:`~celery.app.task.Task` for Django.
Provide a nicer API to trigger tasks at the end of the DB transaction.
"""
def delay_on_commit(self, *args, **kwargs) -> No... | 22 | 727 |
celery | celery/worker/strategy.py | .py | """Task execution strategy (optimization)."""
import logging
from kombu.asynchronous.timer import to_timestamp
from celery import signals
from celery.app import trace as _app_trace
from celery.exceptions import InvalidTaskError
from celery.utils.imports import symbol_by_name
from celery.utils.log import get_logger
fr... | 210 | 7,353 |
celery | celery/worker/state.py | .py | """Internal worker state (global).
This includes the currently active and reserved tasks,
statistics, and revoked tasks.
"""
import os
import platform
import shelve
import sys
import weakref
import zlib
from collections import Counter
from kombu.serialization import pickle, pickle_protocol
from kombu.utils.objects im... | 289 | 8,583 |
celery | celery/worker/pidbox.py | .py | """Worker Pidbox (remote control)."""
import socket
import threading
from kombu.common import ignore_errors
from kombu.utils.encoding import safe_str
from celery.utils.collections import AttributeDict
from celery.utils.functional import pass1
from celery.utils.log import get_logger
from . import control
__all__ = (... | 127 | 3,773 |
celery | celery/worker/request.py | .py | """Task request.
This module defines the :class:`Request` class, that specifies
how tasks are executed.
"""
import logging
import sys
from datetime import datetime
from time import monotonic, time
from weakref import ref
from billiard.common import TERM_SIGNAME
from billiard.einfo import ExceptionInfo, ExceptionWithT... | 875 | 31,124 |
celery | celery/worker/heartbeat.py | .py | """Heartbeat service.
This is the internal thread responsible for sending heartbeat events
at regular intervals (may not be an actual thread).
"""
from celery.signals import heartbeat_sent
from celery.utils.sysinfo import load_average
from .state import SOFTWARE_INFO, active_requests, all_total_count
__all__ = ('Hea... | 62 | 2,107 |
celery | celery/worker/__init__.py | .py | """Worker implementation."""
from .worker import WorkController
__all__ = ('WorkController',)
| 5 | 95 |
celery | celery/worker/components.py | .py | """Worker-level Bootsteps."""
import atexit
import warnings
from kombu.asynchronous import Hub as _Hub
from kombu.asynchronous import get_event_loop, set_event_loop
from kombu.asynchronous.semaphore import DummyLock, LaxBoundedSemaphore
from kombu.asynchronous.timer import Timer as _Timer
from celery import bootsteps... | 247 | 7,917 |
celery | celery/worker/loops.py | .py | """The consumers highly-optimized inner loop."""
import errno
import socket
from celery import bootsteps
from celery.exceptions import WorkerLostError
from celery.utils.log import get_logger
from . import state
__all__ = ('asynloop', 'synloop')
# pylint: disable=redefined-outer-name
# We cache globals and attribute... | 184 | 6,888 |
celery | celery/worker/worker.py | .py | """WorkController can be used to instantiate in-process workers.
The command-line interface for the worker is in :mod:`celery.bin.worker`,
while the worker program is in :mod:`celery.apps.worker`.
The worker program is responsible for adding signal handlers,
setting up logging, etc. This is a bare-bones worker witho... | 436 | 15,755 |
celery | celery/worker/control.py | .py | """Worker remote control command implementations."""
import io
import tempfile
from collections import UserDict, defaultdict, namedtuple
from billiard.common import TERM_SIGNAME
from kombu.utils.encoding import safe_repr
from celery.exceptions import WorkerShutdown
from celery.platforms import EX_OK
from celery.platf... | 638 | 20,362 |
celery | celery/worker/autoscale.py | .py | """Pool Autoscaling.
This module implements the internal thread responsible
for growing and shrinking the pool according to the
current autoscale settings.
The autoscale thread is only enabled if
the :option:`celery worker --autoscale` option is used.
"""
import os
import threading
from time import monotonic, sleep
... | 155 | 4,593 |
celery | celery/worker/consumer/heart.py | .py | """Worker Event Heartbeat Bootstep."""
from celery import bootsteps
from celery.worker import heartbeat
from .events import Events
__all__ = ('Heart',)
class Heart(bootsteps.StartStopStep):
"""Bootstep sending event heartbeats.
This service sends a ``worker-heartbeat`` message every n seconds.
Note:
... | 37 | 930 |
celery | celery/worker/consumer/mingle.py | .py | """Worker <-> Worker Sync at startup (Bootstep)."""
from celery import bootsteps
from celery.utils.log import get_logger
from .events import Events
__all__ = ('Mingle',)
logger = get_logger(__name__)
debug, info, exception = logger.debug, logger.info, logger.exception
class Mingle(bootsteps.StartStopStep):
"""... | 77 | 2,531 |
celery | celery/worker/consumer/__init__.py | .py | """Worker consumer."""
from .agent import Agent
from .connection import Connection
from .consumer import Consumer
from .control import Control
from .events import Events
from .gossip import Gossip
from .heart import Heart
from .mingle import Mingle
from .tasks import Tasks
__all__ = (
'Consumer', 'Agent', 'Connect... | 16 | 391 |
celery | celery/worker/consumer/consumer.py | .py | """Worker Consumer Blueprint.
This module contains the components responsible for consuming messages
from the broker, processing the messages and keeping the broker connections
up and running.
"""
import errno
import logging
import os
import warnings
from collections import defaultdict
from time import sleep
from bil... | 873 | 35,730 |
celery | celery/worker/consumer/gossip.py | .py | """Worker <-> Worker communication Bootstep."""
from collections import defaultdict
from functools import partial
from heapq import heappush
from operator import itemgetter
from kombu import Consumer
from kombu.asynchronous.semaphore import DummyLock
from kombu.exceptions import ContentDisallowed, DecodeError
from ce... | 207 | 6,888 |
celery | celery/worker/consumer/connection.py | .py | """Consumer Broker Connection Bootstep."""
from kombu.common import ignore_errors
from celery import bootsteps
from celery.utils.log import get_logger
__all__ = ('Connection',)
logger = get_logger(__name__)
info = logger.info
class Connection(bootsteps.StartStopStep):
"""Service managing the consumer broker co... | 46 | 1,355 |
celery | celery/worker/consumer/control.py | .py | """Worker Remote Control Bootstep.
``Control`` -> :mod:`celery.worker.pidbox` -> :mod:`kombu.pidbox`.
The actual commands are implemented in :mod:`celery.worker.control`.
"""
from celery import bootsteps
from celery.utils.log import get_logger
from celery.worker import pidbox
from .tasks import Tasks
__all__ = ('Co... | 34 | 946 |
celery | celery/worker/consumer/delayed_delivery.py | .py | """Native delayed delivery functionality for Celery workers.
This module provides the DelayedDelivery bootstep which handles setup and configuration
of native delayed delivery functionality when using quorum queues.
"""
import sys
from typing import Iterator, List, Optional, Set, Union, ValuesView
if sys.version_info... | 280 | 10,236 |
celery | celery/worker/consumer/tasks.py | .py | """Worker Task Consumer Bootstep."""
from __future__ import annotations
from kombu.common import QoS, ignore_errors
from celery import bootsteps
from celery.utils.log import get_logger
from celery.utils.quorum_queues import detect_quorum_queues
from .mingle import Mingle
__all__ = ('Tasks',)
logger = get_logger(... | 125 | 4,308 |
celery | celery/worker/consumer/agent.py | .py | """Celery + :pypi:`cell` integration."""
from celery import bootsteps
from .connection import Connection
__all__ = ('Agent',)
class Agent(bootsteps.StartStopStep):
"""Agent starts :pypi:`cell` actors."""
conditional = True
requires = (Connection,)
def __init__(self, c, **kwargs):
self.agen... | 22 | 525 |
celery | celery/worker/consumer/events.py | .py | """Worker Event Dispatcher Bootstep.
``Events`` -> :class:`celery.events.EventDispatcher`.
"""
from kombu.common import ignore_errors
from celery import bootsteps
from celery.worker.state import reserved_requests
from .connection import Connection
__all__ = ('Events',)
class Events(bootsteps.StartStopStep):
"... | 72 | 2,197 |
celery | celery/app/trace.py | .py | """Trace task execution.
This module defines how the task execution is traced:
errors are recorded, handlers are applied and so on.
"""
import logging
import os
import sys
import time
from collections import namedtuple
from warnings import warn
from billiard.einfo import ExceptionInfo, ExceptionWithTraceback
from kom... | 874 | 34,266 |
celery | celery/app/utils.py | .py | """App utilities: Compat settings, bug-report tool, pickling apps."""
import os
import platform as _platform
import re
from collections import namedtuple
from collections.abc import Mapping
from copy import deepcopy
from types import ModuleType
from kombu.utils.url import maybe_sanitize_url
from celery.exceptions imp... | 416 | 13,171 |
celery | celery/app/backends.py | .py | """Backend selection."""
import sys
import types
from celery._state import current_app
from celery.exceptions import ImproperlyConfigured, reraise
from celery.utils.imports import load_extension_class_names, symbol_by_name
__all__ = ('by_name', 'by_url')
UNKNOWN_BACKEND = """
Unknown result backend: {0!r}. Did you ... | 70 | 2,746 |
celery | celery/app/__init__.py | .py | """Celery Application."""
from celery import _state
from celery._state import app_or_default, disable_trace, enable_trace, pop_current_task, push_current_task
from celery.local import Proxy
from .base import Celery
from .utils import AppPickler
__all__ = (
'Celery', 'AppPickler', 'app_or_default', 'default_app',
... | 77 | 2,430 |
celery | celery/app/amqp.py | .py | """Sending/Receiving Messages (Kombu integration)."""
import numbers
from collections import namedtuple
from collections.abc import Mapping
from datetime import timedelta
from weakref import WeakValueDictionary
from kombu import Connection, Consumer, Exchange, Producer, Queue, pools
from kombu.common import Broadcast
... | 664 | 25,857 |
celery | celery/app/registry.py | .py | """Registry of available tasks."""
import inspect
from importlib import import_module
from celery._state import get_current_app
from celery.app.autoretry import add_autoretry_behaviour
from celery.exceptions import InvalidTaskError, NotRegistered
__all__ = ('TaskRegistry',)
class TaskRegistry(dict):
"""Map of r... | 69 | 2,001 |
celery | celery/app/builtins.py | .py | """Built-in Tasks.
The built-in tasks are always available in all app instances.
"""
from celery._state import connect_on_app_finalize
from celery.utils.log import get_logger
__all__ = ()
logger = get_logger(__name__)
@connect_on_app_finalize
def add_backend_cleanup_task(app):
"""Task used to clean up expired r... | 187 | 6,831 |
celery | celery/app/autoretry.py | .py | """Tasks auto-retry functionality."""
from vine.utils import wraps
from celery.exceptions import Ignore, Retry
from celery.utils.time import get_exponential_backoff_interval
def add_autoretry_behaviour(task, **options):
"""Wrap task's `run` method with auto-retry functionality."""
autoretry_for = tuple(
... | 67 | 2,506 |
celery | celery/app/defaults.py | .py | """Configuration introspection and defaults."""
from collections import deque, namedtuple
from datetime import timedelta
from celery.utils.functional import memoize
from celery.utils.serialization import strtobool
__all__ = ('Option', 'NAMESPACES', 'flatten', 'find')
DEFAULT_POOL = 'prefork'
DEFAULT_ACCEPT_CONTENT... | 448 | 16,549 |
celery | celery/app/control.py | .py | """Worker Remote Control Client.
Client for worker remote control commands.
Server implementation is in :mod:`celery.worker.control`.
There are two types of remote control commands:
* Inspect commands: Does not have side effects, will usually just return some value
found in the worker, like the list of currently re... | 791 | 29,737 |
celery | celery/app/routes.py | .py | """Task Routing.
Contains utilities for working with task routers, (:setting:`task_routes`).
"""
import fnmatch
import re
from collections import OrderedDict
from collections.abc import Mapping
from kombu import Queue
from celery.exceptions import QueueNotFound
from celery.utils.collections import lpmerge
from celer... | 137 | 4,551 |
celery | celery/app/task.py | .py | """Task implementation: request context and the task base class."""
import sys
import types
from billiard.einfo import ExceptionInfo, ExceptionWithTraceback
from kombu import serialization
from kombu.exceptions import OperationalError
from kombu.utils.uuid import uuid
from celery import current_app, states
from celer... | 1,288 | 49,763 |
celery | celery/app/log.py | .py | """Logging configuration.
The Celery instances logging section: ``Celery.log``.
Sets up logging for the worker and other programs,
redirects standard outs, colors log output, patches logging
related compatibility fixes, and so on.
"""
import logging
import os
import sys
import warnings
from logging.handlers import Wa... | 249 | 9,102 |
celery | celery/app/annotations.py | .py | """Task Annotations.
Annotations is a nice term for monkey-patching task classes
in the configuration.
This prepares and performs the annotations in the
:setting:`task_annotations` setting.
"""
from celery.utils.functional import firstmethod, mlazy
from celery.utils.imports import instantiate
_first_match = firstmet... | 53 | 1,445 |
celery | celery/app/base.py | .py | """Actual App instance implementation."""
import functools
import importlib
import inspect
import os
import sys
import threading
import types
import typing
import warnings
from collections import UserDict, defaultdict, deque
from datetime import datetime
from datetime import timezone as datetime_timezone
from operator ... | 1,636 | 62,113 |
celery | celery/app/events.py | .py | """Implementation for the app.events shortcuts."""
from contextlib import contextmanager
from kombu.utils.objects import cached_property
class Events:
"""Implements app.events."""
receiver_cls = 'celery.events.receiver:EventReceiver'
dispatcher_cls = 'celery.events.dispatcher:EventDispatcher'
state_... | 41 | 1,326 |
redash | manage.py | .py | #!/usr/bin/env python
"""
CLI to manage redash.
"""
from redash.cli import manager
if __name__ == "__main__":
manager()
| 10 | 126 |
redash | bin/release_manager.py | .py | #!/usr/bin/env python3
import os
import re
import subprocess
import sys
from urllib.parse import urlparse
import requests
import simplejson
github_token = os.environ["GITHUB_TOKEN"]
auth = (github_token, "x-oauth-basic")
repo = "getredash/redash"
def _github_request(method, path, params=None, headers={}):
if ur... | 173 | 5,062 |
redash | bin/get_changes.py | .py | #!/bin/env python3
import re
import subprocess
import sys
def get_change_log(previous_sha):
args = [
"git",
"--no-pager",
"log",
"--merges",
"--grep",
"Merge pull request",
'--pretty=format:"%h|%s|%b|%p"',
"master...{}".format(previous_sha),
]
... | 47 | 1,128 |
redash | tests/test_configuration.py | .py | from unittest import TestCase
from jsonschema import ValidationError
from redash.utils.configuration import ConfigurationContainer
configuration_schema = {
"type": "object",
"properties": {
"a": {"type": "integer"},
"e": {"type": "integer"},
"b": {"type": "string"},
},
"requir... | 77 | 2,677 |
redash | tests/test_monitor.py | .py | from unittest.mock import MagicMock, patch
from redash import rq_redis_connection
from redash.monitor import rq_job_ids
def test_rq_job_ids_uses_rq_redis_connection():
mock_queue = MagicMock()
mock_queue.job_ids = []
mock_registry = MagicMock()
mock_registry.get_job_ids.return_value = []
with p... | 24 | 737 |
redash | tests/test_migrations.py | .py | import os
from alembic.config import Config
from alembic.script import ScriptDirectory
def test_only_single_head_revision_in_migrations():
"""
If multiple developers are working on migrations and one of them is merged before the
other you might end up with multiple heads (multiple revisions with the same... | 22 | 775 |
redash | tests/__init__.py | .py | import datetime
import logging
import os
from contextlib import contextmanager
from unittest import TestCase
os.environ["REDASH_REDIS_URL"] = os.environ.get("REDASH_REDIS_URL", "redis://localhost:6379/0").replace("/0", "/5")
# Use different url for RQ to avoid DB being cleaned up:
os.environ["RQ_REDIS_URL"] = os.envir... | 139 | 3,863 |
redash | tests/factories.py | .py | from passlib.apps import custom_app_context as pwd_context
import redash.models
from redash.models import db
from redash.permissions import ACCESS_TYPE_MODIFY
from redash.utils import gen_query_hash, utcnow
from redash.utils.configuration import ConfigurationContainer
class ModelFactory:
def __init__(self, model... | 334 | 9,294 |
redash | tests/test_authentication.py | .py | import importlib
import json
import os
import subprocess
import time
import jwcrypto.jwk
import jwt
import requests
from flask import request
from mock import Mock, patch
from sqlalchemy.orm.exc import NoResultFound
from redash import models, settings
from redash.authentication import (
api_key_load_user_from_req... | 545 | 20,875 |
redash | tests/test_permissions.py | .py | from collections import namedtuple
from redash import models
from redash.permissions import has_access
from tests import BaseTestCase
MockUser = namedtuple("MockUser", ["permissions", "group_ids"])
view_only = True
class TestHasAccess(BaseTestCase):
def test_allows_admin_regardless_of_groups(self):
user... | 67 | 2,702 |
redash | tests/test_models.py | .py | import calendar
import datetime
from unittest import TestCase
from dateutil.parser import parse as date_parse
from redash import models
from redash.models import db
from redash.utils import gen_query_hash, utcnow
from tests import BaseTestCase
class DashboardTest(BaseTestCase):
def test_appends_suffix_to_slug_w... | 683 | 27,899 |
redash | tests/test_handlers.py | .py | from flask_login import current_user
from funcy import project
from mock import patch
from redash import models, settings
from tests import BaseTestCase, authenticated_user
class AuthenticationTestMixin:
def test_returns_404_when_not_unauthenticated(self):
for path in self.paths:
rv = self.cl... | 323 | 12,223 |
redash | tests/test_cli.py | .py | import textwrap
import mock
from click.testing import CliRunner
from redash.cli import manager
from redash.models import DataSource, Group, Organization, User, db
from redash.query_runner import query_runners
from redash.utils.configuration import ConfigurationContainer
from tests import BaseTestCase
class DataSour... | 569 | 20,135 |
redash | tests/test_utils.py | .py | from collections import namedtuple
from unittest import TestCase
import pytest
from redash import create_app
from redash.query_runner import (
TYPE_BOOLEAN,
TYPE_DATE,
TYPE_DATETIME,
TYPE_FLOAT,
TYPE_INTEGER,
TYPE_STRING,
)
from redash.utils import (
build_url,
collect_parameters_from_... | 163 | 5,099 |
redash | tests/serializers/test_query_results.py | .py | import csv
import io
from redash.serializers import (
serialize_query_result,
serialize_query_result_to_dsv,
)
from tests import BaseTestCase
data = {
"rows": [
{"datetime": "2019-05-26T12:39:23.026Z", "bool": True, "date": "2019-05-26"},
{"datetime": "", "bool": False, "date": ""},
... | 82 | 3,245 |
redash | tests/query_runner/test_elasticsearch2.py | .py | from unittest import TestCase, mock
from redash.query_runner.elasticsearch2 import (
ElasticSearch2,
XPackSQLElasticSearch,
)
class TestElasticSearch(TestCase):
def test_parse_mappings(self):
mapping_data = {
"bank": {
"mappings": {
"properties": {
... | 151 | 6,081 |
redash | tests/query_runner/test_clickhouse.py | .py | import json
from unittest import TestCase
from unittest.mock import Mock, patch
from redash.query_runner import TYPE_INTEGER
from redash.query_runner.clickhouse import ClickHouse, split_multi_query
split_multi_query_samples = [
# Regular query
("SELECT 1", ["SELECT 1"]),
# Multiple data queries inlined
... | 185 | 4,980 |
redash | tests/query_runner/test_google_spreadsheets.py | .py | import datetime
from unittest import TestCase
import pytest
from google.auth.exceptions import TransportError
from gspread.exceptions import APIError
from mock import MagicMock, patch
from redash.query_runner import TYPE_DATETIME, TYPE_FLOAT
from redash.query_runner.google_spreadsheets import (
TYPE_BOOLEAN,
... | 207 | 7,367 |
redash | tests/query_runner/test_prometheus.py | .py | import time
from datetime import datetime
from unittest import TestCase
import mock
from redash.query_runner.prometheus import Prometheus, get_instant_rows, get_range_rows
class TestPrometheus(TestCase):
def setUp(self):
self.instant_query_result = [
{
"metric": {"name": "exa... | 540 | 20,577 |
redash | tests/query_runner/test_script.py | .py | import os
import subprocess
from _pytest.monkeypatch import MonkeyPatch
from redash.query_runner.script import query_to_script_path, run_script
from tests import BaseTestCase
class TestQueryToScript(BaseTestCase):
monkeypatch = MonkeyPatch()
def test_unspecified(self):
self.assertEqual("/foo/bar/ba... | 37 | 1,500 |
redash | tests/query_runner/test_influx_db_v2.py | .py | import mock
import pytest
from influxdb_client.client.flux_table import (
FluxColumn,
FluxRecord,
FluxTable,
TableList,
)
from redash.query_runner.influx_db_v2 import InfluxDBv2
@pytest.fixture()
def influx_table_list():
tables = TableList()
table_1 = FluxTable()
table_2 = FluxTable()
... | 340 | 13,383 |
redash | tests/query_runner/test_yandex_disk.py | .py | from io import BytesIO
from unittest import mock
import yaml
from redash.query_runner.yandex_disk import enabled
if enabled:
import pandas as pd
from redash.query_runner.yandex_disk import EXTENSIONS_READERS, YandexDisk
test_df = pd.DataFrame(
[
{"id": 1, "name": "Alice", "age": 20}... | 246 | 7,719 |
redash | tests/query_runner/test_mongodb.py | .py | import datetime
from unittest import TestCase
from freezegun import freeze_time
from mock import patch
from pytz import utc
from redash.query_runner import TYPE_INTEGER, TYPE_STRING
from redash.query_runner.mongodb import (
MongoDB,
_get_column_by_name,
parse_query_json,
parse_results,
)
from redash.u... | 293 | 10,915 |
redash | tests/query_runner/test_ignite.py | .py | import datetime
from unittest import TestCase
from redash.query_runner.ignite import Ignite
class TestIgnite(TestCase):
def test_server_to_connection(self):
config = {
"server": "localhost,localhost:10801,invalid:port:100",
}
ignite = Ignite(config)
server = ignite.co... | 62 | 2,026 |
redash | tests/query_runner/test_jql.py | .py | from unittest import TestCase
from redash.query_runner.jql import FieldMapping, parse_issue
class TestFieldMapping(TestCase):
def test_empty(self):
field_mapping = FieldMapping({})
self.assertEqual(field_mapping.get_output_field_name("field1"), "field1")
self.assertEqual(field_mapping.ge... | 126 | 5,169 |
redash | tests/query_runner/test_athena.py | .py | """
Some test cases around the Glue catalog.
"""
from unittest import TestCase
import botocore
import mock
from botocore.stub import Stubber
from redash.query_runner.athena import Athena
class TestGlueSchema(TestCase):
def setUp(self):
client = botocore.session.get_session().create_client(
... | 327 | 14,071 |
redash | tests/query_runner/test_azure_kusto.py | .py | from unittest import TestCase
from unittest.mock import patch
from redash.query_runner.azure_kusto import AzureKusto
class TestAzureKusto(TestCase):
def setUp(self):
self.configuration = {
"cluster": "https://example.kusto.windows.net",
"database": "sample_db",
"azure_... | 43 | 1,712 |
redash | tests/query_runner/test_cass.py | .py | import ssl
from unittest import TestCase
from redash.query_runner.cass import generate_ssl_options_dict
class TestCassandra(TestCase):
def test_generate_ssl_options_dict_creates_plain_protocol_dict(self):
expected = {"ssl_version": ssl.PROTOCOL_TLSv1_2}
actual = generate_ssl_options_dict("PROTOCO... | 21 | 735 |
redash | tests/query_runner/test_databricks.py | .py | from unittest import TestCase
from redash.query_runner import split_sql_statements
class TestSplitMultipleSQLStatements(TestCase):
def _assertSplitSql(self, sql, expected_stmt):
stmt = split_sql_statements(sql)
# ignore leading and trailing whitespaces when comparing
self.assertListEqual(... | 124 | 3,171 |
redash | tests/query_runner/test_bigquery.py | .py | import unittest
from redash.query_runner.big_query import BigQuery
class TestBigQueryQueryRunner(unittest.TestCase):
def test_annotate_query_with_use_query_annotation_option(self):
query_runner = BigQuery({"useQueryAnnotation": True})
self.assertTrue(query_runner.should_annotate_query)
... | 46 | 1,351 |
redash | tests/query_runner/test_basequeryrunner.py | .py | import unittest
from redash.query_runner import BaseQueryRunner
class TestBaseQueryRunner(unittest.TestCase):
def setUp(self):
self.query_runner = BaseQueryRunner({})
def test_duplicate_column_names_assigned_correctly(self):
original_column_names = [
("name", bool),
(... | 35 | 1,156 |
redash | tests/query_runner/test_drill.py | .py | import datetime
from unittest import TestCase
from redash.query_runner import (
TYPE_BOOLEAN,
TYPE_DATETIME,
TYPE_FLOAT,
TYPE_INTEGER,
TYPE_STRING,
)
from redash.query_runner.drill import convert_type, parse_response
class TestConvertType(TestCase):
def test_converts_booleans(self):
s... | 99 | 3,520 |
redash | tests/query_runner/test_e6data.py | .py | from unittest.mock import patch
from redash.query_runner import TYPE_INTEGER, TYPE_STRING
from redash.query_runner.e6data import e6data
runner = e6data(
{
"username": "test_user",
"password": "test_password",
"host": "test_host",
"port": 80,
"catalog": "test_catalog",
... | 90 | 2,575 |
redash | tests/query_runner/test_basesql_queryrunner.py | .py | import unittest
from redash.query_runner import BaseQueryRunner, BaseSQLQueryRunner
from redash.utils import gen_query_hash
class TestBaseSQLQueryRunner(unittest.TestCase):
def setUp(self):
self.query_runner = BaseSQLQueryRunner({})
def test_check_query_limit_no_limit(self):
query = "SELECT ... | 135 | 6,413 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.