Skip to content

Commit 00755b5

Browse files
fix: ADDON-66599 deprecate splunk-hec-token default value and break test execution on exception (#804)
- deprecate default value of splunk-hec-token - give a warning when it's used - add console handler to logger - warnings and errors beside being logged to pytest_splunk_addon.log are also logged to console - other minor refactors from PR-803 References: https://splunk.atlassian.net/browse/ADDON-66599 https://github.com/splunk/pytest-splunk-addon/pull/803/files --------- Co-authored-by: Artem Rys <[email protected]>
1 parent 4a2d5c3 commit 00755b5

File tree

6 files changed

+130
-9
lines changed

6 files changed

+130
-9
lines changed

.github/workflows/build-test-release.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ jobs:
186186
"splunk_app_cim_broken",
187187
"splunk_fiction_indextime",
188188
"splunk_fiction_indextime_broken",
189+
"splunk_fiction_indextime_wrong_hec_token",
189190
"splunk_setup_fixture",
190191
"splunk_app_req",
191192
"splunk_app_req_broken",

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@ test_report.md
3535
*.pickle
3636
*_events.lock
3737
*_events
38+
.venv

pytest_splunk_addon/plugin.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525

2626
test_generator = None
2727

28+
EXC_MAP = [Exception]
29+
2830

2931
def pytest_configure(config):
3032
"""
@@ -93,6 +95,10 @@ def pytest_configure(config):
9395
"markers",
9496
"splunk_requirements_unit: Test checking if all fields for datamodel are defined in cim_fields and missing_recommended_fields",
9597
)
98+
if config.getoption("splunk_hec_token") == "9b741d03-43e9-4164-908b-e09102327d22":
99+
LOGGER.warning(
100+
"Using the default value for --splunk-hec-token which is going to be deprecated. Please provide --splunk-hec-token argument when executing tests."
101+
)
96102

97103
cim_report = config.getoption("cim_report")
98104
if cim_report and not hasattr(config, "slaveinput"):
@@ -115,6 +121,7 @@ def pytest_sessionstart(session):
115121
SampleXdistGenerator.tokenized_event_source = session.config.getoption(
116122
"tokenized_event_source"
117123
).lower()
124+
session.__exc_limits = EXC_MAP
118125
if (
119126
SampleXdistGenerator.tokenized_event_source == "store_new"
120127
and session.config.getoption("ingest_events").lower()
@@ -187,16 +194,31 @@ def init_pytest_splunk_addon_logger():
187194
"""
188195
fh = logging.FileHandler(LOG_FILE)
189196
fh.setLevel(logging.INFO)
197+
ch = logging.StreamHandler()
198+
ch.setLevel(logging.WARNING)
190199
formatter = logging.Formatter(
191200
"%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(message)s"
192201
)
193202
fh.setFormatter(formatter)
203+
ch.setFormatter(formatter)
194204
logger = logging.getLogger("pytest-splunk-addon")
195205
logger.addHandler(fh)
206+
logger.addHandler(ch)
196207
logging.root.propagate = False
197208
logger.setLevel(logging.INFO)
198209
return logger
199210

200211

201212
init_pytest_splunk_addon_logger()
202213
LOGGER = logging.getLogger("pytest-splunk-addon")
214+
215+
216+
def pytest_exception_interact(node, call, report):
217+
"""
218+
Hook called when an exception is raised during a test.
219+
If the number of occurrences for a specific exception exceeds the limit in session.__exc_limits, pytest exits
220+
https://docs.pytest.org/en/stable/reference/reference.html#pytest.hookspec.pytest_exception_interact
221+
"""
222+
if call.excinfo.type in node.session.__exc_limits:
223+
# pytest exits only for exceptions defined in EXC_MAP
224+
pytest.exit(f"Exiting pytest due to: {call.excinfo.type}")

pytest_splunk_addon/splunk.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def pytest_addoption(parser):
110110
action="store",
111111
dest="splunk_hec_token",
112112
default="9b741d03-43e9-4164-908b-e09102327d22",
113-
help='Splunk HTTP event collector token. default is "9b741d03-43e9-4164-908b-e09102327d22" If an external forwarder is used provide HEC token of forwarder.',
113+
help="Splunk HTTP event collector token. If an external forwarder is used provide HEC token of forwarder. Please specify it as default value is going to be deprecated.",
114114
)
115115
group.addoption(
116116
"--splunk-port",
@@ -552,6 +552,7 @@ def splunk_docker(
552552
# get the temp directory shared by all workers
553553
root_tmp_dir = tmp_path_factory.getbasetemp().parent
554554
fn = root_tmp_dir / "pytest_docker"
555+
# if you encounter docker-compose not found modify shell path in your IDE to use /bin/bash
555556
with FileLock(str(fn) + ".lock"):
556557
docker_services.start("splunk")
557558

@@ -576,11 +577,12 @@ def splunk_docker(
576577
docker_services.port_for("splunk", 9997),
577578
)
578579

579-
docker_services.wait_until_responsive(
580-
timeout=180.0,
581-
pause=0.5,
582-
check=lambda: is_responsive_splunk(splunk_info),
583-
)
580+
for _ in range(RESPONSIVE_SPLUNK_TIMEOUT):
581+
if is_responsive_splunk(splunk_info) and is_responsive_hec(
582+
request, splunk_info
583+
):
584+
break
585+
sleep(1)
584586

585587
return splunk_info
586588

@@ -610,9 +612,9 @@ def splunk_external(request):
610612
)
611613

612614
for _ in range(RESPONSIVE_SPLUNK_TIMEOUT):
613-
if is_responsive_splunk(splunk_info):
614-
break
615-
if is_responsive_hec(request, splunk_info):
615+
if is_responsive_splunk(splunk_info) and is_responsive_hec(
616+
request, splunk_info
617+
):
616618
break
617619
sleep(1)
618620

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import os
2+
import pytest
3+
import requests
4+
5+
pytest_plugins = "pytester"
6+
7+
8+
def pytest_configure(config):
9+
config.addinivalue_line("markers", "external: Test search time only")
10+
config.addinivalue_line("markers", "docker: Test search time only")
11+
config.addinivalue_line("markers", "doc: Test Sphinx docs")
12+
13+
14+
@pytest.fixture(scope="session")
15+
def docker_compose_files(request):
16+
"""
17+
Get an absolute path to the `docker-compose.yml` file. Override this
18+
fixture in your tests if you need a custom location.
19+
20+
Returns:
21+
string: the path of the `docker-compose.yml` file
22+
23+
"""
24+
docker_compose_path = os.path.join(
25+
str(request.config.invocation_dir), "docker-compose.yml"
26+
)
27+
# LOGGER.info("docker-compose path: %s", docker_compose_path)
28+
29+
return [docker_compose_path]
30+
31+
32+
@pytest.fixture(scope="session")
33+
def docker_services_project_name(pytestconfig):
34+
rootdir = str(pytestconfig.rootdir)
35+
docker_compose_v2_rootdir = rootdir.lower().replace("/", "")
36+
return f"pytest{docker_compose_v2_rootdir}"
37+
38+
39+
@pytest.fixture(scope="session")
40+
def splunk_hec_uri(splunk, request):
41+
splunk_session = requests.Session()
42+
splunk_session.headers = {"Authorization": f"Splunk test-token"}
43+
uri = f'{request.config.getoption("splunk_hec_scheme")}://{splunk["forwarder_host"]}:{splunk["port_hec"]}/services/collector'
44+
return splunk_session, uri

tests/e2e/test_splunk_addon.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,57 @@ def empty_method():
166166
assert result.ret == 0
167167

168168

169+
@pytest.mark.docker
170+
@pytest.mark.splunk_fiction_indextime_wrong_hec_token
171+
def test_splunk_fiction_indextime_wrong_hec_token(testdir):
172+
"""Make sure that pytest accepts our fixture."""
173+
174+
testdir.makepyfile(
175+
"""
176+
from pytest_splunk_addon.standard_lib.addon_basic import Basic
177+
class Test_App(Basic):
178+
def empty_method():
179+
pass
180+
181+
"""
182+
)
183+
184+
shutil.copytree(
185+
os.path.join(testdir.request.fspath.dirname, "addons/TA_fiction_indextime"),
186+
os.path.join(testdir.tmpdir, "package"),
187+
)
188+
189+
shutil.copytree(
190+
os.path.join(testdir.request.fspath.dirname, "test_data_models"),
191+
os.path.join(testdir.tmpdir, "tests/data_models"),
192+
)
193+
194+
setup_test_dir(testdir)
195+
SampleGenerator.clean_samples()
196+
Rule.clean_rules()
197+
with open(
198+
os.path.join(testdir.request.fspath.dirname, "incorrect_hec_token_conftest.py")
199+
) as conf_test_file:
200+
testdir.makeconftest(conf_test_file.read())
201+
202+
# run pytest with the following cmd args
203+
result = testdir.runpytest(
204+
"--splunk-type=docker",
205+
"-v",
206+
"--search-interval=0",
207+
"--search-retry=0",
208+
"--splunk-data-generator=tests/addons/TA_fiction_indextime/default",
209+
"--search-index=*,_internal",
210+
)
211+
212+
result.assert_outcomes(errors=1, passed=0, failed=0, xfailed=0)
213+
result.stdout.fnmatch_lines(
214+
"!!!!!! _pytest.outcomes.Exit: Exiting pytest due to: <class 'Exception'> !!!!!!!"
215+
)
216+
217+
assert result.ret != 0
218+
219+
169220
@pytest.mark.docker
170221
@pytest.mark.splunk_app_broken
171222
def test_splunk_app_broken(testdir):

0 commit comments

Comments
 (0)