Skip to content

Commit 523aefc

Browse files
committed
Added test case and example for Optional Retry
1 parent 7d4dd58 commit 523aefc

File tree

3 files changed

+69
-10
lines changed

3 files changed

+69
-10
lines changed

examples/optional_retry.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env python
2+
#
3+
# Copyright 2011-2015 Splunk, Inc.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License"): you may
6+
# not use this file except in compliance with the License. You may obtain
7+
# a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14+
# License for the specific language governing permissions and limitations
15+
# under the License.
16+
17+
"""A command line utility that shows how to use the optional retries parameters, "retries" defines the number of time
18+
an API call should be retried before erroring out and "retryBackoff" defines the time to wait in-between the API
19+
retry calls default value is 10 seconds.The example is shown using the "services" API to get list of the services
20+
after a splunk restart, API call will normally fail while Splunk in restart mode but with "retries" set it will
21+
prevent the error out """
22+
23+
from __future__ import absolute_import
24+
from __future__ import print_function
25+
import sys, os
26+
27+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
28+
29+
from splunklib.client import connect
30+
31+
try:
32+
from utils import parse
33+
except ImportError:
34+
raise Exception("Add the SDK repository to your PYTHONPATH to run the examples "
35+
"(e.g., export PYTHONPATH=~/splunk-sdk-python.")
36+
37+
38+
def main():
39+
opts = parse([], {}, ".env")
40+
kwargs = opts.kwargs.copy()
41+
kwargs.update({'retries': 5, 'retryBackoff': 5})
42+
service = connect(**kwargs)
43+
service.restart(timeout=10)
44+
print(service.get("/services"))
45+
46+
47+
if __name__ == "__main__":
48+
main()

tests/test_service.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,16 @@ def test_hec_event(self):
177177
response = event_collector_endpoint.post("", body=json.dumps(msg))
178178
self.assertEqual(response.status, 200)
179179

180+
181+
class TestOptionalRetry(unittest.TestCase):
182+
180183
def test_optional_retry(self):
181-
service = client.connect(retries=5, retryBackoff=5, **self.opts.kwargs)
182-
service.restart(timeout=20) # less timeout so the optional retry logic is executed
183-
self.assertEqual(service.get("/services").status, 200)
184+
opts = testlib.parse([], {}, ".env")
185+
kwargs = opts.kwargs.copy()
186+
kwargs.update({'retries': 5, 'retryBackoff': 5})
187+
self.service = client.connect(**kwargs)
188+
self.service.restart(timeout=10) # timeout value kept lower than actual time needed for Splunk to restart
189+
self.assertEqual(self.service.get("/services").status, 200)
184190

185191

186192
class TestCookieAuthentication(unittest.TestCase):

tests/testlib.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,15 @@
2121

2222
import sys
2323
from splunklib import six
24+
2425
# Run the test suite on the SDK without installing it.
2526
sys.path.insert(0, '../')
2627
sys.path.insert(0, '../examples')
2728

2829
import splunklib.client as client
2930
from time import sleep
3031
from datetime import datetime, timedelta
32+
3133
try:
3234
import unittest2 as unittest
3335
except ImportError:
@@ -43,17 +45,21 @@
4345
import time
4446

4547
import logging
48+
4649
logging.basicConfig(
4750
filename='test.log',
4851
level=logging.DEBUG,
4952
format="%(asctime)s:%(levelname)s:%(message)s")
5053

54+
5155
class NoRestartRequiredError(Exception):
5256
pass
5357

58+
5459
class WaitTimedOutError(Exception):
5560
pass
5661

62+
5763
def to_bool(x):
5864
if x == '1':
5965
return True
@@ -64,7 +70,7 @@ def to_bool(x):
6470

6571

6672
def tmpname():
67-
name = 'delete-me-' + str(os.getpid()) + str(time.time()).replace('.','-')
73+
name = 'delete-me-' + str(os.getpid()) + str(time.time()).replace('.', '-')
6874
return name
6975

7076

@@ -77,7 +83,7 @@ def wait(predicate, timeout=60, pause_time=0.5):
7783
logging.debug("wait timed out after %d seconds", timeout)
7884
raise WaitTimedOutError
7985
sleep(pause_time)
80-
logging.debug("wait finished after %s seconds", datetime.now()-start)
86+
logging.debug("wait finished after %s seconds", datetime.now() - start)
8187

8288

8389
class SDKTestCase(unittest.TestCase):
@@ -94,7 +100,7 @@ def assertEventuallyTrue(self, predicate, timeout=30, pause_time=0.5,
94100
logging.debug("wait timed out after %d seconds", timeout)
95101
self.fail(timeout_message)
96102
sleep(pause_time)
97-
logging.debug("wait finished after %s seconds", datetime.now()-start)
103+
logging.debug("wait finished after %s seconds", datetime.now() - start)
98104

99105
def check_content(self, entity, **kwargs):
100106
for k, v in six.iteritems(kwargs):
@@ -163,12 +169,11 @@ def fake_splunk_version(self, version):
163169
finally:
164170
self.service._splunk_version = original_version
165171

166-
167172
def install_app_from_collection(self, name):
168173
collectionName = 'sdkappcollection'
169174
if collectionName not in self.service.apps:
170175
raise ValueError("sdk-test-application not installed in splunkd")
171-
appPath = self.pathInApp(collectionName, ["build", name+".tar"])
176+
appPath = self.pathInApp(collectionName, ["build", name + ".tar"])
172177
kwargs = {"update": True, "name": appPath, "filename": True}
173178

174179
try:
@@ -235,13 +240,13 @@ def setUpClass(cls):
235240
cls.opts = parse([], {}, ".env")
236241

237242
# Before we start, make sure splunk doesn't need a restart.
238-
service = client.connect(retries=5, retryBackoff=10, **cls.opts.kwargs)
243+
service = client.connect(retries=5, **cls.opts.kwargs)
239244
if service.restart_required:
240245
service.restart(timeout=120)
241246

242247
def setUp(self):
243248
unittest.TestCase.setUp(self)
244-
self.service = client.connect(**self.opts.kwargs)
249+
self.service = client.connect(retries=5, **self.opts.kwargs)
245250
# If Splunk is in a state requiring restart, go ahead
246251
# and restart. That way we'll be sane for the rest of
247252
# the test.

0 commit comments

Comments
 (0)