-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathtestlib.py
More file actions
274 lines (220 loc) · 9.1 KB
/
testlib.py
File metadata and controls
274 lines (220 loc) · 9.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# Copyright © 2011-2026 Splunk, Inc.
#
# 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.
"""Shared unit test utilities."""
import contextlib
import os
import time
import logging
import sys
# Run the test suite on the SDK without installing it.
sys.path.insert(0, "../")
from time import sleep
from datetime import datetime, timedelta
import unittest
from utils import parse
from splunklib import client
logging.basicConfig(
filename="test.log",
level=logging.DEBUG,
format="%(asctime)s:%(levelname)s:%(message)s",
)
class NoRestartRequiredError(Exception):
pass
class WaitTimedOutError(Exception):
pass
def to_bool(x):
if x == "1":
return True
if x == "0":
return False
raise ValueError(f"Not a boolean value: {x}")
def tmpname():
name = "delete-me-" + str(os.getpid()) + str(time.time()).replace(".", "-")
return name
def wait(predicate, timeout=60, pause_time=0.5):
assert pause_time < timeout
start = datetime.now()
diff = timedelta(seconds=timeout)
while not predicate():
if datetime.now() - start > diff:
logging.debug("wait timed out after %d seconds", timeout)
raise WaitTimedOutError
sleep(pause_time)
logging.debug("wait finished after %s seconds", datetime.now() - start)
def restart_splunk(service: client.Service):
service.restart(timeout=120)
# Give Splunk some additional time. In our test suite, a subsequent
# restart shortly after the initial restart can cause Splunk to crash
# and fail to start.
sleep(15)
class SDKTestCase(unittest.TestCase):
restart_already_required = False
installedApps = []
def assertEventuallyTrue(
self,
predicate,
timeout=30,
pause_time=0.5,
timeout_message="Operation timed out.",
):
assert pause_time < timeout
start = datetime.now()
diff = timedelta(seconds=timeout)
while not predicate():
if datetime.now() - start > diff:
logging.debug("wait timed out after %d seconds", timeout)
self.fail(timeout_message)
sleep(pause_time)
logging.debug("wait finished after %s seconds", datetime.now() - start)
def check_content(self, entity, **kwargs):
for k, v in kwargs:
self.assertEqual(entity[k], str(v))
def check_entity(self, entity):
assert entity is not None
self.assertTrue(entity.name is not None)
self.assertTrue(entity.path is not None)
self.assertTrue(entity.state is not None)
self.assertTrue(entity.content is not None)
# Verify access metadata
assert entity.access is not None
entity.access.app
entity.access.owner
entity.access.sharing
# Verify content metadata
# In some cases, the REST API does not return field metadata for when
# entities are intially listed by a collection, so we refresh to make
# sure the metadata is available.
entity.refresh()
self.assertTrue(isinstance(entity.fields.required, list))
self.assertTrue(isinstance(entity.fields.optional, list))
self.assertTrue(isinstance(entity.fields.wildcard, list))
# Verify that all required fields appear in entity content
for field in entity.fields.required:
try:
self.assertTrue(field in entity.content)
except:
# Check for known exceptions
if "configs/conf-times" in entity.path:
if field in ["is_sub_menu"]:
continue
raise
def restart_splunk(self):
restart_splunk(self.service)
def clear_restart_message(self):
"""Tell Splunk to forget that it needs to be restarted.
This is used mostly in cases such as deleting a temporary application.
Splunk asks to be restarted when that happens, but unless the application
contained modular input kinds or the like, it isn't necessary.
"""
if not self.service.restart_required:
raise ValueError("Tried to clear restart message when there was none.")
try:
self.service.delete("messages/restart_required")
except client.HTTPError as he:
if he.status != 404:
raise
@contextlib.contextmanager
def fake_splunk_version(self, version):
original_version = self.service.splunk_version
try:
self.service._splunk_version = version
yield
finally:
self.service._splunk_version = original_version
def install_app_from_collection(self, name):
collectionName = "sdkappcollection"
if collectionName not in self.service.apps:
raise ValueError("sdk-test-application not installed in splunkd")
appPath = self.pathInApp(collectionName, ["build", name + ".tar"])
kwargs = {"update": True, "name": appPath, "filename": True}
try:
self.service.post("apps/local", **kwargs)
except client.HTTPError as he:
if he.status == 400:
raise IOError(f"App {name} not found in app collection")
if self.service.restart_required:
self.restart_splunk()
self.installedApps.append(name)
def app_collection_installed(self):
collectionName = "sdkappcollection"
return collectionName in self.service.apps
def pathInApp(self, appName, pathComponents):
r"""Return a path to *pathComponents* in *appName*.
`pathInApp` is used to refer to files in applications installed with
`install_app_from_collection`. For example, the app `file_to_upload` in
the collection contains `log.txt`. To get the path to it, call::
pathInApp('file_to_upload', ['log.txt'])
The path to `setup.xml` in `has_setup_xml` would be fetched with::
pathInApp('has_setup_xml', ['default', 'setup.xml'])
`pathInApp` figures out the correct separator to use (based on whether
splunkd is running on Windows or Unix) and joins the elements in
*pathComponents* into a path relative to the application specified by
*appName*.
*pathComponents* should be a list of strings giving the components.
This function will try to figure out the correct separator (/ or \)
for the platform that splunkd is running on and construct the path
as needed.
:return: A string giving the path.
"""
splunkHome = self.service.settings["SPLUNK_HOME"]
if "\\" in splunkHome:
# This clause must come first, since Windows machines may
# have mixed \ and / in their paths.
separator = "\\"
elif "/" in splunkHome:
separator = "/"
else:
raise ValueError(
"No separators in $SPLUNK_HOME. Can't determine what file separator to use."
)
appPath = separator.join([splunkHome, "etc", "apps", appName] + pathComponents)
return appPath
@classmethod
def setUpClass(cls):
cls.opts = parse([], {}, ".env")
cls.opts.kwargs.update({"retries": 3})
# Before we start, make sure splunk doesn't need a restart.
service = client.connect(**cls.opts.kwargs)
if service.restart_required:
self.restart_splunk()
def setUp(self):
unittest.TestCase.setUp(self)
self.opts.kwargs.update({"retries": 3})
self.service = client.connect(**self.opts.kwargs)
# If Splunk is in a state requiring restart, go ahead
# and restart. That way we'll be sane for the rest of
# the test.
if self.service.restart_required:
self.restart_splunk()
logging.debug(
"Connected to splunkd version %s",
".".join(str(x) for x in self.service.splunk_version),
)
def tearDown(self):
from splunklib.binding import HTTPError
if self.service.restart_required:
self.fail("Test left Splunk in a state requiring a restart.")
for appName in self.installedApps:
if appName in self.service.apps:
try:
self.service.apps.delete(appName)
wait(lambda: appName not in self.service.apps)
except HTTPError as error:
if not (os.name == "nt" and error.status == 500):
raise
print(
f"Ignoring failure to delete {appName} during tear down: {error}"
)
if self.service.restart_required:
self.clear_restart_message()