Skip to content

Commit 9ffee31

Browse files
committed
refractor changes
1 parent ec6907a commit 9ffee31

31 files changed

+393
-463
lines changed

splunklib/__init__.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import logging
1818

1919
DEFAULT_LOG_FORMAT = '%(asctime)s, Level=%(levelname)s, Pid=%(process)s, Logger=%(name)s, File=%(filename)s, ' \
20-
'Line=%(lineno)s, %(message)s'
20+
'Line=%(lineno)s, %(message)s'
2121
DEFAULT_DATE_FORMAT = '%Y-%m-%d %H:%M:%S %Z'
2222

2323

@@ -58,6 +58,22 @@ def ensure_str(s, encoding='utf-8', errors='strict'):
5858
raise TypeError(f"not expecting type '{type(s)}'")
5959

6060

61+
def ensure_text(s, encoding='utf-8', errors='strict'):
62+
"""
63+
- `str` -> `str`
64+
- `bytes` -> decoded to `str`
65+
"""
66+
if isinstance(s, bytes):
67+
return s.decode(encoding, errors)
68+
if isinstance(s, str):
69+
return s
70+
raise TypeError(f"not expecting type '{type(s)}'")
71+
72+
73+
def assertRegex(self, *args, **kwargs):
74+
return getattr(self, "assertRegex")(*args, **kwargs)
75+
76+
6177
__version_info__ = (1, 6, 19)
6278

6379
__version__ = ".".join(map(str, __version_info__))

splunklib/binding.py

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -169,15 +169,14 @@ def __new__(self, val='', skip_encode=False, encode_slash=False):
169169
if isinstance(val, UrlEncoded):
170170
# Don't urllib.quote something already URL encoded.
171171
return val
172-
elif skip_encode:
172+
if skip_encode:
173173
return str.__new__(self, val)
174-
elif encode_slash:
174+
if encode_slash:
175175
return str.__new__(self, parse.quote_plus(val))
176-
else:
177-
# When subclassing str, just call str.__new__ method
178-
# with your class and the value you want to have in the
179-
# new string.
180-
return str.__new__(self, parse.quote(val))
176+
# When subclassing str, just call str.__new__ method
177+
# with your class and the value you want to have in the
178+
# new string.
179+
return str.__new__(self, parse.quote(val))
181180

182181
def __add__(self, other):
183182
"""self + other
@@ -236,8 +235,7 @@ def _handle_auth_error(msg):
236235
except HTTPError as he:
237236
if he.status == 401:
238237
raise AuthenticationError(msg, he)
239-
else:
240-
raise
238+
raise
241239

242240

243241
def _authentication(request_fun):
@@ -305,8 +303,7 @@ def wrapper(self, *args, **kwargs):
305303
elif he.status == 401 and not self.autologin:
306304
raise AuthenticationError(
307305
"Request failed: Session is not logged in.", he)
308-
else:
309-
raise
306+
raise
310307

311308
return wrapper
312309

@@ -533,14 +530,14 @@ def _auth_headers(self):
533530
"""
534531
if self.has_cookies():
535532
return [("Cookie", _make_cookie_header(list(self.get_cookies().items())))]
536-
elif self.basic and (self.username and self.password):
533+
if self.basic and (self.username and self.password):
537534
encoded_username_password = b64encode(f"{self.username}:{self.password}".encode('utf-8')).decode('ascii')
538535
token = f'Basic {encoded_username_password}'
539536
return [("Authorization", token)]
540-
elif self.bearerToken:
537+
if self.bearerToken:
541538
token = f"Bearer {self.bearerToken}"
542539
return [("Authorization", token)]
543-
elif self.token is _NoAuthenticationToken:
540+
if self.token is _NoAuthenticationToken:
544541
return []
545542
else:
546543
# Ensure the token is properly formatted
@@ -925,8 +922,7 @@ def login(self):
925922
except HTTPError as he:
926923
if he.status == 401:
927924
raise AuthenticationError("Login failed.", he)
928-
else:
929-
raise
925+
raise
930926

931927
def logout(self):
932928
"""Forgets the current session token, and cookies."""
@@ -1304,9 +1300,8 @@ def request(self, url, message, **kwargs):
13041300
except Exception:
13051301
if self.retries <= 0:
13061302
raise
1307-
else:
1308-
time.sleep(self.retryDelay)
1309-
self.retries -= 1
1303+
time.sleep(self.retryDelay)
1304+
self.retries -= 1
13101305
response = record(response)
13111306
if 400 <= response.status:
13121307
raise HTTPError(response)

splunklib/client.py

Lines changed: 26 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -212,10 +212,9 @@ def _load_atom_entries(response):
212212
# its state wrapped in another element, but at the top level.
213213
# For example, in XML, it returns <entry>...</entry> instead of
214214
# <feed><entry>...</entry></feed>.
215-
else:
216-
entries = r.get('entry', None)
217-
if entries is None: return None
218-
return entries if isinstance(entries, list) else [entries]
215+
entries = r.get('entry', None)
216+
if entries is None: return None
217+
return entries if isinstance(entries, list) else [entries]
219218

220219

221220
# Load the sid from the body of the given response
@@ -530,8 +529,7 @@ def modular_input_kinds(self):
530529
"""
531530
if self.splunk_version >= (5,):
532531
return ReadOnlyCollection(self, PATH_MODULAR_INPUTS, item=ModularInputKind)
533-
else:
534-
raise IllegalOperationException("Modular inputs are not supported before Splunk version 5.")
532+
raise IllegalOperationException("Modular inputs are not supported before Splunk version 5.")
535533

536534
@property
537535
def storage_passwords(self):
@@ -926,7 +924,6 @@ def __init__(self, service, path, **kwargs):
926924
self._state = None
927925
if not kwargs.get('skip_refresh', False):
928926
self.refresh(kwargs.get('state', None)) # "Prefresh"
929-
return
930927

931928
def __contains__(self, item):
932929
try:
@@ -963,10 +960,9 @@ def __getattr__(self, key):
963960
# case we try to find it in self.content and then self.defaults.
964961
if key in self.state.content:
965962
return self.state.content[key]
966-
elif key in self.defaults:
963+
if key in self.defaults:
967964
return self.defaults[key]
968-
else:
969-
raise AttributeError(key)
965+
raise AttributeError(key)
970966

971967
def __getitem__(self, key):
972968
# getattr attempts to find a field on the object in the normal way,
@@ -1022,8 +1018,7 @@ def _proper_namespace(self, owner=None, app=None, sharing=None):
10221018
return (self._state.access.owner,
10231019
self._state.access.app,
10241020
self._state.access.sharing)
1025-
else:
1026-
return (self.service.namespace['owner'],
1021+
return (self.service.namespace['owner'],
10271022
self.service.namespace['app'],
10281023
self.service.namespace['sharing'])
10291024
else:
@@ -1272,15 +1267,13 @@ def __getitem__(self, key):
12721267
if len(entries) > 1:
12731268
raise AmbiguousReferenceException(
12741269
f"Found multiple entities named '{key}'; please specify a namespace.")
1275-
elif len(entries) == 0:
1270+
if len(entries) == 0:
12761271
raise KeyError(key)
1277-
else:
1278-
return entries[0]
1272+
return entries[0]
12791273
except HTTPError as he:
12801274
if he.status == 404: # No entity matching key and namespace.
12811275
raise KeyError(key)
1282-
else:
1283-
raise
1276+
raise
12841277

12851278
def __iter__(self, **kwargs):
12861279
"""Iterate over the entities in the collection.
@@ -1344,10 +1337,9 @@ def _entity_path(self, state):
13441337
raw_path = parse.unquote(state.links.alternate)
13451338
if 'servicesNS/' in raw_path:
13461339
return _trailing(raw_path, 'servicesNS/', '/', '/')
1347-
elif 'services/' in raw_path:
1340+
if 'services/' in raw_path:
13481341
return _trailing(raw_path, 'services/')
1349-
else:
1350-
return raw_path
1342+
return raw_path
13511343

13521344
def _load_list(self, response):
13531345
"""Converts *response* to a list of entities.
@@ -1596,14 +1588,13 @@ def create(self, name, **params):
15961588
# This endpoint doesn't return the content of the new
15971589
# item. We have to go fetch it ourselves.
15981590
return self[name]
1599-
else:
1600-
entry = atom.entry
1601-
state = _parse_atom_entry(entry)
1602-
entity = self.item(
1603-
self.service,
1604-
self._entity_path(state),
1605-
state=state)
1606-
return entity
1591+
entry = atom.entry
1592+
state = _parse_atom_entry(entry)
1593+
entity = self.item(
1594+
self.service,
1595+
self._entity_path(state),
1596+
state=state)
1597+
return entity
16071598

16081599
def delete(self, name, **params):
16091600
"""Deletes a specified entity from the collection.
@@ -1644,8 +1635,7 @@ def delete(self, name, **params):
16441635
# KeyError.
16451636
if he.status == 404:
16461637
raise KeyError(f"No such entity {name}")
1647-
else:
1648-
raise
1638+
raise
16491639
return self
16501640

16511641
def get(self, name="", owner=None, app=None, sharing=None, **query):
@@ -1749,8 +1739,7 @@ def __contains__(self, key):
17491739
except HTTPError as he:
17501740
if he.status == 404: # No entity matching key
17511741
return False
1752-
else:
1753-
raise
1742+
raise
17541743

17551744
def create(self, name):
17561745
""" Creates a configuration file named *name*.
@@ -1771,10 +1760,9 @@ def create(self, name):
17711760
response = self.post(__conf=name)
17721761
if response.status == 303:
17731762
return self[name]
1774-
elif response.status == 201:
1763+
if response.status == 201:
17751764
return ConfigurationFile(self.service, PATH_CONF % name, item=Stanza, state={'title': name})
1776-
else:
1777-
raise ValueError(f"Unexpected status code {response.status} returned from creating a stanza")
1765+
raise ValueError(f"Unexpected status code {response.status} returned from creating a stanza")
17781766

17791767
def delete(self, key):
17801768
"""Raises `IllegalOperationException`."""
@@ -2203,7 +2191,7 @@ def update(self, **kwargs):
22032191

22042192
if 'restrictToHost' in kwargs:
22052193
raise IllegalOperationException("Cannot set restrictToHost on an existing input with the SDK.")
2206-
elif 'restrictToHost' in self._state.content and self.kind != 'udp':
2194+
if 'restrictToHost' in self._state.content and self.kind != 'udp':
22072195
to_update['restrictToHost'] = self._state.content['restrictToHost']
22082196

22092197
# Do the actual update operation.
@@ -2235,10 +2223,9 @@ def __getitem__(self, key):
22352223
entries = self._load_list(response)
22362224
if len(entries) > 1:
22372225
raise AmbiguousReferenceException(f"Found multiple inputs of kind {kind} named {key}.")
2238-
elif len(entries) == 0:
2226+
if len(entries) == 0:
22392227
raise KeyError((key, kind))
2240-
else:
2241-
return entries[0]
2228+
return entries[0]
22422229
except HTTPError as he:
22432230
if he.status == 404: # No entity matching kind and key
22442231
raise KeyError((key, kind))

splunklib/data.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,9 @@ def load(text, match=None):
8888
count = len(items)
8989
if count == 0:
9090
return None
91-
elif count == 1:
91+
if count == 1:
9292
return load_root(items[0], nametable)
93-
else:
94-
return [load_root(item, nametable) for item in items]
93+
return [load_root(item, nametable) for item in items]
9594

9695

9796
# Load the attributes of the given element.

splunklib/modularinput/argument.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class Argument:
1818

1919
"""Class representing an argument to a modular input kind.
2020
21-
``Argument`` is meant to be used with ``Scheme`` to generate an XML
21+
``Argument`` is meant to be used with ``Scheme`` to generate an XML
2222
definition of the modular input kind that Splunk understands.
2323
2424
``name`` is the only required parameter for the constructor.

splunklib/modularinput/event.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414

1515
from io import TextIOBase
1616
import xml.etree.ElementTree as ET
17-
from splunklib.six import ensure_text
17+
18+
from splunklib import ensure_text
1819

1920

2021
class Event:

splunklib/modularinput/event_writer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import sys
1616

17-
from splunklib.six import ensure_str
17+
from splunklib import ensure_str
1818
from .event import ET
1919

2020

splunklib/modularinput/script.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def run_script(self, args, event_writer, input_stream):
6868
event_writer.close()
6969
return 0
7070

71-
elif str(args[1]).lower() == "--scheme":
71+
if str(args[1]).lower() == "--scheme":
7272
# Splunk has requested XML specifying the scheme for this
7373
# modular input Return it and exit.
7474
scheme = self.get_scheme()
@@ -77,9 +77,8 @@ def run_script(self, args, event_writer, input_stream):
7777
EventWriter.FATAL,
7878
"Modular input script returned a null scheme.")
7979
return 1
80-
else:
81-
event_writer.write_xml_document(scheme.to_xml())
82-
return 0
80+
event_writer.write_xml_document(scheme.to_xml())
81+
return 0
8382

8483
elif args[1].lower() == "--validate-arguments":
8584
validation_definition = ValidationDefinition.parse(input_stream)

splunklib/modularinput/utils.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,13 @@ def xml_compare(expected, found):
4545
if (expected.text is None or expected.text.strip() == "") \
4646
and (found.text is None or found.text.strip() == ""):
4747
return True
48-
else:
49-
return expected.tag == found.tag and expected.text == found.text \
48+
return expected.tag == found.tag and expected.text == found.text \
5049
and expected.attrib == found.attrib
5150

5251
def parse_parameters(param_node):
5352
if param_node.tag == "param":
5453
return param_node.text
55-
elif param_node.tag == "param_list":
54+
if param_node.tag == "param_list":
5655
parameters = []
5756
for mvp in param_node:
5857
parameters.append(mvp.text)

0 commit comments

Comments
 (0)