Skip to content

Commit

Permalink
Format all files with black.
Browse files Browse the repository at this point in the history
  • Loading branch information
Black Formatting authored and a-feld committed Aug 26, 2019
1 parent a753908 commit 0664015
Show file tree
Hide file tree
Showing 24 changed files with 378 additions and 344 deletions.
37 changes: 19 additions & 18 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,65 +12,66 @@

import os
import sys
sys.path.insert(0, os.path.abspath('../opentelemetry-api/src/'))

sys.path.insert(0, os.path.abspath("../opentelemetry-api/src/"))


# -- Project information -----------------------------------------------------

project = 'OpenTelemetry'
copyright = '2019, OpenTelemetry Authors'
author = 'OpenTelemetry Authors'
project = "OpenTelemetry"
copyright = "2019, OpenTelemetry Authors"
author = "OpenTelemetry Authors"


# -- General configuration ---------------------------------------------------

# Easy automatic cross-references for `code in backticks`
default_role = 'any'
default_role = "any"

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
# API doc generation
'sphinx.ext.autodoc',
"sphinx.ext.autodoc",
# Support for google-style docstrings
'sphinx.ext.napoleon',
"sphinx.ext.napoleon",
# Infer types from hints instead of docstrings
'sphinx_autodoc_typehints',
"sphinx_autodoc_typehints",
# Add links to source from generated docs
'sphinx.ext.viewcode',
"sphinx.ext.viewcode",
# Link to other sphinx docs
'sphinx.ext.intersphinx',
"sphinx.ext.intersphinx",
]

intersphinx_mapping = {'python': ('https://docs.python.org/3/', None)}
intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}

# http://www.sphinx-doc.org/en/master/config.html#confval-nitpicky
# Sphinx will warn about all references where the target cannot be found.
nitpicky = True
nitpick_ignore = []

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

autodoc_default_options = {
'members': True,
'undoc-members': True,
'show-inheritance': True,
'member-order': 'bysource'
"members": True,
"undoc-members": True,
"show-inheritance": True,
"member-order": "bysource",
}

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
Expand Down
7 changes: 1 addition & 6 deletions ext/opentelemetry-ext-wsgi/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,7 @@

BASE_DIR = os.path.dirname(__file__)
VERSION_FILENAME = os.path.join(
BASE_DIR,
"src",
"opentelemetry",
"ext",
"wsgi",
"version.py",
BASE_DIR, "src", "opentelemetry", "ext", "wsgi", "version.py"
)
PACKAGE_INFO = {}
with open(VERSION_FILENAME) as f:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,7 @@ class OpenTelemetryMiddleware:
wsgi: The WSGI application callable.
"""

def __init__(
self,
wsgi,
propagators=None,
):
def __init__(self, wsgi, propagators=None):
self.wsgi = wsgi

# TODO: implement context propagation
Expand All @@ -54,9 +50,9 @@ def _add_request_attributes(span, environ):
span.set_attribute("http.host", host)

url = (
environ.get("REQUEST_URI") or
environ.get("RAW_URI") or
wsgiref_util.request_uri(environ, include_query=False)
environ.get("REQUEST_URI")
or environ.get("RAW_URI")
or wsgiref_util.request_uri(environ, include_query=False)
)
span.set_attribute("http.url", url)

Expand Down Expand Up @@ -101,5 +97,5 @@ def __call__(self, environ, start_response):
for yielded in iterable:
yield yielded
finally:
if hasattr(iterable, 'close'):
if hasattr(iterable, "close"):
iterable.close()
21 changes: 9 additions & 12 deletions ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def iter_wsgi(environ, start_response):
assert isinstance(environ, dict)
start_response("200 OK", [("Content-Type", "text/plain")])
return response

return iter_wsgi


Expand All @@ -66,10 +67,9 @@ class TestWsgiApplication(unittest.TestCase):
def setUp(self):
tracer = trace_api.tracer()
self.span_context_manager = mock.MagicMock()
self.span_context_manager.__enter__.return_value = \
mock.create_autospec(
trace_api.Span, spec_set=True
)
self.span_context_manager.__enter__.return_value = mock.create_autospec(
trace_api.Span, spec_set=True
)
self.patcher = mock.patch.object(
tracer,
"start_span",
Expand Down Expand Up @@ -115,8 +115,7 @@ def validate_response(self, response, error=None):

self.assertEqual(self.status, "200 OK")
self.assertEqual(
self.response_headers,
[("Content-Type", "text/plain")]
self.response_headers, [("Content-Type", "text/plain")]
)
if error:
self.assertIs(self.exc_info[0], error)
Expand Down Expand Up @@ -159,8 +158,7 @@ def setUp(self):

def test_request_attributes(self):
OpenTelemetryMiddleware._add_request_attributes( # noqa pylint: disable=protected-access
self.span,
self.environ,
self.span, self.environ
)
expected = (
mock.call("component", "http"),
Expand All @@ -173,7 +171,7 @@ def test_request_attributes(self):

def test_response_attributes(self):
OpenTelemetryMiddleware._add_response_attributes( # noqa pylint: disable=protected-access
self.span, "404 Not Found",
self.span, "404 Not Found"
)
expected = (
mock.call("http.status_code", 404),
Expand All @@ -184,12 +182,11 @@ def test_response_attributes(self):

def test_response_attributes_invalid_status_code(self):
OpenTelemetryMiddleware._add_response_attributes( # noqa pylint: disable=protected-access
self.span, "Invalid Status Code",
self.span, "Invalid Status Code"
)
self.assertEqual(self.span.set_attribute.call_count, 1)
self.span.set_attribute.assert_called_with(
"http.status_text",
"Status Code",
"http.status_text", "Status Code"
)


Expand Down
15 changes: 8 additions & 7 deletions opentelemetry-api/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,16 @@
description="OpenTelemetry Python API",
include_package_data=True,
long_description=open("README.rst").read(),
install_requires=[
"typing; python_version<'3.5'",
],
install_requires=["typing; python_version<'3.5'"],
extras_require={},
license="Apache-2.0",
package_dir={"": "src"},
packages=setuptools.find_namespace_packages(where="src",
include="opentelemetry.*"),
url=("https://github.com/open-telemetry/opentelemetry-python"
"/tree/master/opentelemetry-api"),
packages=setuptools.find_namespace_packages(
where="src", include="opentelemetry.*"
),
url=(
"https://github.com/open-telemetry/opentelemetry-python"
"/tree/master/opentelemetry-api"
),
zip_safe=False,
)
4 changes: 3 additions & 1 deletion opentelemetry-api/src/opentelemetry/context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ async def main():

from .base_context import BaseRuntimeContext

__all__ = ['Context']
__all__ = ["Context"]


Context = ( # pylint: disable=invalid-name
Expand All @@ -151,7 +151,9 @@ async def main():

try:
from .async_context import AsyncRuntimeContext

Context = AsyncRuntimeContext() # pylint:disable=invalid-name
except ImportError:
from .thread_local_context import ThreadLocalRuntimeContext

Context = ThreadLocalRuntimeContext() # pylint:disable=invalid-name
6 changes: 3 additions & 3 deletions opentelemetry-api/src/opentelemetry/context/async_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

class AsyncRuntimeContext(base_context.BaseRuntimeContext):
class Slot(base_context.BaseRuntimeContext.Slot):
def __init__(self, name: str, default: 'object'):
def __init__(self, name: str, default: "object"):
# pylint: disable=super-init-not-called
self.name = name
self.contextvar = ContextVar(name) # type: ContextVar[object]
Expand All @@ -31,13 +31,13 @@ def __init__(self, name: str, default: 'object'):
def clear(self) -> None:
self.contextvar.set(self.default())

def get(self) -> 'object':
def get(self) -> "object":
try:
return self.contextvar.get()
except LookupError:
value = self.default()
self.set(value)
return value

def set(self, value: 'object') -> None:
def set(self, value: "object") -> None:
self.contextvar.set(value)
38 changes: 17 additions & 21 deletions opentelemetry-api/src/opentelemetry/context/base_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,24 @@
import typing


def wrap_callable(target: 'object') -> typing.Callable[[], object]:
def wrap_callable(target: "object") -> typing.Callable[[], object]:
if callable(target):
return target
return lambda: target


class BaseRuntimeContext:
class Slot:
def __init__(self, name: str, default: 'object'):
def __init__(self, name: str, default: "object"):
raise NotImplementedError

def clear(self) -> None:
raise NotImplementedError

def get(self) -> 'object':
def get(self) -> "object":
raise NotImplementedError

def set(self, value: 'object') -> None:
def set(self, value: "object") -> None:
raise NotImplementedError

_lock = threading.Lock()
Expand All @@ -49,10 +49,8 @@ def clear(cls) -> None:

@classmethod
def register_slot(
cls,
name: str,
default: 'object' = None,
) -> 'BaseRuntimeContext.Slot':
cls, name: str, default: "object" = None
) -> "BaseRuntimeContext.Slot":
"""Register a context slot with an optional default value.
:type name: str
Expand All @@ -68,52 +66,50 @@ def register_slot(
cls._slots[name] = cls.Slot(name, default)
return cls._slots[name]

def apply(self, snapshot: typing.Dict[str, 'object']) -> None:
def apply(self, snapshot: typing.Dict[str, "object"]) -> None:
"""Set the current context from a given snapshot dictionary"""

for name in snapshot:
setattr(self, name, snapshot[name])

def snapshot(self) -> typing.Dict[str, 'object']:
def snapshot(self) -> typing.Dict[str, "object"]:
"""Return a dictionary of current slots by reference."""

keys = self._slots.keys()
return dict((n, self._slots[n].get()) for n in keys)

def __repr__(self) -> str:
return '{}({})'.format(type(self).__name__, self.snapshot())
return "{}({})".format(type(self).__name__, self.snapshot())

def __getattr__(self, name: str) -> 'object':
def __getattr__(self, name: str) -> "object":
if name not in self._slots:
self.register_slot(name, None)
slot = self._slots[name]
return slot.get()

def __setattr__(self, name: str, value: 'object') -> None:
def __setattr__(self, name: str, value: "object") -> None:
if name not in self._slots:
self.register_slot(name, None)
slot = self._slots[name]
slot.set(value)

def __getitem__(self, name: str) -> 'object':
def __getitem__(self, name: str) -> "object":
return self.__getattr__(name)

def __setitem__(self, name: str, value: 'object') -> None:
def __setitem__(self, name: str, value: "object") -> None:
self.__setattr__(name, value)

def with_current_context(
self,
func: typing.Callable[..., 'object'],
) -> typing.Callable[..., 'object']:
self, func: typing.Callable[..., "object"]
) -> typing.Callable[..., "object"]:
"""Capture the current context and apply it to the provided func.
"""

caller_context = self.snapshot()

def call_with_current_context(
*args: 'object',
**kwargs: 'object'
) -> 'object':
*args: "object", **kwargs: "object"
) -> "object":
try:
backup_context = self.snapshot()
self.apply(caller_context)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class BinaryFormat(abc.ABC):
This class provides an interface that enables converting span contexts
to and from a binary format.
"""

@staticmethod
@abc.abstractmethod
def to_bytes(context: SpanContext) -> bytes:
Expand All @@ -39,6 +40,7 @@ def to_bytes(context: SpanContext) -> bytes:
A bytes representation of the SpanContext.
"""

@staticmethod
@abc.abstractmethod
def from_bytes(byte_representation: bytes) -> typing.Optional[SpanContext]:
Expand Down
Loading

0 comments on commit 0664015

Please sign in to comment.