Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NH-34752 Add config file tests + small changes #139

Merged
merged 14 commits into from
Apr 27, 2023
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
40 changes: 19 additions & 21 deletions solarwinds_apm/apm_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,9 @@ def __init__(
"histogram_precision": -1,
"reporter_file_single": 0,
"enable_sanitize_sql": True,
"inst_enabled": defaultdict(lambda: True),
"log_trace_id": "never",
"proxy": "",
"transaction": defaultdict(lambda: True),
"inst": defaultdict(lambda: True),
"is_grpc_clean_hack_enabled": False,
"transaction_filters": [],
}
Expand Down Expand Up @@ -484,33 +482,37 @@ def get(self, key: str, default: Any = None):
)
return value if value is not None else default

def update_with_cnf_file(self) -> None:
"""Update the settings with the config file (json), if any."""

def _snake_to_camel_case(key):
key_parts = key.split("_")
camel_head = key_parts[0]
camel_body = "".join(part.title() for part in key_parts[1:])
return f"{camel_head}{camel_body}"

def get_cnf_dict(self) -> Any:
"""Load Python dict from confg file (json), if any"""
cnf_filepath = os.environ.get(
"SW_APM_CONFIG_FILE", "./solarwinds-apm-config.json"
)
if not cnf_filepath:
return
cnf_dict = None
try:
with open(cnf_filepath, encoding="utf-8") as cnf_file:
try:
cnf_dict = json.load(cnf_file)
file_content = cnf_file.read()
cnf_dict = json.loads(file_content)
except ValueError as ex:
logger.error(
"Invalid config file, must be valid json. Ignoring: %s",
ex,
)
return
except FileNotFoundError as ex:
logger.error("Invalid config file path. Ignoring: %s", ex)
return cnf_dict

def update_with_cnf_file(self) -> None:
"""Update the settings with the config file (json), if any."""

def _snake_to_camel_case(key):
key_parts = key.split("_")
camel_head = key_parts[0]
camel_body = "".join(part.title() for part in key_parts[1:])
return f"{camel_head}{camel_body}"

cnf_dict = self.get_cnf_dict()
if not cnf_dict:
return

try:
Expand Down Expand Up @@ -594,7 +596,7 @@ def update_with_env_var(self) -> None:
available_envvs = set(self.__config.keys())
# TODO after alpha: is_lambda
for key in available_envvs:
if key in {"inst_enabled", "transaction", "inst"}:
if key == "transaction":

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason for having transaction in self.__config.keys(). I think removing it from there will nullify this branch.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's there as part of one way to store transaction with a default and transaction.prepend_domain_name as a nested object if set by customer, but I'm not convinced this is a good reason!

Right now an accepted config file would be:

{
    "transaction": {
        "prependDomain": false
    },
    "transactionSettings": []
}

But it might make more sense to customer if it were:

{
    "prependDomain": false,
    "transactionSettings": []
}

I'll change this in a next PR.

# we do not allow complex config options to be set via environment variables
continue
env = "SW_APM_" + key.upper()
Expand Down Expand Up @@ -717,9 +719,5 @@ def _convert_to_bool(val):
except (ValueError, TypeError):
logger.warning(
"Ignore config option with invalid (non-convertible or out-of-range) type: %s",
".".join(
keys
if keys[0] not in ["inst", "transaction"]
else keys[1:]
),
".".join(keys if keys[0] != "transaction" else keys[1:]),
)
Empty file.
Empty file.
34 changes: 34 additions & 0 deletions tests/unit/test_apm_config/fixtures/cnf_dict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import pytest

@pytest.fixture
def fixture_cnf_dict():
return {
"agentEnabled": True,
"tracingMode": "enabled",
"triggerTrace": "enabled",
"collector": "foo-bar",
"reporter": "udp",
"debugLevel": 6,
"serviceKey": "not-good-to-put-here:wont-be-used",
"hostnameAlias": "foo-bar",
"trustedpath": "foo-bar",
"eventsFlushInterval": 2,
"maxRequestSizeBytes": 2,
"ec2MetadataTimeout": 1234,
"maxFlushWaitTime": 2,
"maxTransactions": 2,
"logname": "foo-bar",
"traceMetrics": 2,
"tokenBucketCapacity": 2,
"tokenBucketRate": 2,
"bufsize": 2,
"histogramPrecision": 2,
"reporterFileSingle": 2,
"enableSanitizeSql": True,
"logTraceId": "always",
"proxy": "http://foo-bar",
"transaction": {
"prependDomain": True
},
"isGrpcCleanHackEnabled": True,
}
14 changes: 14 additions & 0 deletions tests/unit/test_apm_config/fixtures/cnf_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pytest

@pytest.fixture
def fixture_cnf_file(mocker):
read_data = '{"foo": "bar"}'
mocked_cnf_file_data = mocker.mock_open(read_data=read_data)
builtin_open = "builtins.open"
mocker.patch(builtin_open, mocked_cnf_file_data)

@pytest.fixture
def fixture_cnf_file_invalid_json(mocker):
mocked_cnf_file_data = mocker.mock_open(read_data="invalid-foo")
builtin_open = "builtins.open"
mocker.patch(builtin_open, mocked_cnf_file_data)
15 changes: 15 additions & 0 deletions tests/unit/test_apm_config/fixtures/env_vars.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import os
import pytest

from solarwinds_apm.apm_constants import (
INTL_SWO_DEFAULT_PROPAGATORS,
INTL_SWO_DEFAULT_TRACES_EXPORTER,
)

@pytest.fixture(name="mock_env_vars")
def fixture_mock_env_vars(mocker):
mocker.patch.dict(os.environ, {
"OTEL_PROPAGATORS": ",".join(INTL_SWO_DEFAULT_PROPAGATORS),
"OTEL_TRACES_EXPORTER": INTL_SWO_DEFAULT_TRACES_EXPORTER,
"SW_APM_SERVICE_KEY": "valid:key",
})
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
#
# 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 json
import os
import pytest

Expand All @@ -14,18 +13,10 @@
from solarwinds_apm.apm_constants import (
INTL_SWO_AO_COLLECTOR,
INTL_SWO_AO_STG_COLLECTOR,
INTL_SWO_DEFAULT_PROPAGATORS,
INTL_SWO_DEFAULT_TRACES_EXPORTER,
)

@pytest.fixture(name="mock_env_vars")
def fixture_mock_env_vars(mocker):
mocker.patch.dict(os.environ, {
"OTEL_PROPAGATORS": ",".join(INTL_SWO_DEFAULT_PROPAGATORS),
"OTEL_TRACES_EXPORTER": INTL_SWO_DEFAULT_TRACES_EXPORTER,
"SW_APM_SERVICE_KEY": "valid:key",
})

# pylint: disable=unused-import
from .fixtures.env_vars import fixture_mock_env_vars

Check notice

Code scanning / CodeQL

Unused import

Import of 'fixture_mock_env_vars' is not used.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dismissing because pytest is using them.


class TestSolarWindsApmConfig:
"""
Expand Down
Loading