Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,3 @@ exclude =
.tox
__pycache__
build
scripts
tests
10 changes: 4 additions & 6 deletions lambda/tests/test_instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,8 @@
TraceContextTextMapPropagator,
)


AWS_LAMBDA_EXEC_WRAPPER = "AWS_LAMBDA_EXEC_WRAPPER"
INIT_OTEL_SCRIPTS_DIR = os.path.join(
*(os.path.dirname(__file__), "..")
)
INIT_OTEL_SCRIPTS_DIR = os.path.join(*(os.path.dirname(__file__), ".."))
TOX_PYTHON_DIRECTORY = os.path.dirname(os.path.dirname(which("python3")))


Expand Down Expand Up @@ -89,6 +86,7 @@ def __init__(self, function_name, aws_request_id, invoked_function_arn):
MOCK_W3C_TRACE_STATE_KEY = "vendor_specific_key"
MOCK_W3C_TRACE_STATE_VALUE = "test_value"


def replace_in_file(filename, old_text, new_text):
with fileinput.FileInput(filename, inplace=True) as file_object:
for line in file_object:
Expand Down Expand Up @@ -122,7 +120,7 @@ def mock_aws_lambda_exec_wrapper():
)

# NOTE: Like opentelemetry-lambda, `solarwinds-apm/wrapper` cannot affect
# this python environment. We parse the stdout produced by our test python
# this python environment. We parse the stdout produced by our test python
# program to update the environment in this parent python process.

for env_var_line in completed_subprocess.stdout.split("\n"):
Expand Down Expand Up @@ -289,4 +287,4 @@ def test_parent_context_from_lambda_event(self):
)
self.assertTrue(parent_context.is_remote)

test_env_patch.stop()
test_env_patch.stop()
7 changes: 2 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,7 @@ exclude = '''
(
/( # generated files
.tox|
build|
scripts|
tests
build
)/
)
'''
Expand All @@ -101,8 +99,6 @@ line-length = 79
exclude = [
".tox",
"build",
"scripts",
"tests",
"__pycache__",
]

Expand All @@ -125,6 +121,7 @@ ignore = [
"E203",
"B008", # for Resource.create() test compatibility
"UP006", # Use `set` instead of `typing.Set` type annotation, for compatibility with upstream SDK state
"UP038", # deprecated by Astral for performance
]

[tool.ruff.lint.isort]
Expand Down
6 changes: 4 additions & 2 deletions scripts/lint_and_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@


def parse_args(args=None):
parser = argparse.ArgumentParser(description="Lint and format everything, autofixing if possible.")
parser = argparse.ArgumentParser(
description="Lint and format everything, autofixing if possible."
)
parser.add_argument("--check-only", action="store_true")
parser.add_argument("--allowexitcodes", action="append", default=[0])
parser.set_defaults(parser=parser)
Expand All @@ -25,7 +27,7 @@ def run_subprocess(args, allowexitcodes):
result = subprocess.run(args)
if result is not None and result.returncode not in allowexitcodes:
print(
"'{}' failed with code {}".format(args[0], result.returncode),
f"'{args[0]}' failed with code {result.returncode}",
file=sys.stderr,
)
sys.exit(result.returncode)
Expand Down
6 changes: 4 additions & 2 deletions tests/docker/install/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
# 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 requests

from flask import Flask
from opentelemetry import trace

app = Flask(__name__)
tracer = trace.get_tracer(__name__)


@app.route("/test/")
def test_trace():
"""Makes request traced by autoinstrumentation
Expand All @@ -21,6 +21,8 @@ def test_trace():
current_span.set_attribute("test.custom_attribute", "outer-foo-bar")
with tracer.start_as_current_span("test_manual_inner"):
current_span = trace.get_current_span()
current_span.set_attribute("test.custom_attribute", "inner-foo-bar")
current_span.set_attribute(
"test.custom_attribute", "inner-foo-bar"
)
requests.get("http://www.solarwinds.com/")
return "Done"
24 changes: 15 additions & 9 deletions tests/docker/install/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,44 @@
import os
import sys
import time
import requests

import requests

level = logging.DEBUG
logger = logging.getLogger()
logger.setLevel(level)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(level)
formatter = logging.Formatter('%(levelname)s | %(message)s')
formatter = logging.Formatter("%(levelname)s | %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)


def request_server(attempts=10):
# Brute force until server responds
try:
resp = requests.get("http://{}:{}/test/".format(
os.getenv("FLASK_RUN_HOST"),
os.getenv("FLASK_RUN_PORT"),
))
resp = requests.get(
"http://{}:{}/test/".format(
os.getenv("FLASK_RUN_HOST"),
os.getenv("FLASK_RUN_PORT"),
)
)
logger.debug("Response headers from Flask server:")
logger.debug(resp.headers)
except Exception:
logger.debug("Server not responding. Will try up to {} more times".format(attempts))
logger.debug(
f"Server not responding. Will try up to {attempts} more times"
)
attempts -= 1
if attempts > 0:
time.sleep(1)
request_server(attempts)
else:
sys.exit("ERROR: No response from instrumented test server after several attempts.")
sys.exit(
"ERROR: No response from instrumented test server after several attempts."
)
except (KeyboardInterrupt, SystemExit) as exc:
logger.debug("Exiting with: {e}".format(e=exc))
logger.debug(f"Exiting with: {exc}")


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
#
# 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.
# 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.
32 changes: 18 additions & 14 deletions tests/integration/test_base_sw_headers_attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@

import flask
import requests
from werkzeug.test import Client
from werkzeug.wrappers import Response

from opentelemetry import trace as trace_api
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
Expand All @@ -30,6 +27,8 @@
)
from opentelemetry.test.test_base import TestBase
from opentelemetry.util._importlib_metadata import entry_points
from werkzeug.test import Client
from werkzeug.wrappers import Response

from solarwinds_apm.apm_config import SolarWindsApmConfig
from solarwinds_apm.configurator import SolarWindsConfigurator
Expand All @@ -38,7 +37,6 @@
from solarwinds_apm.propagator import SolarWindsPropagator



class TestBaseSwHeadersAndAttributes(TestBase):
"""
Base class for testing SolarWinds custom distro header propagation
Expand All @@ -49,7 +47,7 @@ class TestBaseSwHeadersAndAttributes(TestBase):
"BucketCapacity",
"BucketRate",
"SampleRate",
"SampleSource"
"SampleSource",
]

@staticmethod
Expand All @@ -74,7 +72,7 @@ def _test_trace():
# WSGI capitalizes incoming HTTP headers
incoming_headers.update({k.lower(): v.lower()})

resp = requests.get(f"http://postman-echo.com/headers")
resp = requests.get("http://postman-echo.com/headers")

# The return type must be a string, dict, tuple, Response instance, or WSGI callable
# (not CaseInsensitiveDict)
Expand All @@ -83,7 +81,7 @@ def _test_trace():
"tracestate": resp.request.headers["tracestate"],
"incoming-headers": incoming_headers,
}

def _setup_endpoints(self):
# pylint: disable=no-member
self.app.route("/test_trace/")(self._test_trace)
Expand All @@ -96,22 +94,24 @@ def setUp(self):
# Load OTel env vars entry points
argument_otel_environment_variable = {}
for entry_point in iter(
entry_points(
group="opentelemetry_environment_variables"
)
entry_points(group="opentelemetry_environment_variables")
):
environment_variable_module = entry_point.load()
for attribute in dir(environment_variable_module):
if attribute.startswith("OTEL_"):
argument = re.sub(r"OTEL_(PYTHON_)?", "", attribute).lower()
argument = re.sub(
r"OTEL_(PYTHON_)?", "", attribute
).lower()
argument_otel_environment_variable[argument] = attribute

# Set APM service key - not valid, but we mock anyway
os.environ["SW_APM_SERVICE_KEY"] = "foo:bar"

# Load Distro
SolarWindsDistro().configure()
assert os.environ["OTEL_PROPAGATORS"] == "solarwinds_propagator,baggage"
assert (
os.environ["OTEL_PROPAGATORS"] == "solarwinds_propagator,baggage"
)

# Load Configurator to Configure SW custom SDK components
# except use TestBase InMemorySpanExporter
Expand All @@ -127,9 +127,13 @@ def setUp(self):
reset_metrics_globals()
# Init parent-based with JsonSampler to guarantee sampling decision for tests
self.metric_reader = InMemoryMetricReader()
self.meter_provider = MeterProvider(metric_readers=[self.metric_reader])
self.meter_provider = MeterProvider(
metric_readers=[self.metric_reader]
)
set_meter_provider(self.meter_provider)
sampler_configuration = SolarWindsApmConfig.to_configuration(apm_config)
sampler_configuration = SolarWindsApmConfig.to_configuration(
apm_config
)
json_sampler = JsonSampler(
self.meter_provider,
sampler_configuration,
Expand Down
Loading
Loading