Skip to content

Commit 3550236

Browse files
committed
tests: add unit tests
1 parent b968353 commit 3550236

File tree

2 files changed

+81
-55
lines changed

2 files changed

+81
-55
lines changed

solnlib/splunkenv.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,22 @@
2020
import os.path as op
2121
import socket
2222
from typing import List, Optional, Tuple, Union
23-
from splunk.clilib.cli_common import getAppConf
24-
from splunk.clilib.bundle_paths import make_splunkhome_path as mksplhomepath
23+
24+
try:
25+
from splunk.clilib.cli_common import getAppConf
26+
except ImportError:
27+
28+
def getAppConf(*args, **kwargs):
29+
return None
30+
31+
32+
try:
33+
from splunk.clilib.bundle_paths import make_splunkhome_path as mksplhomepath
34+
except ImportError:
35+
36+
def mksplhomepath(*args, **kwargs):
37+
return None
38+
2539

2640
from .utils import is_true
2741

@@ -34,7 +48,7 @@
3448
"get_splunkd_uri",
3549
"get_conf_key_value",
3650
"get_conf_stanza",
37-
"get_conf_stanzas",
51+
"_get_conf_stanzas",
3852
]
3953

4054
ETC_LEAF = "etc"
@@ -224,7 +238,7 @@ def get_conf_key_value(
224238
KeyError: If `stanza` or `key` doesn't exist.
225239
"""
226240

227-
stanzas = get_conf_stanzas(conf_name, app_name)
241+
stanzas = _get_conf_stanzas(conf_name, app_name)
228242
return stanzas[stanza][key]
229243

230244

@@ -245,11 +259,11 @@ def get_conf_stanza(
245259
KeyError: If stanza doesn't exist.
246260
"""
247261

248-
stanzas = get_conf_stanzas(conf_name, app_name)
262+
stanzas = _get_conf_stanzas(conf_name, app_name)
249263
return stanzas[stanza]
250264

251265

252-
def get_conf_stanzas(conf_name: str, app_name: str, logger=None) -> dict:
266+
def _get_conf_stanzas(conf_name: str, app_name: str, logger=None) -> dict:
253267
"""Get stanzas of `conf_name`
254268
255269
Arguments:
@@ -260,21 +274,16 @@ def get_conf_stanzas(conf_name: str, app_name: str, logger=None) -> dict:
260274
Config stanzas.
261275
262276
Examples:
263-
>>> stanzas = get_conf_stanzas('server')
277+
>>> stanzas = _get_conf_stanzas('server')
264278
>>> return: {'serverName': 'testServer', 'sessionTimeout': '1h', ...}
265279
"""
266280

267-
path = make_splunkhome_path(["etc", "apps", app_name])
281+
if app_name == APP_SYSTEM:
282+
path = make_splunkhome_path(["etc", app_name])
283+
else:
284+
path = make_splunkhome_path(["etc", "apps", app_name])
268285
app_conf = getAppConf(
269286
confName=conf_name, app=app_name, use_btool=False, app_path=path
270287
)
271288

272-
if logger:
273-
logger.info(f"akakakakakkakakakaka 21 path: {path}")
274-
275-
if logger:
276-
logger.info(
277-
f"akakakakakkakakakaka 22 app_conf={type(app_conf)} app_conf: {app_conf}"
278-
)
279-
280289
return app_conf

tests/unit/common.py

Lines changed: 56 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,12 @@
1414
# limitations under the License.
1515
#
1616

17+
import os
1718
import os.path as op
1819
import socket
19-
import subprocess
20+
21+
from configparser import ConfigParser
22+
from io import StringIO
2023

2124
from splunklib import binding, client
2225
from splunklib.data import record
@@ -32,50 +35,64 @@
3235

3336

3437
def mock_splunkhome(monkeypatch):
35-
class MockPopen:
36-
def __init__(
37-
self,
38-
args,
39-
bufsize=0,
40-
executable=None,
41-
stdin=None,
42-
stdout=None,
43-
stderr=None,
44-
preexec_fn=None,
45-
close_fds=False,
46-
shell=False,
47-
cwd=None,
48-
env=None,
49-
universal_newlines=False,
50-
startupinfo=None,
51-
creationflags=0,
52-
):
53-
self._conf = args[3]
54-
55-
def communicate(self, input=None):
56-
if self._conf == "server":
57-
file_path = op.sep.join(
58-
[cur_dir, "data/mock_splunk/etc/system/default/server.conf"]
59-
)
60-
elif self._conf == "inputs":
61-
file_path = op.sep.join(
62-
[
63-
cur_dir,
64-
"data/mock_splunk/etc/apps/splunk_httpinput/local/inputs.conf",
65-
]
66-
)
67-
else:
68-
file_path = op.sep.join(
69-
[cur_dir, "data/mock_splunk/etc/system/default/web.conf"]
38+
def get_app_conf(confName, app, use_btool, app_path):
39+
if confName == "server":
40+
file_path = op.sep.join(
41+
[cur_dir, "data/mock_splunk/etc/system/default/server.conf"]
42+
)
43+
elif confName == "inputs":
44+
file_path = op.sep.join(
45+
[
46+
cur_dir,
47+
"data/mock_splunk/etc/apps/splunk_httpinput/local/inputs.conf",
48+
]
49+
)
50+
else:
51+
file_path = op.sep.join(
52+
[cur_dir, "data/mock_splunk/etc/system/default/web.conf"]
53+
)
54+
55+
with open(file_path) as fp:
56+
data = fp.read(), None
57+
58+
parser = ConfigParser(**{"strict": False})
59+
parser.optionxform = str
60+
parser.read_file(StringIO(data[0]))
61+
62+
out = {}
63+
for section in parser.sections():
64+
out[section] = {
65+
item[0]: item[1] for item in parser.items(section, raw=True)
66+
}
67+
return out
68+
69+
def make_splunk_gome(parts):
70+
relpath = os.path.normpath(os.path.join(*parts))
71+
basepath = ""
72+
etc_with_trailing_sep = os.path.join("etc", "")
73+
if (relpath == "etc") or relpath.startswith(etc_with_trailing_sep):
74+
try:
75+
basepath = os.environ["SPLUNK_ETC"]
76+
except KeyError:
77+
basepath = op.join(os.path.normpath(os.environ["SPLUNK_HOME"]), "etc")
78+
relpath = relpath[4:]
79+
else:
80+
basepath = os.path.normpath(os.environ["SPLUNK_HOME"])
81+
fullpath = os.path.normpath(os.path.join(basepath, relpath))
82+
if os.path.relpath(fullpath, basepath)[0:2] == "..":
83+
raise ValueError(
84+
'Illegal escape from parent directory "{}": {}'.format(
85+
basepath, fullpath
7086
)
87+
)
7188

72-
with open(file_path) as fp:
73-
return fp.read(), None
89+
return fullpath
7490

7591
splunk_home = op.join(cur_dir, "data/mock_splunk/")
7692
monkeypatch.setenv("SPLUNK_HOME", splunk_home)
7793
monkeypatch.setenv("SPLUNK_ETC", op.join(splunk_home, "etc"))
78-
monkeypatch.setattr(subprocess, "Popen", MockPopen)
94+
monkeypatch.setattr("solnlib.splunkenv.getAppConf", get_app_conf)
95+
monkeypatch.setattr("solnlib.splunkenv.mksplhomepath", make_splunk_gome)
7996

8097

8198
def mock_serverinfo(monkeypatch):

0 commit comments

Comments
 (0)