From 45a2b350e54da9f99a718148d257ee4e28b1d8e4 Mon Sep 17 00:00:00 2001 From: alrex Date: Mon, 20 Sep 2021 08:32:05 -0700 Subject: [PATCH 1/2] use f-strings (#2131) Co-authored-by: Owais Lone --- .../exporter/jaeger/thrift/send.py | 4 +- .../tests/test_otlp_trace_exporter.py | 8 +--- .../exporter/zipkin/node_endpoint.py | 4 +- .../src/opentelemetry/attributes/__init__.py | 4 +- .../src/opentelemetry/trace/__init__.py | 2 +- .../trace/propagation/tracecontext.py | 6 +-- .../src/opentelemetry/trace/span.py | 19 ++-------- .../src/opentelemetry/util/_providers.py | 4 +- .../auto_instrumentation/sitecustomize.py | 2 +- .../instrumentation/bootstrap.py | 10 ++--- .../instrumentation/dependencies.py | 4 +- .../instrumentation/propagators.py | 8 +--- .../tests/test_dependencies.py | 4 +- .../sdk/_configuration/__init__.py | 10 ++--- .../src/opentelemetry/sdk/trace/__init__.py | 37 +++++-------------- .../src/opentelemetry/sdk/trace/sampling.py | 14 ++----- .../src/opentelemetry/sdk/util/__init__.py | 8 ++-- .../opentelemetry/sdk/util/instrumentation.py | 4 +- .../tests/trace/export/test_export.py | 2 +- opentelemetry-sdk/tests/trace/test_trace.py | 19 ++++------ .../tests/test_b3_format.py | 14 ++----- .../propagators/jaeger/__init__.py | 7 +--- scripts/eachdist.py | 32 ++++++++-------- scripts/public_symbols_checker.py | 4 +- .../test_asyncio.py | 2 +- .../test_threads.py | 2 +- .../test_listener_per_request/test_asyncio.py | 2 +- .../test_listener_per_request/test_threads.py | 2 +- .../test_nested_callbacks/test_asyncio.py | 2 +- .../test_nested_callbacks/test_threads.py | 2 +- .../test_asyncio.py | 2 +- .../test_threads.py | 2 +- .../src/opentelemetry/test/spantestutil.py | 6 +-- .../util/src/opentelemetry/test/test_base.py | 4 +- 34 files changed, 85 insertions(+), 171 deletions(-) diff --git a/exporter/opentelemetry-exporter-jaeger-thrift/src/opentelemetry/exporter/jaeger/thrift/send.py b/exporter/opentelemetry-exporter-jaeger-thrift/src/opentelemetry/exporter/jaeger/thrift/send.py index c7827038b19..9ddc6d7b27e 100644 --- a/exporter/opentelemetry-exporter-jaeger-thrift/src/opentelemetry/exporter/jaeger/thrift/send.py +++ b/exporter/opentelemetry-exporter-jaeger-thrift/src/opentelemetry/exporter/jaeger/thrift/send.py @@ -123,9 +123,9 @@ def __init__(self, thrift_url="", auth=None, timeout_in_millis=None): # set basic auth header if auth is not None: - auth_header = "{}:{}".format(*auth) + auth_header = f"{auth[0]}:{auth[1]}" decoded = base64.b64encode(auth_header.encode()).decode("ascii") - basic_auth = dict(Authorization="Basic {}".format(decoded)) + basic_auth = dict(Authorization=f"Basic {decoded}") self.http_transport.setCustomHeaders(basic_auth) def submit(self, batch: jaeger.Batch): diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_trace_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_trace_exporter.py index 1a244b00674..198ff442718 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_trace_exporter.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_trace_exporter.py @@ -320,16 +320,12 @@ def test_otlp_exporter_endpoint(self, mock_secure, mock_insecure): self.assertEqual( 1, mock_method.call_count, - "expected {} to be called for {} {}".format( - mock_method, endpoint, insecure - ), + f"expected {mock_method} to be called for {endpoint} {insecure}", ) self.assertEqual( expected_endpoint, mock_method.call_args[0][0], - "expected {} got {} {}".format( - expected_endpoint, mock_method.call_args[0][0], endpoint - ), + f"expected {expected_endpoint} got {mock_method.call_args[0][0]} {endpoint}", ) mock_method.reset_mock() diff --git a/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/node_endpoint.py b/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/node_endpoint.py index ee7cb71f02b..67f5d0ad12f 100644 --- a/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/node_endpoint.py +++ b/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/node_endpoint.py @@ -64,7 +64,7 @@ def ipv4(self, address: IpInput) -> None: ipv4_address = ipaddress.ip_address(address) if not isinstance(ipv4_address, ipaddress.IPv4Address): raise ValueError( - "%r does not appear to be an IPv4 address" % address + f"{address!r} does not appear to be an IPv4 address" ) self._ipv4 = ipv4_address @@ -80,6 +80,6 @@ def ipv6(self, address: IpInput) -> None: ipv6_address = ipaddress.ip_address(address) if not isinstance(ipv6_address, ipaddress.IPv6Address): raise ValueError( - "%r does not appear to be an IPv6 address" % address + f"{address!r} does not appear to be an IPv6 address" ) self._ipv6 = ipv6_address diff --git a/opentelemetry-api/src/opentelemetry/attributes/__init__.py b/opentelemetry-api/src/opentelemetry/attributes/__init__.py index 7fd185f3176..20d9ae91e1d 100644 --- a/opentelemetry-api/src/opentelemetry/attributes/__init__.py +++ b/opentelemetry-api/src/opentelemetry/attributes/__init__.py @@ -153,8 +153,8 @@ def __init__( self._immutable = immutable def __repr__(self): - return "{}({}, maxlen={})".format( - type(self).__name__, dict(self._dict), self.maxlen + return ( + f"{type(self).__name__}({dict(self._dict)}, maxlen={self.maxlen})" ) def __getitem__(self, key): diff --git a/opentelemetry-api/src/opentelemetry/trace/__init__.py b/opentelemetry-api/src/opentelemetry/trace/__init__.py index 58d75bbea88..482d43a044e 100644 --- a/opentelemetry-api/src/opentelemetry/trace/__init__.py +++ b/opentelemetry-api/src/opentelemetry/trace/__init__.py @@ -537,7 +537,7 @@ def use_span( span.set_status( Status( status_code=StatusCode.ERROR, - description="{}: {}".format(type(exc).__name__, exc), + description=f"{type(exc).__name__}: {exc}", ) ) raise diff --git a/opentelemetry-api/src/opentelemetry/trace/propagation/tracecontext.py b/opentelemetry-api/src/opentelemetry/trace/propagation/tracecontext.py index 3fc1f2bd665..14b68876b30 100644 --- a/opentelemetry-api/src/opentelemetry/trace/propagation/tracecontext.py +++ b/opentelemetry-api/src/opentelemetry/trace/propagation/tracecontext.py @@ -100,11 +100,7 @@ def inject( span_context = span.get_span_context() if span_context == trace.INVALID_SPAN_CONTEXT: return - traceparent_string = "00-{trace_id}-{span_id}-{:02x}".format( - span_context.trace_flags, - trace_id=format_trace_id(span_context.trace_id), - span_id=format_span_id(span_context.span_id), - ) + traceparent_string = f"00-{format_trace_id(span_context.trace_id)}-{format_span_id(span_context.span_id)}-{span_context.trace_flags:02x}" setter.set(carrier, self._TRACEPARENT_HEADER_NAME, traceparent_string) if span_context.trace_state: tracestate_string = span_context.trace_state.to_header() diff --git a/opentelemetry-api/src/opentelemetry/trace/span.py b/opentelemetry-api/src/opentelemetry/trace/span.py index 832b8b62f6a..239fbfd3af8 100644 --- a/opentelemetry-api/src/opentelemetry/trace/span.py +++ b/opentelemetry-api/src/opentelemetry/trace/span.py @@ -40,9 +40,7 @@ _TRACECONTEXT_MAXIMUM_TRACESTATE_KEYS = 32 _delimiter_pattern = re.compile(r"[ \t]*,[ \t]*") -_member_pattern = re.compile( - "({})(=)({})[ \t]*".format(_KEY_FORMAT, _VALUE_FORMAT) -) +_member_pattern = re.compile(f"({_KEY_FORMAT})(=)({_VALUE_FORMAT})[ \t]*") _logger = logging.getLogger(__name__) @@ -245,7 +243,7 @@ def __len__(self) -> int: def __repr__(self) -> str: pairs = [ - "{key=%s, value=%s}" % (key, value) + f"{{key={key}, value={value}}}" for key, value in self._dict.items() ] return str(pairs) @@ -478,16 +476,7 @@ def __delattr__(self, *args: str) -> None: ) def __repr__(self) -> str: - return ( - "{}(trace_id=0x{}, span_id=0x{}, trace_flags=0x{:02x}, trace_state={!r}, is_remote={})" - ).format( - type(self).__name__, - format_trace_id(self.trace_id), - format_span_id(self.span_id), - self.trace_flags, - self.trace_state, - self.is_remote, - ) + return f"{type(self).__name__}(trace_id=0x{format_trace_id(self.trace_id)}, span_id=0x{format_span_id(self.span_id)}, trace_flags=0x{self.trace_flags:02x}, trace_state={self.trace_state!r}, is_remote={self.is_remote})" class NonRecordingSpan(Span): @@ -540,7 +529,7 @@ def record_exception( pass def __repr__(self) -> str: - return "NonRecordingSpan({!r})".format(self._context) + return f"NonRecordingSpan({self._context!r})" INVALID_SPAN_ID = 0x0000000000000000 diff --git a/opentelemetry-api/src/opentelemetry/util/_providers.py b/opentelemetry-api/src/opentelemetry/util/_providers.py index 0e31f702ba6..98c75ed06bd 100644 --- a/opentelemetry-api/src/opentelemetry/util/_providers.py +++ b/opentelemetry-api/src/opentelemetry/util/_providers.py @@ -32,12 +32,12 @@ def _load_provider( try: entry_point = next( iter_entry_points( - "opentelemetry_{}".format(provider), + f"opentelemetry_{provider}", name=cast( str, environ.get( provider_environment_variable, - "default_{}".format(provider), + f"default_{provider}", ), ), ) diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py index 5bbf0685ff9..a4a5dc8d5a0 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py @@ -119,7 +119,7 @@ def initialize(): logger.exception("Failed to auto initialize opentelemetry") finally: environ["PYTHONPATH"] = sub( - r"{}{}?".format(dirname(abspath(__file__)), pathsep), + fr"{dirname(abspath(__file__))}{pathsep}?", "", environ["PYTHONPATH"], ) diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap.py index abeb23df3d1..7fe8de0ef03 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap.py @@ -38,11 +38,9 @@ def wrapper(package=None): except subprocess.SubprocessError as exp: cmd = getattr(exp, "cmd", None) if cmd: - msg = 'Error calling system command "{0}"'.format( - " ".join(cmd) - ) + msg = f'Error calling system command "{" ".join(cmd)}"' if package: - msg = '{0} for package "{1}"'.format(msg, package) + msg = f'{msg} for package "{package}"' raise RuntimeError(msg) return wrapper @@ -81,9 +79,7 @@ def _pip_check(): for package_tup in libraries.values(): for package in package_tup: if package.lower() in pip_check_lower: - raise RuntimeError( - "Dependency conflict found: {}".format(pip_check) - ) + raise RuntimeError(f"Dependency conflict found: {pip_check}") def _is_installed(req): diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/dependencies.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/dependencies.py index 0cec55769c3..6c65d6677e1 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/dependencies.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/dependencies.py @@ -21,9 +21,7 @@ def __init__(self, required, found=None): self.found = found def __str__(self): - return 'DependencyConflict: requested: "{0}" but found: "{1}"'.format( - self.required, self.found - ) + return f'DependencyConflict: requested: "{self.required}" but found: "{self.found}"' def get_dist_dependency_conflicts( diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/propagators.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/propagators.py index 4d6ce39eae8..bc40f7742c7 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/propagators.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/propagators.py @@ -54,7 +54,7 @@ class DictHeaderSetter(Setter): def set(self, carrier, key, value): # pylint: disable=no-self-use old_value = carrier.get(key, "") if old_value: - value = "{0}, {1}".format(old_value, value) + value = f"{old_value}, {value}" carrier[key] = value @@ -115,11 +115,7 @@ def inject( setter.set( carrier, header_name, - "00-{trace_id}-{span_id}-{:02x}".format( - span_context.trace_flags, - trace_id=format_trace_id(span_context.trace_id), - span_id=format_span_id(span_context.span_id), - ), + f"00-{format_trace_id(span_context.trace_id)}-{format_span_id(span_context.span_id)}-{span_context.trace_flags:02x}", ) setter.set( carrier, diff --git a/opentelemetry-instrumentation/tests/test_dependencies.py b/opentelemetry-instrumentation/tests/test_dependencies.py index 8b2f2e9b392..a8acac62f45 100644 --- a/opentelemetry-instrumentation/tests/test_dependencies.py +++ b/opentelemetry-instrumentation/tests/test_dependencies.py @@ -50,9 +50,7 @@ def test_get_dependency_conflicts_mismatched_version(self): self.assertTrue(isinstance(conflict, DependencyConflict)) self.assertEqual( str(conflict), - 'DependencyConflict: requested: "pytest == 5000" but found: "pytest {0}"'.format( - pytest.__version__ - ), + f'DependencyConflict: requested: "pytest == 5000" but found: "pytest {pytest.__version__}"', ) def test_get_dist_dependency_conflicts(self): diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py index 65bb92eb7ab..78bb1377801 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py @@ -91,9 +91,7 @@ def _import_tracer_provider_config_components( entry_point = component_entry_points.get(selected_component, None) if not entry_point: raise RuntimeError( - "Requested component '{}' not found in entry points for '{}'".format( - selected_component, entry_point_name - ) + f"Requested component '{selected_component}' not found in entry points for '{entry_point_name}'" ) component_impl = entry_point.load() @@ -116,9 +114,7 @@ def _import_exporters( if issubclass(exporter_impl, SpanExporter): trace_exporters[exporter_name] = exporter_impl else: - raise RuntimeError( - "{0} is not a trace exporter".format(exporter_name) - ) + raise RuntimeError(f"{exporter_name} is not a trace exporter") return trace_exporters @@ -133,7 +129,7 @@ def _import_id_generator(id_generator_name: str) -> IdGenerator: if issubclass(id_generator_impl, IdGenerator): return id_generator_impl - raise RuntimeError("{0} is not an IdGenerator".format(id_generator_name)) + raise RuntimeError(f"{id_generator_name} is not an IdGenerator") def _initialize_components(): diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py index 135546b362f..ab6df18fdd1 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py @@ -219,7 +219,7 @@ def _submit_and_await( self, func: Callable[[SpanProcessor], Callable[..., None]], *args: Any, - **kwargs: Any + **kwargs: Any, ): futures = [] for sp in self._span_processors: @@ -442,12 +442,10 @@ def to_json(self, indent=4): if self.parent is not None: if isinstance(self.parent, Span): ctx = self.parent.context - parent_id = "0x{}".format( - trace_api.format_span_id(ctx.span_id) - ) + parent_id = f"0x{trace_api.format_span_id(ctx.span_id)}" elif isinstance(self.parent, SpanContext): - parent_id = "0x{}".format( - trace_api.format_span_id(self.parent.span_id) + parent_id = ( + f"0x{trace_api.format_span_id(self.parent.span_id)}" ) start_time = None @@ -484,12 +482,8 @@ def to_json(self, indent=4): @staticmethod def _format_context(context): x_ctx = OrderedDict() - x_ctx["trace_id"] = "0x{}".format( - trace_api.format_trace_id(context.trace_id) - ) - x_ctx["span_id"] = "0x{}".format( - trace_api.format_span_id(context.span_id) - ) + x_ctx["trace_id"] = f"0x{trace_api.format_trace_id(context.trace_id)}" + x_ctx["span_id"] = f"0x{trace_api.format_span_id(context.span_id)}" x_ctx["trace_state"] = repr(context.trace_state) return x_ctx @@ -612,16 +606,7 @@ def __init__( ) def __repr__(self): - return "{}(max_span_attributes={}, max_events_attributes={}, max_link_attributes={}, max_attributes={}, max_events={}, max_links={}, max_attribute_length={})".format( - type(self).__name__, - self.max_span_attribute_length, - self.max_event_attributes, - self.max_link_attributes, - self.max_attributes, - self.max_events, - self.max_links, - self.max_attribute_length, - ) + return f"{type(self).__name__}(max_span_attributes={self.max_span_attribute_length}, max_events_attributes={self.max_event_attributes}, max_link_attributes={self.max_link_attributes}, max_attributes={self.max_attributes}, max_events={self.max_events}, max_links={self.max_links}, max_attribute_length={self.max_attribute_length})" @classmethod def _from_env_if_absent( @@ -759,9 +744,7 @@ def __init__( self._links = BoundedList.from_seq(self._limits.max_links, links) def __repr__(self): - return '{}(name="{}", context={})'.format( - type(self).__name__, self._name, self._context - ) + return f'{type(self).__name__}(name="{self._name}", context={self._context})' def _new_events(self): return BoundedList(self._limits.max_events) @@ -889,9 +872,7 @@ def __exit__( self.set_status( Status( status_code=StatusCode.ERROR, - description="{}: {}".format( - exc_type.__name__, exc_val - ), + description=f"{exc_type.__name__}: {exc_val}", ) ) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py index 878c5d816c4..4aac5f6f88d 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py @@ -145,9 +145,7 @@ class SamplingResult: """ def __repr__(self) -> str: - return "{}({}, attributes={})".format( - type(self).__name__, str(self.decision), str(self.attributes) - ) + return f"{type(self).__name__}({str(self.decision)}, attributes={str(self.attributes)})" def __init__( self, @@ -271,7 +269,7 @@ def should_sample( ) def get_description(self) -> str: - return "TraceIdRatioBased{{{}}}".format(self._rate) + return f"TraceIdRatioBased{{{self._rate}}}" class ParentBased(Sampler): @@ -342,13 +340,7 @@ def should_sample( ) def get_description(self): - return "ParentBased{{root:{},remoteParentSampled:{},remoteParentNotSampled:{}," "localParentSampled:{},localParentNotSampled:{}}}".format( - self._root.get_description(), - self._remote_parent_sampled.get_description(), - self._remote_parent_not_sampled.get_description(), - self._local_parent_sampled.get_description(), - self._local_parent_not_sampled.get_description(), - ) + return f"ParentBased{{root:{self._root.get_description()},remoteParentSampled:{self._remote_parent_sampled.get_description()},remoteParentNotSampled:{self._remote_parent_not_sampled.get_description()},localParentSampled:{self._local_parent_sampled.get_description()},localParentNotSampled:{self._local_parent_not_sampled.get_description()}}}" DEFAULT_OFF = ParentBased(ALWAYS_OFF) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.py index a94fe647b76..e1857d8e62d 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.py @@ -54,9 +54,7 @@ def __init__(self, maxlen: Optional[int]): self._lock = threading.Lock() def __repr__(self): - return "{}({}, maxlen={})".format( - type(self).__name__, list(self._dq), self._dq.maxlen - ) + return f"{type(self).__name__}({list(self._dq)}, maxlen={self._dq.maxlen})" def __getitem__(self, index): return self._dq[index] @@ -113,8 +111,8 @@ def __init__(self, maxlen: Optional[int]): self._lock = threading.Lock() # type: threading.Lock def __repr__(self): - return "{}({}, maxlen={})".format( - type(self).__name__, dict(self._dict), self.maxlen + return ( + f"{type(self).__name__}({dict(self._dict)}, maxlen={self.maxlen})" ) def __getitem__(self, key): diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py b/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py index c55f26ec623..2c3dba4923b 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py @@ -27,9 +27,7 @@ def __init__(self, name: str, version: str): self._version = version def __repr__(self): - return "{}({}, {})".format( - type(self).__name__, self._name, self._version - ) + return f"{type(self).__name__}({self._name}, {self._version})" def __hash__(self): return hash((self._name, self._version)) diff --git a/opentelemetry-sdk/tests/trace/export/test_export.py b/opentelemetry-sdk/tests/trace/export/test_export.py index 23f9308e084..c698f4d6e61 100644 --- a/opentelemetry-sdk/tests/trace/export/test_export.py +++ b/opentelemetry-sdk/tests/trace/export/test_export.py @@ -259,7 +259,7 @@ def test_flush_from_multiple_threads(self): def create_spans_and_flush(tno: int): for span_idx in range(num_spans): _create_start_and_end_span( - "Span {}-{}".format(tno, span_idx), span_processor + f"Span {tno}-{span_idx}", span_processor ) self.assertTrue(span_processor.force_flush()) diff --git a/opentelemetry-sdk/tests/trace/test_trace.py b/opentelemetry-sdk/tests/trace/test_trace.py index f4b75d106ba..09fcec6a9b3 100644 --- a/opentelemetry-sdk/tests/trace/test_trace.py +++ b/opentelemetry-sdk/tests/trace/test_trace.py @@ -1515,8 +1515,7 @@ def _test_span_limits( ] some_attrs = { - "init_attribute_{}".format(idx): self.long_val - for idx in range(100) + f"init_attribute_{idx}": self.long_val for idx in range(100) } with tracer.start_as_current_span( "root", links=some_links, attributes=some_attrs @@ -1524,17 +1523,15 @@ def _test_span_limits( self.assertEqual(len(root.links), max_links) self.assertEqual(len(root.attributes), max_attrs) for idx in range(100): + root.set_attribute(f"my_str_attribute_{idx}", self.long_val) root.set_attribute( - "my_str_attribute_{}".format(idx), self.long_val + f"my_byte_attribute_{idx}", self.long_val.encode() ) root.set_attribute( - "my_byte_attribute_{}".format(idx), self.long_val.encode() - ) - root.set_attribute( - "my_int_attribute_{}".format(idx), self.long_val.encode() + f"my_int_attribute_{idx}", self.long_val.encode() ) root.add_event( - "my_event_{}".format(idx), attributes={"k": self.long_val} + f"my_event_{idx}", attributes={"k": self.long_val} ) self.assertEqual(len(root.attributes), max_attrs) @@ -1576,7 +1573,7 @@ def _test_span_no_limits(self, tracer): with tracer.start_as_current_span("root") as root: for idx in range(num_events): root.add_event( - "my_event_{}".format(idx), attributes={"k": self.long_val} + f"my_event_{idx}", attributes={"k": self.long_val} ) self.assertEqual(len(root.events), num_events) @@ -1586,9 +1583,7 @@ def _test_span_no_limits(self, tracer): ) + randint(1, 100) with tracer.start_as_current_span("root") as root: for idx in range(num_attributes): - root.set_attribute( - "my_attribute_{}".format(idx), self.long_val - ) + root.set_attribute(f"my_attribute_{idx}", self.long_val) self.assertEqual(len(root.attributes), num_attributes) for attr_val in root.attributes.values(): diff --git a/propagator/opentelemetry-propagator-b3/tests/test_b3_format.py b/propagator/opentelemetry-propagator-b3/tests/test_b3_format.py index b1d0a9a6bd3..4068e2060a6 100644 --- a/propagator/opentelemetry-propagator-b3/tests/test_b3_format.py +++ b/propagator/opentelemetry-propagator-b3/tests/test_b3_format.py @@ -125,9 +125,7 @@ def test_extract_single_header(self): propagator = self.get_propagator() child, parent, _ = self.get_child_parent_new_carrier( { - propagator.SINGLE_HEADER_KEY: "{}-{}".format( - self.serialized_trace_id, self.serialized_span_id - ) + propagator.SINGLE_HEADER_KEY: f"{self.serialized_trace_id}-{self.serialized_span_id}" } ) @@ -144,11 +142,7 @@ def test_extract_single_header(self): child, parent, _ = self.get_child_parent_new_carrier( { - propagator.SINGLE_HEADER_KEY: "{}-{}-1-{}".format( - self.serialized_trace_id, - self.serialized_span_id, - self.serialized_parent_id, - ) + propagator.SINGLE_HEADER_KEY: f"{self.serialized_trace_id}-{self.serialized_span_id}-1-{self.serialized_parent_id}" } ) @@ -173,9 +167,7 @@ def test_extract_header_precedence(self): _, _, new_carrier = self.get_child_parent_new_carrier( { - propagator.SINGLE_HEADER_KEY: "{}-{}".format( - single_header_trace_id, self.serialized_span_id - ), + propagator.SINGLE_HEADER_KEY: f"{single_header_trace_id}-{self.serialized_span_id}", propagator.TRACE_ID_KEY: self.serialized_trace_id, propagator.SPAN_ID_KEY: self.serialized_span_id, propagator.SAMPLED_KEY: "1", diff --git a/propagator/opentelemetry-propagator-jaeger/src/opentelemetry/propagators/jaeger/__init__.py b/propagator/opentelemetry-propagator-jaeger/src/opentelemetry/propagators/jaeger/__init__.py index fe16c260816..9589f97619a 100644 --- a/propagator/opentelemetry-propagator-jaeger/src/opentelemetry/propagators/jaeger/__init__.py +++ b/propagator/opentelemetry-propagator-jaeger/src/opentelemetry/propagators/jaeger/__init__.py @@ -127,12 +127,7 @@ def _extract_baggage(self, getter, carrier, context): def _format_uber_trace_id(trace_id, span_id, parent_span_id, flags): - return "{trace_id}:{span_id}:{parent_id}:{:02x}".format( - flags, - trace_id=format_trace_id(trace_id), - span_id=format_span_id(span_id), - parent_id=format_span_id(parent_span_id), - ) + return f"{format_trace_id(trace_id)}:{format_span_id(span_id)}:{format_span_id(parent_span_id)}:{flags:02x}" def _extract_first_element( diff --git a/scripts/eachdist.py b/scripts/eachdist.py index 51d3872d72b..58064a7400d 100755 --- a/scripts/eachdist.py +++ b/scripts/eachdist.py @@ -31,14 +31,12 @@ def unique(elems): def extraargs_help(calledcmd): return cleandoc( - """ - Additional arguments to pass on to {}. + f""" + Additional arguments to pass on to {calledcmd}. This is collected from any trailing arguments passed to `%(prog)s`. Use an initial `--` to separate them from regular arguments. - """.format( - calledcmd - ) + """ ) @@ -405,7 +403,7 @@ def execute_args(args): rootpath = find_projectroot() targets = find_targets(args.mode, rootpath) if not targets: - sys.exit("Error: No targets selected (root: {})".format(rootpath)) + sys.exit(f"Error: No targets selected (root: {rootpath})") def fmt_for_path(fmt, path): return fmt.format( @@ -421,7 +419,7 @@ def _runcmd(cmd): ) if result is not None and result.returncode not in args.allowexitcode: print( - "'{}' failed with code {}".format(cmd, result.returncode), + f"'{cmd}' failed with code {result.returncode}", file=sys.stderr, ) sys.exit(result.returncode) @@ -476,7 +474,7 @@ def install_args(args): if args.with_test_deps: extras.append("test") if extras: - allfmt += "[{}]".format(",".join(extras)) + allfmt += f"[{','.join(extras)}]" # note the trailing single quote, to close the quote opened above. allfmt += "'" @@ -554,9 +552,9 @@ def update_changelog(path, version, new_entry): try: with open(path, encoding="utf-8") as changelog: text = changelog.read() - if "## [{}]".format(version) in text: + if f"## [{version}]" in text: raise AttributeError( - "{} already contans version {}".format(path, version) + f"{path} already contans version {version}" ) with open(path, encoding="utf-8") as changelog: for line in changelog: @@ -568,11 +566,11 @@ def update_changelog(path, version, new_entry): unreleased_changes = True except FileNotFoundError: - print("file missing: {}".format(path)) + print(f"file missing: {path}") return if unreleased_changes: - print("updating: {}".format(path)) + print(f"updating: {path}") text = re.sub(r"## \[Unreleased\].*", new_entry, text) with open(path, "w", encoding="utf-8") as changelog: changelog.write(text) @@ -622,7 +620,7 @@ def update_version_files(targets, version, packages): targets, "version.py", "__version__ .*", - '__version__ = "{}"'.format(version), + f'__version__ = "{version}"', ) @@ -632,7 +630,7 @@ def update_dependencies(targets, version, packages): update_files( targets, "setup.cfg", - r"({}.*)==(.*)".format(basename(pkg)), + fr"({basename(pkg)}.*)==(.*)", r"\1== " + version, ) @@ -642,14 +640,14 @@ def update_files(targets, filename, search, replace): for target in targets: curr_file = find(filename, target) if curr_file is None: - print("file missing: {}/{}".format(target, filename)) + print(f"file missing: {target}/{filename}") continue with open(curr_file, encoding="utf-8") as _file: text = _file.read() if replace in text: - print("{} already contains {}".format(curr_file, replace)) + print(f"{curr_file} already contains {replace}") continue with open(curr_file, "w", encoding="utf-8") as _file: @@ -673,7 +671,7 @@ def release_args(args): version = mcfg["version"] updated_versions.append(version) packages = mcfg["packages"].split() - print("update {} packages to {}".format(group, version)) + print(f"update {group} packages to {version}") update_dependencies(targets, version, packages) update_version_files(targets, version, packages) diff --git a/scripts/public_symbols_checker.py b/scripts/public_symbols_checker.py index bdc530e95d3..3be1c3ee8b9 100644 --- a/scripts/public_symbols_checker.py +++ b/scripts/public_symbols_checker.py @@ -78,9 +78,9 @@ def m_diff_lines_getter(diff_lines): print("The code in this branch adds the following public symbols:") print() for file_path, symbols in file_path_symbols.items(): - print("- {}".format(file_path)) + print(f"- {file_path}") for symbol in symbols: - print("\t{}".format(symbol)) + print(f"\t{symbol}") print() print( diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_asyncio.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_asyncio.py index 64cfea933c4..e94a643c290 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_asyncio.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_asyncio.py @@ -29,7 +29,7 @@ async def after_handler(): await before_handler() await after_handler() - return "%s::response" % message + return f"{message}::response" def send(self, message): return self.send_task(message) diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_threads.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_threads.py index 36c0a8b8414..99693461e35 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_threads.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_threads.py @@ -29,7 +29,7 @@ def after_handler(): self.executor.submit(before_handler).result() self.executor.submit(after_handler).result() - return "%s::response" % message + return f"{message}::response" def send(self, message): return self.executor.submit(self.send_task, message) diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_asyncio.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_asyncio.py index 085c0ea8134..35153cb6275 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_asyncio.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_asyncio.py @@ -16,7 +16,7 @@ def __init__(self, tracer, loop): self.loop = loop async def task(self, message, listener): - res = "%s::response" % message + res = f"{message}::response" listener.on_response(res) return res diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_threads.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_threads.py index 8f82e1fb158..dc40373912c 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_threads.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_threads.py @@ -17,7 +17,7 @@ def __init__(self, tracer): def _task(self, message, listener): # pylint: disable=no-self-use - res = "%s::response" % message + res = f"{message}::response" listener.on_response(res) return res diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_nested_callbacks/test_asyncio.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_nested_callbacks/test_asyncio.py index 12eb4362770..1e6d2a36044 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_nested_callbacks/test_asyncio.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_nested_callbacks/test_asyncio.py @@ -34,7 +34,7 @@ async def task(): for idx in range(1, 4): self.assertEqual( - spans[0].attributes.get("key%s" % idx, None), str(idx) + spans[0].attributes.get(f"key{idx}", None), str(idx) ) def submit(self): diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_nested_callbacks/test_threads.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_nested_callbacks/test_threads.py index a1d35c35d88..5bb63ab9e78 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_nested_callbacks/test_threads.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_nested_callbacks/test_threads.py @@ -32,7 +32,7 @@ def test_main(self): for idx in range(1, 4): self.assertEqual( - spans[0].attributes.get("key%s" % idx, None), str(idx) + spans[0].attributes.get(f"key{idx}", None), str(idx) ) def submit(self): diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_subtask_span_propagation/test_asyncio.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_subtask_span_propagation/test_asyncio.py index 6e544560704..2bf8b3cbd8b 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_subtask_span_propagation/test_asyncio.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_subtask_span_propagation/test_asyncio.py @@ -29,4 +29,4 @@ async def parent_task(self, message): # noqa async def child_task(self, message): # No need to pass/activate the parent Span, as it stays in the context. with self.tracer.start_active_span("child"): - return "%s::response" % message + return f"{message}::response" diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_subtask_span_propagation/test_threads.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_subtask_span_propagation/test_threads.py index 1ba5f697cad..09eddf3448b 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_subtask_span_propagation/test_threads.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_subtask_span_propagation/test_threads.py @@ -30,4 +30,4 @@ def parent_task(self, message): def child_task(self, message, span): with self.tracer.scope_manager.activate(span, False): with self.tracer.start_active_span("child"): - return "%s::response" % message + return f"{message}::response" diff --git a/tests/util/src/opentelemetry/test/spantestutil.py b/tests/util/src/opentelemetry/test/spantestutil.py index 408f4c4947f..ea83b90b8d4 100644 --- a/tests/util/src/opentelemetry/test/spantestutil.py +++ b/tests/util/src/opentelemetry/test/spantestutil.py @@ -55,13 +55,13 @@ def setUp(self): def get_span_with_dropped_attributes_events_links(): attributes = {} for index in range(130): - attributes["key{}".format(index)] = ["value{}".format(index)] + attributes[f"key{index}"] = [f"value{index}"] links = [] for index in range(129): links.append( trace_api.Link( trace_sdk._Span( - name="span{}".format(index), + name=f"span{index}", context=trace_api.INVALID_SPAN_CONTEXT, attributes=attributes, ).get_span_context(), @@ -77,5 +77,5 @@ def get_span_with_dropped_attributes_events_links(): "span", links=links, attributes=attributes ) as span: for index in range(131): - span.add_event("event{}".format(index), attributes=attributes) + span.add_event(f"event{index}", attributes=attributes) return span diff --git a/tests/util/src/opentelemetry/test/test_base.py b/tests/util/src/opentelemetry/test/test_base.py index 4945d1cb32d..9762a08010e 100644 --- a/tests/util/src/opentelemetry/test/test_base.py +++ b/tests/util/src/opentelemetry/test/test_base.py @@ -113,12 +113,12 @@ def by_name(self, name): for span in self: if span.name == name: return span - self.test.fail("Did not find span with name {}".format(name)) + self.test.fail(f"Did not find span with name {name}") return None def by_attr(self, key, value): for span in self: if span.attributes.get(key) == value: return span - self.test.fail("Did not find span with attrs {}={}".format(key, value)) + self.test.fail(f"Did not find span with attrs {key}={value}") return None From d9c22a87b6bfc5ec332588c764f82c32f068b2c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Neum=C3=BCller?= Date: Mon, 20 Sep 2021 18:36:45 +0200 Subject: [PATCH 2/2] Add test base class with local HTTP server. (#2101) --- CHANGELOG.md | 2 + tests/util/src/opentelemetry/test/httptest.py | 68 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 tests/util/src/opentelemetry/test/httptest.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e6e35414c80..00b3640cf13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#2071](https://github.com/open-telemetry/opentelemetry-python/pull/2071)) - Do not skip sequence attribute on decode error ([#2097](https://github.com/open-telemetry/opentelemetry-python/pull/2097)) +- `opentelemetry-test`: Add `HttpTestBase` to allow tests with actual TCP sockets + ([#2101](https://github.com/open-telemetry/opentelemetry-python/pull/2101)) ## [1.5.0-0.24b0](https://github.com/open-telemetry/opentelemetry-python/releases/tag/v1.5.0-0.24b0) - 2021-08-26 diff --git a/tests/util/src/opentelemetry/test/httptest.py b/tests/util/src/opentelemetry/test/httptest.py new file mode 100644 index 00000000000..94964ea9f17 --- /dev/null +++ b/tests/util/src/opentelemetry/test/httptest.py @@ -0,0 +1,68 @@ +# Copyright The OpenTelemetry Authors +# +# 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 writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +import unittest +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, HTTPServer +from threading import Thread + + +class HttpTestBase(unittest.TestCase): + DEFAULT_RESPONSE = b"Hello!" + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" # Support keep-alive. + # timeout = 3 # No timeout -- if shutdown hangs, make sure to close your connection + + STATUS_RE = re.compile(r"/status/(\d+)") + + def do_GET(self): # pylint:disable=invalid-name + status_match = self.STATUS_RE.fullmatch(self.path) + status = 200 + if status_match: + status = int(status_match.group(1)) + if status == 200: + body = HttpTestBase.DEFAULT_RESPONSE + self.send_response(HTTPStatus.OK) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + else: + self.send_error(status) + + @classmethod + def create_server(cls): + server_address = ("127.0.0.1", 0) # Only bind to localhost. + return HTTPServer(server_address, cls.Handler) + + @classmethod + def run_server(cls): + httpd = cls.create_server() + worker = Thread( + target=httpd.serve_forever, daemon=True, name="Test server worker" + ) + worker.start() + return worker, httpd + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.server_thread, cls.server = cls.run_server() + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server_thread.join() + super().tearDownClass()